Search in sources :

Example 1 with InvalidRecordException

use of exceptions.InvalidRecordException in project ASCIIGenome by dariober.

the class TrackIntervalFeature method featureIsVisible.

/**
 * Return true if string is visible, i.e. it
 * passes the regex filters. Note that regex filters are applied to the raw string.
 * @throws InvalidGenomicCoordsException
 * @throws IOException
 */
protected Boolean featureIsVisible(String x) throws InvalidGenomicCoordsException, IOException {
    if (x.contains("__ignore_me__")) {
        return false;
    }
    boolean showIt = true;
    if (this.getShowRegex() != null && !this.getShowRegex().equals(Filter.DEFAULT_SHOW_REGEX.getValue())) {
        showIt = this.getShowRegex().matcher(x).find();
    }
    boolean hideIt = false;
    if (!this.getHideRegex().pattern().isEmpty()) {
        hideIt = this.getHideRegex().matcher(x).find();
    }
    Boolean isVisible = false;
    if (showIt && !hideIt) {
        isVisible = true;
    } else {
        // If feature is not visible, no need to go on as there is no way to bring it back.
        return false;
    }
    // Awk
    try {
        isVisible = Utils.passAwkFilter(x, this.getAwk());
    } catch (Exception e) {
        System.err.print(Utils.padEndMultiLine("Invalid awk script.", this.getGc().getUserWindowSize()));
        try {
            this.setAwk("");
        } catch (ClassNotFoundException | InvalidRecordException | SQLException e1) {
            e1.printStackTrace();
        }
        throw new InvalidGenomicCoordsException();
    }
    if (isVisible == null) {
        System.err.print(Utils.padEndMultiLine("Awk output must be either empty or equal to input.", this.getGc().getUserWindowSize()));
        try {
            // Remove the faulty awk script.
            this.setAwk("");
        } catch (ClassNotFoundException | IOException | InvalidRecordException | SQLException e) {
        // 
        }
        throw new InvalidGenomicCoordsException();
    }
    return isVisible;
}
Also used : SQLException(java.sql.SQLException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException) IOException(java.io.IOException) InvalidRecordException(exceptions.InvalidRecordException) InvalidCommandLineException(exceptions.InvalidCommandLineException) InvalidColourException(exceptions.InvalidColourException) InvalidRecordException(exceptions.InvalidRecordException) SQLException(java.sql.SQLException) IOException(java.io.IOException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException)

Example 2 with InvalidRecordException

use of exceptions.InvalidRecordException in project ASCIIGenome by dariober.

the class MakeTabixIndex method sortByChromThenPos.

/**
 * Sort file by columns chrom (text) and pos (int). chromIdx and posIdx are 1-based
 * indexes for the chrom and pos column. For bed use 1 and 2 respectively. For use GTF/GFF  1 and 4.
 * Comment lines, starting with #, are returned as they are. Reading stops if the line ##FASTA is found.
 */
