Search in sources :

Example 6 with InvalidGenomicCoordsException

use of exceptions.InvalidGenomicCoordsException 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 7 with InvalidGenomicCoordsException

use of exceptions.InvalidGenomicCoordsException in project ASCIIGenome by dariober.

the class Utils method parseStringCoordsToList.

/**
 *Parse string region in the form <chrom>:[start[-end]] to a list containing the
 * the three elements. See tests for behavior.
 * <start> and <end> if present are guaranteed to be parsable to positive int.
 * @throws InvalidGenomicCoordsException
 */
public static List<String> parseStringCoordsToList(String region) throws InvalidGenomicCoordsException {
    List<String> coords = new ArrayList<String>(3);
    coords.add(null);
    coords.add("1");
    // Max size of binning index for tabix is 2^29. See also https://github.com/samtools/htslib/issues/435
    coords.add("536870912");
    String chrom = StringUtils.substringBeforeLast(region, ":").trim();
    coords.set(0, chrom);
    String fromTo = StringUtils.substringAfterLast(region, ":").replaceAll(",", "").replaceAll("\\s", "");
    if (fromTo.isEmpty()) {
        // Only chrom given
        return coords;
    }
    if (!fromTo.replaceFirst("-", "").matches("[0-9]+")) {
        // If the from-to part does not contain only digits with the exception of the - separator,
        // we assume this is a chrom name containing : and missing the from-to part.
        coords.set(0, region);
        return coords;
    }
    int nsep = StringUtils.countMatches(fromTo, "-");
    Integer from = null;
    Integer to = null;
    if (nsep == 0) {
        // Only start position given
        from = Integer.parseInt(StringUtils.substringBefore(fromTo, "-").trim());
        to = from;
    } else if (nsep == 1) {
        // From and To positions given.
        from = Integer.parseInt(StringUtils.substringBefore(fromTo, "-").trim());
        to = Integer.parseInt(StringUtils.substringAfter(fromTo, "-").trim());
        if (from > to || from <= 0 || to <= 0 || (to - from + 1) > 536870912) {
            throw new InvalidGenomicCoordsException();
        }
    } else {
        throw new InvalidGenomicCoordsException();
    }
    coords.set(1, from.toString());
    coords.set(2, to.toString());
    return coords;
}
Also used : ArrayList(java.util.ArrayList) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException)

Example 8 with InvalidGenomicCoordsException

use of exceptions.InvalidGenomicCoordsException 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 9 with InvalidGenomicCoordsException

use of exceptions.InvalidGenomicCoordsException 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 10 with InvalidGenomicCoordsException

use of exceptions.InvalidGenomicCoordsException in project ASCIIGenome by dariober.

the class Main method initRegion.

/**
 * Return a suitable region to start. If a region is already given, do nothing.
 * This method is a mess and should be cleaned up together with GenomicCoords class.
 * @throws InvalidGenomicCoordsException
 */
public static String initRegion(List<String> inputFileList, String fasta, String genome, int debug) throws IOException, InvalidGenomicCoordsException {
    // Preferably we start from a position that has a feature rather than from the start of a
    // random chrom.
    System.err.print("Initializing coordinates... ");
    // First search for files that can init chrom and position
    List<String> skipped = new ArrayList<String>();
    for (String x : inputFileList) {
        TrackFormat fmt = Utils.getFileTypeFromName(x);
        if (fmt.equals(TrackFormat.TDF)) {
            skipped.add(x);
            continue;
        }
        try {
            String region = Utils.initRegionFromFile(x);
            System.err.println("Done from: " + x);
            return region;
        } catch (Exception e) {
            System.err.println("\nCould not initilize from file " + x);
            if (debug > 0) {
                e.printStackTrace();
            }
        }
    }
    // Try to initialize from fasta
    if (fasta != null && !fasta.trim().isEmpty()) {
        IndexedFastaSequenceFile faSeqFile = new IndexedFastaSequenceFile(new File(fasta));
        String region = faSeqFile.nextSequence().getName();
        faSeqFile.close();
        return region;
    }
    // Try genome file
    if (genome != null && !genome.trim().isEmpty()) {
        GenomicCoords gc = new GenomicCoords(Utils.getTerminalWidth());
        gc.setGenome(Arrays.asList(new String[] { genome }), false);
        SAMSequenceDictionary samSeqDict = gc.getSamSeqDict();
        String region = samSeqDict.getSequence(0).getSequenceName();
        return region;
    }
    // Failing that, look for any file that gives at least chrom
    for (String x : skipped) {
        try {
            String region = Utils.initRegionFromFile(x);
            System.err.println("Done from: " + x);
            return region;
        } catch (Exception e) {
            System.err.println("\nCould not initilize from file " + x);
            if (debug > 0) {
                e.printStackTrace();
            }
        }
    }
    // It appears everything failed to initialise...
    return "";
}
Also used : TrackFormat(tracks.TrackFormat) ArrayList(java.util.ArrayList) File(java.io.File) IndexedFastaSequenceFile(htsjdk.samtools.reference.IndexedFastaSequenceFile) SAMSequenceDictionary(htsjdk.samtools.SAMSequenceDictionary) InvalidCommandLineException(exceptions.InvalidCommandLineException) InvalidColourException(exceptions.InvalidColourException) InvalidRecordException(exceptions.InvalidRecordException) SQLException(java.sql.SQLException) InvalidConfigException(exceptions.InvalidConfigException) UnindexableFastaFileException(faidx.UnindexableFastaFileException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) DocumentException(com.itextpdf.text.DocumentException) BamIndexNotFoundException(exceptions.BamIndexNotFoundException) InvalidGenomicCoordsException(exceptions.InvalidGenomicCoordsException) IndexedFastaSequenceFile(htsjdk.samtools.reference.IndexedFastaSequenceFile)

Aggregations

InvalidGenomicCoordsException (exceptions.InvalidGenomicCoordsException)13 ArrayList (java.util.ArrayList)7 InvalidColourException (exceptions.InvalidColourException)5 InvalidCommandLineException (exceptions.InvalidCommandLineException)5 InvalidRecordException (exceptions.InvalidRecordException)5 IOException (java.io.IOException)5 SQLException (java.sql.SQLException)5 InvalidConfigException (exceptions.InvalidConfigException)4 SAMSequenceDictionary (htsjdk.samtools.SAMSequenceDictionary)4 IndexedFastaSequenceFile (htsjdk.samtools.reference.IndexedFastaSequenceFile)3 File (java.io.File)3 PatternSyntaxException (java.util.regex.PatternSyntaxException)3 ArgumentParserException (net.sourceforge.argparse4j.inf.ArgumentParserException)3 List (java.util.List)2 TrackFormat (tracks.TrackFormat)2 DocumentException (com.itextpdf.text.DocumentException)1 CommandList (commandHelp.CommandList)1 BamIndexNotFoundException (exceptions.BamIndexNotFoundException)1 UnindexableFastaFileException (faidx.UnindexableFastaFileException)1 SAMRecord (htsjdk.samtools.SAMRecord)1