Search in sources :

Example 11 with InvalidCommandLineException

use of exceptions.InvalidCommandLineException in project ASCIIGenome by dariober.

the class TrackSet method setFilterVariantReads.

public void setFilterVariantReads(List<String> cmdInput) throws InvalidCommandLineException, MalformedURLException, ClassNotFoundException, IOException, InvalidGenomicCoordsException, InvalidRecordException, SQLException {
    List<String> args = new ArrayList<String>();
    for (String x : cmdInput) {
        args.add(x);
    }
    // Remove command name
    args.remove(0);
    // Collect arguments
    boolean variantOnly = !Utils.argListContainsFlag(args, "-all");
    boolean invertSelection = Utils.argListContainsFlag(args, "-v");
    String region = Utils.getArgForParam(args, "-r", null);
    String chrom = Filter.DEFAULT_VARIANT_CHROM.getValue();
    int from = -1;
    int to = -1;
    if (region != null && this.getTrackList().size() > 0) {
        if (this.getTrackList().get(0).getGc().getFastaFile() == null) {
            System.err.println("A reference sequence is required to execute this command.");
            throw new InvalidCommandLineException();
        }
        chrom = this.getTrackList().get(0).getGc().getChrom();
        // Find whether the region is a single pos +/- a value or
        region = region.trim().replaceAll(" ", "").replaceAll(",", "").replaceAll("/", "");
        try {
            if (region.contains("+-") || region.contains("-+")) {
                String[] fromTo = region.replaceAll("\\+", "").split("-");
                int offset = Integer.parseInt(fromTo[1]);
                from = Integer.parseInt(fromTo[0]) - offset;
                to = Integer.parseInt(fromTo[0]) + offset;
            } else if (region.contains("-")) {
                String[] fromTo = region.split("-");
                from = Integer.parseInt(fromTo[0]) - Integer.parseInt(fromTo[1]);
                to = Integer.parseInt(fromTo[0]);
            } else if (region.contains("+")) {
                String[] fromTo = region.split("\\+");
                from = Integer.parseInt(fromTo[0]);
                to = Integer.parseInt(fromTo[0]) + Integer.parseInt(fromTo[1]);
            } else if (region.contains(":")) {
                String[] fromTo = region.split(":");
                from = Integer.parseInt(fromTo[0]);
                to = Integer.parseInt(fromTo[1]);
            } else {
                from = Integer.parseInt(region);
                to = Integer.parseInt(region);
            }
        } catch (NumberFormatException e) {
            System.err.println("Cannot parse region into integers: " + region);
            throw new InvalidCommandLineException();
        }
        if (from < 1)
            from = 1;
        if (to < 1)
            to = 1;
        if (from > to)
            from = to;
    }
    // -----------------------------------------------
    // Stub for filtering by records in another track
    // String track= Utils.getArgForParam(args, "-t", null);
    // if(track != null){
    // List<String>pattern= new ArrayList<String>();
    // pattern.add(track);
    // List<Track> tname= this.matchTracks(pattern, true, false);
    // if(tname.size() == 0){
    // // Handle no track matched
    // }
    // TrackIntervalFeature tr= (TrackIntervalFeature)this.getTrack(tname.get(0));
    // tr.getIntervalFeatureList();
    // // List<String> chroms=
    // // List<Integer> starts=
    // // List<ends> ends=
    // }
    // Modify Track.setVariantReadInInterval() to accept a list of chrom, start, end positions.
    // -----------------------------------------------
    List<String> trackNameRegex = new ArrayList<String>();
    // Regex for tracks:
    if (args.size() == 0) {
        // This will turn off everything
        trackNameRegex.add(".*");
    } else {
        // Everything after -off is track re to turn off.
        trackNameRegex.addAll(args);
    }
    // Set filter
    List<Track> tracksToReset = this.matchTracks(trackNameRegex, true, invertSelection);
    for (Track tr : tracksToReset) {
        tr.setVariantReadInInterval(chrom, from, to, variantOnly);
    }
}
Also used : ArrayList(java.util.ArrayList) InvalidCommandLineException(exceptions.InvalidCommandLineException)

Example 12 with InvalidCommandLineException

use of exceptions.InvalidCommandLineException in project ASCIIGenome by dariober.

the class GenomicCoordsHistory method setGenome.

/**
 * Set sequence dictionary and fasta ref, if available for all the genomic coords in this
 * history.
 * @throws InvalidGenomicCoordsException
 */
public void setGenome(List<String> tokens) throws InvalidCommandLineException, IOException, InvalidGenomicCoordsException {
    if (tokens.size() == 0) {
        throw new InvalidCommandLineException();
    }
    List<GenomicCoords> toDelete = new ArrayList<GenomicCoords>();
    GenomicCoords now = this.current();
    for (GenomicCoords gc : this.getCurrentSessionHistory()) {
        // Set the genome for each position in history. Invalid positions are removed.
        gc.setGenome(tokens, true);
        if (!this.isValidPosition(gc, gc.getSamSeqDict())) {
            toDelete.add(gc);
        }
    }
    for (GenomicCoords gc : toDelete) {
        this.getCurrentSessionHistory().remove(gc);
    }
    // After having removed invalid positions, reset the position tracker to where we were.
    this.positionTracker = this.getCurrentSessionHistory().indexOf(now);
    if (this.positionTracker < 0) {
        if (this.getCurrentSessionHistory().size() > 0) {
            // Try to move to the last valid position.
            this.positionTracker = this.getCurrentSessionHistory().size() - 1;
        } else {
            // There are no valid positions in the history so create a new one and move there
            int terminalWindowSize = Utils.getTerminalWidth();
            GenomicCoords defaultPos = new GenomicCoords("default", terminalWindowSize, null, null);
            defaultPos.setGenome(tokens, true);
            LinkedHashMap<String, Integer> chromLen = new LinkedHashMap<String, Integer>();
            for (SAMSequenceRecord x : defaultPos.getSamSeqDict().getSequences()) {
                chromLen.put(x.getSequenceName(), x.getSequenceLength());
            }
            String chrom = chromLen.keySet().iterator().next();
            GenomicCoords newGc = new GenomicCoords(chrom + ":" + 1, terminalWindowSize, defaultPos.getSamSeqDict(), defaultPos.getFastaFile());
            this.add(newGc);
        }
    }
}
Also used : InvalidCommandLineException(exceptions.InvalidCommandLineException) ArrayList(java.util.ArrayList) SAMSequenceRecord(htsjdk.samtools.SAMSequenceRecord) LinkedHashMap(java.util.LinkedHashMap)