private void sortByChromThenPos(String unsorted, File sorted, TabixFormat fmt) throws SQLException, InvalidRecordException, IOException, ClassNotFoundException {
    int chromIdx = 1;
    int posIdx = 2;
    if (fmt.equals(TabixFormat.BED)) {
    // 
    } else if (fmt.equals(TabixFormat.GFF)) {
        posIdx = 4;
    } else if (fmt.equals(TabixFormat.VCF)) {
        posIdx = 2;
    } else {
        System.err.println("Invalid format found");
        throw new InvalidRecordException();
    }
    Connection conn = this.createSQLiteDb("data");
    PreparedStatement stmtInsert = conn.prepareStatement("INSERT INTO data (contig, pos, posEnd, line) VALUES (?, ?, ?, ?)");
    BufferedReader br = Utils.reader(unsorted);
    BufferedWriter wr = new BufferedWriter(new FileWriter(sorted));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.trim().startsWith("##FASTA")) {
            break;
        }
        if (line.trim().startsWith("#")) {
            wr.write(line + "\n");
            continue;
        }
        String[] tabs = line.split("\t");
        stmtInsert.setString(1, tabs[chromIdx - 1]);
        stmtInsert.setInt(2, Integer.parseInt(tabs[posIdx - 1]));
        if (fmt.equals(TabixFormat.VCF)) {
            stmtInsert.setInt(3, 0);
        } else {
            stmtInsert.setInt(3, Integer.parseInt(tabs[posIdx]));
        }
        stmtInsert.setString(4, line.replaceAll("\n$", ""));
        stmtInsert.executeUpdate();
    }
    stmtInsert.close();
    br.close();
    PreparedStatement stmtSelect = conn.prepareStatement("SELECT * FROM data ORDER BY contig, pos, posEnd");
    ResultSet rs = stmtSelect.executeQuery();
    while (rs.next()) {
        wr.write(rs.getString("line") + "\n");
    }
    conn.commit();
    stmtSelect.close();
    wr.close();
    this.sqliteFile.delete();
}
Also used : FileWriter(java.io.FileWriter) Connection(java.sql.Connection) BufferedReader(java.io.BufferedReader) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) InvalidRecordException(exceptions.InvalidRecordException) BufferedWriter(java.io.BufferedWriter)

Example 3 with InvalidRecordException

use of exceptions.InvalidRecordException in project ASCIIGenome by dariober.

the class MakeTabixIndex method addLineToIndex.

/**
 * Set vcfHeader and vcfCodec to null if reading non-vcf line.
 */
private void addLineToIndex(String line, TabixIndexCreator indexCreator, long filePosition, TabixFormat fmt, VCFHeader vcfHeader, VCFCodec vcfCodec) throws InvalidRecordException {
    if (fmt.equals(TabixFormat.BED)) {
        BedLineCodec bedCodec = new BedLineCodec();
        BedLine bed = bedCodec.decode(line);
        indexCreator.addFeature(bed, filePosition);
    } else if (fmt.equals(TabixFormat.GFF)) {
        GtfLine gtf = new GtfLine(line.split("\t"));
        indexCreator.addFeature(gtf, filePosition);
    } else if (fmt.equals(TabixFormat.VCF)) {
        VariantContext vcf = vcfCodec.decode(line);
        indexCreator.addFeature(vcf, filePosition);
    } else {
        System.err.println("Unexpected TabixFormat: " + fmt.sequenceColumn + " " + fmt.startPositionColumn);
        throw new InvalidRecordException();
    }
}
Also used : GtfLine(utils.GtfLine) VariantContext(htsjdk.variant.variantcontext.VariantContext) InvalidRecordException(exceptions.InvalidRecordException) BedLineCodec(utils.BedLineCodec) BedLine(utils.BedLine)

Example 4 with InvalidRecordException

use of exceptions.InvalidRecordException in project ASCIIGenome by dariober.

the class MakeTabixIndex method blockCompressAndIndex.

/**
 * Block compress input file and create associated tabix index.
 * @throws IOException
 * @throws InvalidRecordException
 */
private void blockCompressAndIndex(String intab, File bgzfOut, TabixFormat fmt) throws IOException, InvalidRecordException {
    LineIterator lin = utils.IOUtils.openURIForLineIterator(intab);
    BlockCompressedOutputStream writer = new BlockCompressedOutputStream(bgzfOut);
    long filePosition = writer.getFilePointer();
    TabixIndexCreator indexCreator = new TabixIndexCreator(fmt);
    boolean first = true;
    // This is relevant to vcf files only: Prepare header and codec
    // ------------------------------------------------------------
    VCFHeader vcfHeader = null;
    VCFCodec vcfCodec = null;
    if (fmt.equals(TabixFormat.VCF)) {
        try {
            VCFFileReader vcfr = new VCFFileReader(new File(intab), false);
            // new VCFHeader();
            vcfHeader = vcfr.getFileHeader();
            vcfr.close();
        } catch (MalformedFeatureFile e) {
            vcfHeader = new VCFHeader();
        }
        vcfCodec = new VCFCodec();
        vcfCodec.setVCFHeader(vcfHeader, Utils.getVCFHeaderVersion(vcfHeader));
    }
    // ------------------------------------------------------------
    int nWarnings = 10;
    while (lin.hasNext()) {
        String line = lin.next().trim();
        try {
            if (line.isEmpty() || line.startsWith("track ")) {
                continue;
            }
            if (line.startsWith("#")) {
                writer.write((line + "\n").getBytes());
                filePosition = writer.getFilePointer();
                continue;
            }
            if (line.startsWith("##FASTA")) {
                break;
            }
            if (first && !fmt.equals(TabixFormat.VCF)) {
                String dummy = this.makeDummyLine(line, fmt);
                addLineToIndex(dummy, indexCreator, filePosition, fmt, null, null);
                writer.write(dummy.getBytes());
                writer.write('\n');
                filePosition = writer.getFilePointer();
                first = false;
            }
            addLineToIndex(line, indexCreator, filePosition, fmt, vcfHeader, vcfCodec);
            writer.write(line.getBytes());
            writer.write('\n');
            filePosition = writer.getFilePointer();
        } catch (Exception e) {
            if (e.getMessage().contains("added out sequence of order") || e.getMessage().contains("Features added out of order")) {
                // Get a string marker for out-of-order from htsjdk/tribble/index/tabix/TabixIndexCreator.java
                throw new InvalidRecordException();
            }
            if (nWarnings >= 0) {
                System.err.println("Warning: " + e.getMessage() + ". Skipping:\n" + line);
            }
            if (nWarnings == 0) {
                System.err.println("Additional warnings will not be show.");
            }
            nWarnings--;
        }
    }
    writer.flush();
    Index index = indexCreator.finalizeIndex(writer.getFilePointer());
    index.writeBasedOnFeatureFile(bgzfOut);
    writer.close();
    CloserUtil.close(lin);
}
Also used : VCFCodec(htsjdk.variant.vcf.VCFCodec) BlockCompressedOutputStream(htsjdk.samtools.util.BlockCompressedOutputStream) VCFFileReader(htsjdk.variant.vcf.VCFFileReader) TabixIndexCreator(htsjdk.tribble.index.tabix.TabixIndexCreator) Index(htsjdk.tribble.index.Index) MalformedFeatureFile(htsjdk.tribble.TribbleException.MalformedFeatureFile) LineIterator(htsjdk.tribble.readers.LineIterator) InvalidRecordException(exceptions.InvalidRecordException) SQLException(java.sql.SQLException) IOException(java.io.IOException) VCFHeader(htsjdk.variant.vcf.VCFHeader) MalformedFeatureFile(htsjdk.tribble.TribbleException.MalformedFeatureFile) File(java.io.File) InvalidRecordException(exceptions.InvalidRecordException)

Example 5 with InvalidRecordException

use of exceptions.InvalidRecordException in project ASCIIGenome by dariober.

the class InteractiveInput method processInput.

/**
 * Parse the input list of commands to print information or modify the input TrackProcessor.
 * @throws IOException
 * @throws InvalidGenomicCoordsException
 * @throws InvalidCommandLineException
 * @throws SQLException
 * @throws InvalidRecordException
 * @throws ClassNotFoundException
 */