Example 13 with InvalidCommandLineException

use of exceptions.InvalidCommandLineException in project ASCIIGenome by dariober.

the class InteractiveInput method next.

/**
 * Move to next feature using parameters in cmdInput.
 * First arg in cmdInput is command name itself.
 * The side effect is to modify the TrackProcessor obj to update the position.
 */
private void next(List<String> cmdInput, TrackProcessor proc) throws InvalidGenomicCoordsException, IOException, InvalidCommandLineException {
    List<String> args = new ArrayList<String>(cmdInput);
    // Remove command name
    args.remove(0);
    int zo = 5;
    if (args.contains("-zo")) {
        try {
            zo = Integer.parseInt(args.get(args.indexOf("-zo") + 1));
            args.remove(args.get(args.indexOf("-zo") + 1));
            args.remove("-zo");
            if (zo < 0) {
                zo = 0;
            }
        } catch (Exception e) {
            System.err.println(Utils.padEndMultiLine("Argument to -zo parameter must be an integer", proc.getWindowSize()));
            throw new InvalidCommandLineException();
        }
    }
    GenomicCoords gc = (GenomicCoords) proc.getGenomicCoordsHistory().current().clone();
    String trackId = "";
    boolean start = false;
    if (args.contains("-start")) {
        start = true;
        args.remove("-start");
    }
    boolean center = false;
    if (args.contains("-c")) {
        center = true;
        args.remove("-c");
    }
    boolean getPrevious = false;
    if (args.contains("-back")) {
        getPrevious = true;
        args.remove("-back");
    }
    if (args.size() > 0) {
        trackId = args.get(0);
    }
    if (start) {
        proc.getGenomicCoordsHistory().add(proc.getTrackSet().goToNextFeatureOnFile(trackId, gc, -1.0, getPrevious));
    } else if (center) {
        proc.getGenomicCoordsHistory().add(proc.getTrackSet().goToNextFeatureOnFile(trackId, gc, 0, getPrevious));
    } else {
        proc.getGenomicCoordsHistory().add(proc.getTrackSet().goToNextFeatureOnFile(trackId, gc, zo, getPrevious));
    }
}
Also used : ArrayList(java.util.ArrayList) InvalidCommandLineException(exceptions.InvalidCommandLineException) 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)

Example 14 with InvalidCommandLineException

use of exceptions.InvalidCommandLineException 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)

Example 15 with InvalidCommandLineException

use of exceptions.InvalidCommandLineException in project ASCIIGenome by dariober.

the class Main method initConsole.

public static ConsoleReader initConsole() throws IOException, InvalidColourException {
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        public void run() {
            // On exit turn off all formatting
            System.out.print("\033[0m");
        }
    }));
    ConsoleReader console = new ConsoleReader();
    try {
        // Autcomplete commands with length > x
        for (CommandHelp x : CommandList.commandHelpList()) {
            if (x.getName().length() > 2) {
                console.addCompleter(new StringsCompleter(x.getName()));
            }
        }
    } catch (InvalidCommandLineException e) {
        e.printStackTrace();
    }
    console.setExpandEvents(false);
    return console;
}
Also used : ConsoleReader(jline.console.ConsoleReader) StringsCompleter(jline.console.completer.StringsCompleter) CommandHelp(commandHelp.CommandHelp) InvalidCommandLineException(exceptions.InvalidCommandLineException)

Aggregations

InvalidCommandLineException (exceptions.InvalidCommandLineException)18 ArrayList (java.util.ArrayList)13 PatternSyntaxException (java.util.regex.PatternSyntaxException)8 IOException (java.io.IOException)6 InvalidColourException (exceptions.InvalidColourException)5 InvalidConfigException (exceptions.InvalidConfigException)5 InvalidGenomicCoordsException (exceptions.InvalidGenomicCoordsException)5 InvalidRecordException (exceptions.InvalidRecordException)5 SQLException (java.sql.SQLException)5 ArgumentParserException (net.sourceforge.argparse4j.inf.ArgumentParserException)5 Pattern (java.util.regex.Pattern)4 File (java.io.File)3 Test (org.junit.Test)3 GenomicCoords (samTextViewer.GenomicCoords)3 Config (coloring.Config)1 ConfigKey (coloring.ConfigKey)1 Xterm256 (coloring.Xterm256)1 CommandHelp (commandHelp.CommandHelp)1 CommandList (commandHelp.CommandList)1 SAMSequenceDictionary (htsjdk.samtools.SAMSequenceDictionary)1