protected TrackProcessor processInput(String cmdConcatInput, TrackProcessor proc, int debug) throws InvalidGenomicCoordsException, IOException, ClassNotFoundException, InvalidRecordException, SQLException, InvalidCommandLineException {
    cmdConcatInput = cmdConcatInput.replaceAll("//.*", "").trim();
    int terminalWidth = Utils.getTerminalWidth();
    // cmdInputList: List of individual commands in tokens to be issued.
    // E.g.: [ ["zi"],
    // ["-F", "16"],
    // ["mapq", "10"] ]
    // Don't check the validity of each cmd now. Execute one by one and if anything goes wrong
    // reset interactiveInputExitCode = 1 (or else other than 0) so that console input is asked again. Of course, what is executed is not
    // rolled back.
    List<String> cmdInputChainList = new ArrayList<String>();
    // For splitting at delimiter (&&) and ignore delimiters inside single quotes.
    for (String cmd : Splitter.on(Pattern.compile("&&(?=([^']*'[^']*')*[^']*$)")).trimResults().omitEmptyStrings().split(cmdConcatInput)) {
        cmdInputChainList.add(cmd);
    }
    if (cmdInputChainList.size() >= 2 && cmdInputChainList.get(0).startsWith("setConfig ")) {
        // This is to refresh the screen and actually set the new color
        cmdInputChainList.add("+0");
    }
    String fasta = proc.getGenomicCoordsHistory().current().getFastaFile();
    SAMSequenceDictionary samSeqDict = proc.getGenomicCoordsHistory().current().getSamSeqDict();
    // Messages that may be sent from the various methods.
    String messages = "";
    for (String cmdString : cmdInputChainList) {
        List<String> cmdTokens = Utils.tokenize(cmdString, " ");
        // If something goes wrong this will change
        this.interactiveInputExitCode = ExitCode.CLEAN;
        try {
            // * These commands only print info or do stuff without editing the GenomicCoordinates or the Tracks:
            if (cmdTokens.get(0).equals("h") || cmdTokens.get(0).equals("-h")) {
                System.err.println(Utils.padEndMultiLine(CommandList.briefHelp(), proc.getWindowSize()));
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.size() >= 2 && cmdTokens.get(1).equals("-h")) {
                // Help on this command
                String help = Utils.padEndMultiLine("\n" + CommandList.getHelpForCommand(cmdTokens.get(0)), proc.getWindowSize());
                System.err.println(help);
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("posHistory")) {
                this.posHistory(cmdTokens, proc.getGenomicCoordsHistory().getCurrentSessionHistory(), proc.getWindowSize());
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("history")) {
                String hist = Utils.padEndMultiLine(this.cmdHistoryToString(cmdTokens), proc.getWindowSize());
                System.err.println(hist);
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("show")) {
                this.interactiveInputExitCode = this.show(cmdTokens, proc);
            } else if (cmdTokens.get(0).equals("explainSamFlag")) {
                this.interactiveInputExitCode = this.explainSamFlag(cmdTokens, proc);
            } else if (cmdTokens.get(0).equals("sys")) {
                this.execSysCmd(cmdString, proc.getWindowSize());
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("recentlyOpened")) {
                String opened = Utils.padEndMultiLine(proc.getTrackSet().showRecentlyOpened(cmdTokens), proc.getWindowSize());
                System.out.println(opened);
                this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
            } else if (cmdTokens.get(0).equals("setConfig")) {
                try {
                    this.setConfigOpt(cmdTokens);
                    this.interactiveInputExitCode = ExitCode.CLEAN;
                } catch (Exception e) {
                    System.err.println(Utils.padEndMultiLine("Unable to set configuration", proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    if (debug > 0) {
                        e.printStackTrace();
                    }
                }
            } else if (cmdTokens.get(0).equals("save")) {
                List<String> args = new ArrayList<String>(cmdTokens);
                proc.setStripAnsi(!Utils.argListContainsFlag(args, "-color"));
                // Default: do not append
                proc.setAppendToSnapshotFile(false);
                if (args.contains(">>")) {
                    proc.setAppendToSnapshotFile(true);
                    args.remove(">>");
                } else if (args.contains(">")) {
                    proc.setAppendToSnapshotFile(false);
                    args.remove(">");
                }
                proc.setSnapshotFile(Utils.parseCmdinputToGetSnapshotFile(Joiner.on(" ").join(args), proc.getGenomicCoordsHistory().current()));
            } else if (cmdTokens.get(0).equals("q")) {
                System.out.print("\033[0m");
                console.clearScreen();
                console.flush();
                System.exit(0);
            // * These commands change the GenomicCoordinates (navigate) but do not touch the tracks.
            } else if (cmdTokens.get(0).equals("f") || cmdTokens.get(0).equals("b") || cmdTokens.get(0).equals("ff") || cmdTokens.get(0).equals("bb") || cmdTokens.get(0).matches("^\\-\\d+.*") || cmdTokens.get(0).matches("^\\+\\d+.*")) {
                // No cmd line args either f/b ops or ints
                String newRegion = Utils.parseConsoleInput(cmdTokens, proc.getGenomicCoordsHistory().current()).trim();
                proc.getGenomicCoordsHistory().add(new GenomicCoords(newRegion, terminalWidth, samSeqDict, fasta));
            } else if (cmdTokens.get(0).matches("^\\d+.*") || cmdTokens.get(0).matches("^\\.\\d+.*")) {
                String newRegion;
                try {
                    newRegion = this.gotoOnCurrentChrom(cmdTokens, proc.getGenomicCoordsHistory().current());
                } catch (IndexOutOfBoundsException e) {
                    System.err.append("Column coordinates must be >= 1 and <= the screen width");
                    throw new InvalidCommandLineException();
                }
                proc.getGenomicCoordsHistory().add(new GenomicCoords(newRegion, terminalWidth, samSeqDict, fasta));
            } else if (cmdTokens.get(0).equals("goto") || cmdTokens.get(0).startsWith(":")) {
                String reg = Joiner.on(" ").join(cmdTokens).replaceFirst("goto|:", "").trim();
                proc.getGenomicCoordsHistory().add(new GenomicCoords(reg, terminalWidth, samSeqDict, fasta));
            } else if (cmdTokens.get(0).equals("p")) {
                proc.getGenomicCoordsHistory().previous();
            } else if (cmdTokens.get(0).equals("n")) {
                proc.getGenomicCoordsHistory().next();
            } else if (cmdTokens.get(0).equals("zo")) {
                int nz = Utils.parseZoom(Joiner.on(" ").join(cmdTokens), 1);
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                for (int i = 0; i < nz; i++) {
                    gc.zoomOut();
                }
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("zi")) {
                int nz = Utils.parseZoom(Joiner.on(" ").join(cmdTokens), 1);
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                for (int i = 0; i < nz; i++) {
                    gc.zoomIn();
                }
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("extend")) {
                if (cmdTokens.size() == 1) {
                    System.err.println(Utils.padEndMultiLine("Expected at least one argument.", proc.getWindowSize()));
                }
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                gc.cmdInputExtend(cmdTokens);
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("trim")) {
                GenomicCoords gc = proc.getTrackSet().trimCoordsForTrack(cmdTokens);
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("l")) {
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                gc.left();
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("r")) {
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                gc.right();
                proc.getGenomicCoordsHistory().add(gc);
            } else if (cmdTokens.get(0).equals("setGenome")) {
                this.setGenome(cmdTokens, proc);
            // * These commands change the Tracks but do not touch the GenomicCoordinates.
            } else if (cmdTokens.get(0).equals("dataCol")) {
                try {
                    proc.getTrackSet().setDataColForRegex(cmdTokens);
                } catch (Exception e) {
                    String msg = Utils.padEndMultiLine("Error processing " + cmdTokens + ". Perhaps a non-numeric column was selected?", proc.getWindowSize());
                    System.err.println(msg);
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
            } else if (cmdTokens.get(0).equals("ylim")) {
                proc.getTrackSet().setTrackYlimitsForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("trackHeight")) {
                proc.getTrackSet().setTrackHeightForRegex(cmdTokens);
            } else if ((cmdTokens.get(0).equals("colorTrack") || cmdTokens.get(0).equals("colourTrack"))) {
                proc.getTrackSet().setTrackColourForRegex(cmdTokens);
            } else if ((cmdTokens.get(0).equals("featureColorForRegex"))) {
                proc.getTrackSet().setFeatureColorForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("hideTitle")) {
                proc.getTrackSet().setHideTitleForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals(Command.BSseq.getCmdDescr())) {
                if (proc.getGenomicCoordsHistory().current().getFastaFile() == null) {
                    String msg = Utils.padEndMultiLine("Cannot set BSseq mode without reference sequence", proc.getWindowSize());
                    System.err.println(msg);
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
                proc.getTrackSet().setBisulfiteModeForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("squash") || cmdTokens.get(0).equals(Command.featureDisplayMode.toString())) {
                proc.getTrackSet().setFeatureDisplayModeForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("gap")) {
                proc.getTrackSet().setFeatureGapForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("readsAsPairs")) {
                proc.getTrackSet().setReadsAsPairsForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("gffNameAttr")) {
                proc.getTrackSet().setAttributeForGFFName(cmdTokens);
            } else if (cmdTokens.get(0).equals("open") || cmdTokens.get(0).equals("addTracks")) {
                cmdTokens.remove(0);
                List<String> globbed = Utils.globFiles(cmdTokens);
                if (globbed.size() == 0) {
                    globbed = this.openFilesFromIndexes(proc.getTrackSet().getOpenedFiles(), cmdTokens);
                }
                if (globbed.size() == 0) {
                    String msg = Utils.padEndMultiLine(cmdTokens + ": No file found.", proc.getWindowSize());
                    System.err.println(msg);
                    this.interactiveInputExitCode = ExitCode.ERROR;
                } else {
                    for (String sourceName : globbed) {
                        String msg = Utils.padEndMultiLine("Adding: " + sourceName, proc.getWindowSize());
                        System.err.println(msg);
                        try {
                            proc.getTrackSet().addTrackFromSource(sourceName, proc.getGenomicCoordsHistory().current(), null);
                        } catch (Exception e) {
                            try {
                                // It may be that you are in position that doesn't exist in the sequence dictionary that
                                // came with this new file. To recover, find an existing position, move there and try to reload the
                                // file. This fixes issue#23
                                String region = Main.initRegion(globbed, null, null, debug);
                                proc.getGenomicCoordsHistory().add(new GenomicCoords(region, terminalWidth, samSeqDict, fasta));
                                proc.getTrackSet().addTrackFromSource(sourceName, proc.getGenomicCoordsHistory().current(), null);
                            } catch (Exception x) {
                                x.printStackTrace();
                                msg = Utils.padEndMultiLine("Failed to add: " + sourceName, proc.getWindowSize());
                                System.err.println(msg);
                            }
                        }
                        if (proc.getGenomicCoordsHistory().current().getSamSeqDict() == null || proc.getGenomicCoordsHistory().current().getSamSeqDict().size() == 0) {
                            GenomicCoords testSeqDict = new GenomicCoords("default", Utils.getTerminalWidth(), null, null);
                            List<String> candidateSourceGenome = new ArrayList<String>();
                            candidateSourceGenome.add(sourceName);
                            testSeqDict.setGenome(candidateSourceGenome, false);
                            if (testSeqDict.getSamSeqDict() != null) {
                                candidateSourceGenome.add(0, "cmd");
                                proc.getGenomicCoordsHistory().setGenome(candidateSourceGenome);
                            }
                        }
                    }
                }
            } else if (cmdTokens.get(0).equals("reload")) {
                proc.getTrackSet().reload(cmdTokens);
            } else if (cmdTokens.get(0).equals("dropTracks")) {
                if (cmdTokens.size() <= 1) {
                    System.err.println(Utils.padEndMultiLine("List one or more tracks to drop or `dropTracks -h` for help.", proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
                messages += proc.getTrackSet().dropTracksWithRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("orderTracks")) {
                cmdTokens.remove(0);
                proc.getTrackSet().orderTracks(cmdTokens);
            } else if (cmdTokens.get(0).equals("editNames")) {
                messages += proc.getTrackSet().editNamesForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals(Command.print.toString())) {
                proc.getTrackSet().setPrintModeAndPrintFeaturesForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("grep")) {
                proc.getTrackSet().setFilterForTrackIntervalFeature(cmdTokens);
            } else if (cmdTokens.get(0).equals("awk")) {
                proc.getTrackSet().setAwkForTrack(cmdTokens);
            } else if (cmdTokens.get(0).equals("filterVariantReads")) {
                proc.getTrackSet().setFilterVariantReads(cmdTokens);
            } else if (cmdTokens.get(0).equals(Command.rpm.getCmdDescr())) {
                proc.getTrackSet().setRpmForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("samtools")) {
                proc.getTrackSet().setSamFilterForRegex(cmdTokens);
            } else if (cmdTokens.get(0).equals("genotype")) {
                proc.getTrackSet().setGenotypeMatrix(cmdTokens);
            // * These commands change both the Tracks and the GenomicCoordinates
            } else if (cmdTokens.get(0).equals("next")) {
                this.next(cmdTokens, proc);
            } else if (cmdTokens.get(0).equals("find")) {
                boolean all = Utils.argListContainsFlag(cmdTokens, "-all");
                boolean fixedPattern = Utils.argListContainsFlag(cmdTokens, "-F");
                boolean caseIns = Utils.argListContainsFlag(cmdTokens, "-c");
                if (cmdTokens.size() < 2) {
                    System.err.println(Utils.padEndMultiLine("Error in find command. Expected at least 1 argument got: " + cmdTokens, proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
                if (cmdTokens.size() == 2) {
                    // If track arg is missing use this placeholder.
                    cmdTokens.add("");
                }
                GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
                gc.setTerminalWidth(terminalWidth);
                int flag = 0;
                if (fixedPattern) {
                    flag |= Pattern.LITERAL;
                }
                if (!caseIns) {
                    flag |= Pattern.CASE_INSENSITIVE;
                }
                Pattern pattern;
                try {
                    pattern = Pattern.compile(cmdTokens.get(1), flag);
                } catch (PatternSyntaxException e) {
                    System.err.println("Invalid regex");
                    throw new InvalidCommandLineException();
                }
                GenomicCoords nextGc = proc.getTrackSet().findNextMatchOnTrack(pattern, cmdTokens.get(2), gc, all);
                if (nextGc.equalCoords(gc)) {
                    System.err.println("No match found outside of this window for query '" + cmdTokens.get(1) + "'");
                    this.interactiveInputExitCode = ExitCode.CLEAN_NO_FLUSH;
                } else {
                    proc.getGenomicCoordsHistory().add(nextGc);
                }
            } else if (cmdTokens.get(0).equals("seqRegex")) {
                try {
                    proc.getTrackSet().setRegexForTrackSeqRegex(cmdTokens, proc.getGenomicCoordsHistory().current());
                } catch (InvalidCommandLineException e) {
                    System.err.println(Utils.padEndMultiLine("Cannot find regex in sequence without fasta reference!", proc.getWindowSize()));
                    this.interactiveInputExitCode = ExitCode.ERROR;
                    continue;
                }
            } else if (cmdTokens.get(0).equals("bookmark")) {
                messages += proc.getTrackSet().bookmark(proc.getGenomicCoordsHistory().current(), cmdTokens);
            } else {
                System.err.println(Utils.padEndMultiLine("Unrecognized command: " + cmdTokens.get(0), proc.getWindowSize()));
                String suggestions = Joiner.on(" or ").join(Utils.suggestCommand(cmdTokens.get(0).trim(), CommandList.cmds()));
                if (!suggestions.isEmpty()) {
                    System.err.println(Utils.padEndMultiLine("Maybe you mean " + suggestions + "?", proc.getWindowSize()));
                }
                this.interactiveInputExitCode = ExitCode.ERROR;
            // throw new InvalidCommandLineException();
            }
        } catch (ArgumentParserException e) {
            this.interactiveInputExitCode = ExitCode.ERROR;
        } catch (Exception e) {
            // You shouldn't catch anything! Be more specific.
            System.err.println(Utils.padEndMultiLine("\nError processing input: " + cmdTokens, proc.getWindowSize()));
            System.err.println(Utils.padEndMultiLine("For help on command \"cmd\" execute 'cmd -h' or '-h' for list of commands.\n", proc.getWindowSize()));
            this.interactiveInputExitCode = ExitCode.ERROR;
            if (debug == 1) {
                e.printStackTrace();
            } else if (debug == 2) {
                e.printStackTrace();
                System.exit(1);
            }
        }
        if (this.interactiveInputExitCode.equals(ExitCode.CLEAN) || this.interactiveInputExitCode.equals(ExitCode.CLEAN_NO_FLUSH)) {
            // Command has been parsed ok. Let's see if we can execute it without exceptions.
            try {
                if (this.interactiveInputExitCode.equals(ExitCode.CLEAN)) {
                    console.clearScreen();
                    console.flush();
                    proc.iterateTracks();
                } else {
                // 
                }
            } catch (InvalidGenomicCoordsException e) {
                String region = Main.initRegion(proc.getTrackSet().getFilenameList(), null, null, debug);
                proc.getGenomicCoordsHistory().add(new GenomicCoords(region, terminalWidth, samSeqDict, fasta));
                System.err.println(Utils.padEndMultiLine("Invalid genomic coordinates found. Resetting to " + region, proc.getWindowSize()));
                if (debug > 0) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                System.err.println(Utils.padEndMultiLine("Error processing tracks with input " + cmdTokens, proc.getWindowSize()));
                this.interactiveInputExitCode = ExitCode.ERROR;
                if (debug > 0) {
                    e.printStackTrace();
                }
            }
        }
        if (this.interactiveInputExitCode.equals(ExitCode.ERROR)) {
            // Unless we are in non-interactive mode
            if (nonInteractive) {
                System.exit(1);
            }
            break;
        }
    }
    // END OF LOOP THROUGH CHAIN OF INPUT COMMANDS
    if (!messages.isEmpty()) {
        System.err.println(Utils.padEndMultiLine(messages.trim(), proc.getWindowSize()));
    }
    messages = "";
    return proc;
}
Also used : Pattern(java.util.regex.Pattern) ArrayList(java.util.ArrayList) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) InvalidCommandLineException(exceptions.InvalidCommandLineException) InvalidColourException(exceptions.InvalidColourException) InvalidRecordException(exceptions.InvalidRecordException) SQLException(java.sql.SQLException) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) InvalidConfigException(exceptions.InvalidConfigException) PatternSyntaxException(java.util.regex.PatternSyntaxException) IOException(java.io.IOException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException) InvalidCommandLineException(exceptions.InvalidCommandLineException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException) ArrayList(java.util.ArrayList) CommandList(commandHelp.CommandList) List(java.util.List) ArgumentParserException(net.sourceforge.argparse4j.inf.ArgumentParserException) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

InvalidRecordException (exceptions.InvalidRecordException)5 IOException (java.io.IOException)3 SQLException (java.sql.SQLException)3 InvalidColourException (exceptions.InvalidColourException)2 InvalidCommandLineException (exceptions.InvalidCommandLineException)2 InvalidGenomicCoordsException (exceptions.InvalidGenomicCoordsException)2 CommandList (commandHelp.CommandList)1 InvalidConfigException (exceptions.InvalidConfigException)1 SAMSequenceDictionary (htsjdk.samtools.SAMSequenceDictionary)1 BlockCompressedOutputStream (htsjdk.samtools.util.BlockCompressedOutputStream)1 MalformedFeatureFile (htsjdk.tribble.TribbleException.MalformedFeatureFile)1 Index (htsjdk.tribble.index.Index)1 TabixIndexCreator (htsjdk.tribble.index.tabix.TabixIndexCreator)1 LineIterator (htsjdk.tribble.readers.LineIterator)1 VariantContext (htsjdk.variant.variantcontext.VariantContext)1 VCFCodec (htsjdk.variant.vcf.VCFCodec)1 VCFFileReader (htsjdk.variant.vcf.VCFFileReader)1 VCFHeader (htsjdk.variant.vcf.VCFHeader)1 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1