Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

In this page you can find the example usage for java.io PrintStream PrintStream.

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

Creates a new print stream, without automatic line flushing, with the specified file.

Usage

From source file:net.lightbody.bmp.proxy.jetty.jetty.win32.Service.java

public static void main(String[] arg) {
    String opt;//from  w  ww.  j  ava2s  .co m
    opt = System.getProperty("SERVICE_OUT");
    if (opt != null) {
        try {
            PrintStream stdout = new PrintStream(new FileOutputStream(opt));
            System.setOut(stdout);
        } catch (Exception e) {
            log.warn(LogSupport.EXCEPTION, e);
        }
    }

    opt = System.getProperty("SERVICE_ERR");
    if (opt != null) {
        try {
            PrintStream stderr = new PrintStream(new FileOutputStream(opt));
            System.setErr(stderr);
        } catch (Exception e) {
            log.warn(LogSupport.EXCEPTION, e);
        }
    }

    if (arg.length == 0)
        arg = new String[] { "etc/jetty.xml" };

    try {
        _configs = new Vector();
        for (int i = 0; i < arg.length; i++)
            _configs.add(arg[i]);
        createAll();
        startAll();
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }
}

From source file:edu.msu.cme.rdp.readseq.writers.StkWriter.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("r", "removeref", false, "is set, do not write the GC reference sequences to output");
    options.addOption("h", "header", true,
            "the header of the output file in case a differenet stk version, default is " + STK_HEADER);
    String header = STK_HEADER;// ww w  .  ja v a2s.c  o m
    boolean removeRef = false;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("removeref")) {
            removeRef = true;
        }
        if (line.hasOption("header")) {
            header = line.getOptionValue("header");
        }

        args = line.getArgs();
        if (args.length < 2) {
            throw new Exception("Need input and output files");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-stk <input-file> <out-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SequenceReader reader = new SequenceReader(new File(args[0]));
    PrintStream out = new PrintStream(new File(args[1]));
    StkWriter writer = new StkWriter(reader, out, header);
    reader = new SequenceReader(new File(args[0]));
    Sequence seq;
    while ((seq = reader.readNextSequence()) != null) {
        if (seq.getSeqName().startsWith("#") && removeRef) {
            continue;
        }
        writer.writeSeq(seq);
    }
    writer.writeEndOfBlock();
    writer.close();
    reader.close();

}

From source file:edu.msu.cme.rdp.probematch.cli.SliceToPrimer.java

public static void main(String[] args) throws Exception {
    //args = "--fedit-dist 4 --redit-dist=4 -k --max-length=400 --min-length=280 -o java_sliced_edit4.fasta TGCGAYCCSAARGCBGACTC ATSGCCATCATYTCRCCGGA /scratch/fishjord/tae_kwon_primer_match/all_genomes.fasta".split(" ");
    PatternBitMask64[] fprimers;/*  ww w.  j ava  2s.c  om*/
    String[] fprimerStrs, rprimerStrs;
    PatternBitMask64[] rprimers;

    FastaWriter seqOut;
    PrintStream statsOut;

    int fEdit = 3;
    int rEdit = 3;
    int minLength = Integer.MIN_VALUE;
    int maxLength = Integer.MAX_VALUE;
    boolean allowAmbiguities = true;
    boolean keepPrimers = false;

    SequenceReader inSeqs;

    try {

        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("edit-dist")) {
            fEdit = rEdit = Integer.parseInt(line.getOptionValue("edit-dist"));

            if (line.hasOption("redit-dist") || line.hasOption("fedit-dist")) {
                throw new Exception("edit-dist, [fedit-dist, redit-dist] are mutually exclusive");
            }
        }

        if (line.hasOption("fedit-dist")) {
            fEdit = Integer.parseInt(line.getOptionValue("fedit-dist"));
        }

        if (line.hasOption("no-ambiguities")) {
            allowAmbiguities = false;
        }

        if (line.hasOption("keep-primers")) {
            keepPrimers = true;
        }

        if (line.hasOption("redit-dist")) {
            rEdit = Integer.parseInt(line.getOptionValue("redit-dist"));
        }

        if (line.hasOption("seq-out")) {
            seqOut = new FastaWriter(new File(line.getOptionValue("seq-out")));
        } else {
            throw new Exception("Must specify seq-out");
        }

        if (line.hasOption("stats-out")) {
            statsOut = new PrintStream(new File(line.getOptionValue("stats-out")));
        } else {
            statsOut = System.out;
        }

        if (line.hasOption("min-length")) {
            minLength = Integer.parseInt(line.getOptionValue("min-length"));
        }

        if (line.hasOption("max-length")) {
            maxLength = Integer.parseInt(line.getOptionValue("max-length"));
        }

        args = line.getArgs();

        if (args.length != 3) {
            throw new Exception("Unexpected number of command line arguments");
        }

        fprimers = translateStringPrimers(args[0].split(","), allowAmbiguities, false);
        fprimerStrs = args[0].split(",");
        rprimers = translateStringPrimers(args[1].split(","), allowAmbiguities, true);
        rprimerStrs = args[1].split(",");
        inSeqs = new SequenceReader(new File(args[2]));

    } catch (Exception e) {
        new HelpFormatter().printHelp("SliceToPrimer [options] <f,p,r,i,m,e,r> <r,p,r,i,m,e,r> <in_seq_file>",
                options);
        System.err.println("ERROR: " + e.getMessage());
        return;
    }

    Sequence seq;

    statsOut.println(
            "orig_seqid\tsliced_seqid\tfprimer\tstart\tend\tscore\trprimer\tstart\tend\tscore\tlength");

    ScoringMatrix sccoringMatrix = ScoringMatrix.getDefaultNuclMatrix();

    DPMAligner[] faligners = new DPMAligner[fprimers.length];
    for (int index = 0; index < faligners.length; index++) {
        faligners[index] = new DPMAligner(fprimerStrs[index], Integer.MAX_VALUE);
    }

    try {
        while ((seq = inSeqs.readNextSequence()) != null) {
            Set<PrimerMatch> fprimerMatches = new HashSet();
            Set<PrimerMatch> rprimerMatches = new HashSet();

            for (int index = 0; index < fprimers.length; index++) {
                PatternBitMask64 primer = fprimers[index];

                for (BitVector64Match r : BitVector64.process(seq.getSeqString().toCharArray(), primer, fEdit)
                        .getResults()) {
                    PrimerMatch match = new PrimerMatch();
                    match.start = r.getPosition() - (primer.getPatternLength() + r.getScore());
                    match.end = r.getPosition();
                    match.score = r.getScore();
                    match.primerIndex = index;
                    fprimerMatches.add(match);
                }
            }

            for (int index = 0; index < rprimers.length; index++) {
                PatternBitMask64 primer = rprimers[index];

                for (BitVector64Match r : BitVector64.process(seq.getSeqString().toCharArray(), primer, rEdit)
                        .getResults()) {
                    PrimerMatch match = new PrimerMatch();
                    match.start = r.getPosition() - (primer.getPatternLength() + r.getScore());
                    match.end = r.getPosition();
                    match.score = r.getScore();
                    match.primerIndex = index;
                    rprimerMatches.add(match);
                }
            }

            if (fprimerMatches.isEmpty() || rprimerMatches.isEmpty()) {
                statsOut.println(seq.getSeqName() + "\tEither/or no forward/reverse primer hits");
                continue;
            }
            for (PrimerMatch fmatch : fprimerMatches) {
                PrimerMatch bestReverse = null;
                int bestScore = Integer.MAX_VALUE;
                for (PrimerMatch rmatch : rprimerMatches) {
                    if (rmatch.start > fmatch.end && rmatch.start - fmatch.end < bestScore) {
                        bestReverse = rmatch;
                        bestScore = rmatch.start - fmatch.end;
                    }
                }

                if (bestReverse == null) {
                    statsOut.println(seq.getSeqName() + "\tNo reverse primer before " + fmatch.end);
                    continue;
                }

                String slicedSeq = null;
                if (keepPrimers) {
                    slicedSeq = seq.getSeqString().substring(fmatch.start, bestReverse.end);
                } else {
                    slicedSeq = seq.getSeqString().substring(fmatch.end, bestReverse.start);
                }

                String seqid = seq.getSeqName() + "_" + fmatch.primerIndex + "_" + fmatch.start;
                if (slicedSeq.length() > minLength && slicedSeq.length() < maxLength) {
                    seqOut.writeSeq(seqid, "", slicedSeq);
                }

                DPMAlignment seqs = faligners[fmatch.primerIndex]
                        .align(seq.getSeqString().substring(fmatch.start, fmatch.end));
                System.err.println(">" + seqid);
                System.err.println(fprimerStrs[fmatch.primerIndex]);
                System.err.println(seq.getSeqString().substring(fmatch.start, fmatch.end));
                System.err.println();
                System.err.println(seqs.getAlignedMatchFragment());
                System.err.println(seqs.getAlignedProbe());

                System.err.println();

                statsOut.println(seq.getSeqName() + "\t" + seqid + "\t" + fmatch.primerIndex + "\t"
                        + fmatch.start + "\t" + fmatch.end + "\t" + fmatch.score + "\t"
                        + bestReverse.primerIndex + "\t" + bestReverse.start + "\t" + bestReverse.end + "\t"
                        + bestReverse.score + "\t" + slicedSeq.length());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        statsOut.close();
        seqOut.close();
    }
}

From source file:fr.cs.examples.conversion.PropagatorConversion.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///from  w  ww .j ava 2  s . co m
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();

        // gravity field
        NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(2, 0);
        double mu = provider.getMu();

        // inertial frame
        Frame inertialFrame = FramesFactory.getEME2000();

        // Initial date
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC());

        // Initial orbit (GTO)
        final double a = 24396159; // semi major axis in meters
        final double e = 0.72831215; // eccentricity
        final double i = FastMath.toRadians(7); // inclination
        final double omega = FastMath.toRadians(180); // perigee argument
        final double raan = FastMath.toRadians(261); // right ascention of ascending node
        final double lM = 0; // mean anomaly
        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);
        final double period = initialOrbit.getKeplerianPeriod();

        // Initial state definition
        final SpacecraftState initialState = new SpacecraftState(initialOrbit);

        // Adaptive step integrator with a minimum step of 0.001 and a maximum step of 1000
        final double minStep = 0.001;
        final double maxStep = 1000.;
        final double dP = 1.e-2;
        final OrbitType orbType = OrbitType.CARTESIAN;
        final double[][] tol = NumericalPropagator.tolerances(dP, initialOrbit, orbType);
        final AbstractIntegrator integrator = new DormandPrince853Integrator(minStep, maxStep, tol[0], tol[1]);

        // Propagator
        NumericalPropagator numProp = new NumericalPropagator(integrator);
        numProp.setInitialState(initialState);
        numProp.setOrbitType(orbType);

        // Force Models:
        // 1 - Perturbing gravity field (only J2 is considered here)
        ForceModel gravity = new HolmesFeatherstoneAttractionModel(
                FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider);

        // Add force models to the propagator
        numProp.addForceModel(gravity);

        // Propagator factory
        PropagatorBuilder builder = new KeplerianPropagatorBuilder(mu, inertialFrame, OrbitType.KEPLERIAN,
                PositionAngle.TRUE);

        // Propagator converter
        PropagatorConverter fitter = new FiniteDifferencePropagatorConverter(builder, 1.e-6, 5000);

        // Resulting propagator
        KeplerianPropagator kepProp = (KeplerianPropagator) fitter.convert(numProp, 2 * period, 251);

        // Step handlers
        StatesHandler numStepHandler = new StatesHandler();
        StatesHandler kepStepHandler = new StatesHandler();

        // Set up operating mode for the propagator as master mode
        // with fixed step and specialized step handler
        numProp.setMasterMode(60., numStepHandler);
        kepProp.setMasterMode(60., kepStepHandler);

        // Extrapolate from the initial to the final date
        numProp.propagate(initialDate.shiftedBy(10. * period));
        kepProp.propagate(initialDate.shiftedBy(10. * period));

        // retrieve the states
        List<SpacecraftState> numStates = numStepHandler.getStates();
        List<SpacecraftState> kepStates = kepStepHandler.getStates();

        // Print the results on the output file
        File output = new File(new File(System.getProperty("user.home")), "elements.dat");
        PrintStream stream = new PrintStream(output);
        stream.println("# date Anum Akep Enum Ekep Inum Ikep LMnum LMkep");
        for (SpacecraftState numState : numStates) {
            for (SpacecraftState kepState : kepStates) {
                if (numState.getDate().compareTo(kepState.getDate()) == 0) {
                    stream.println(numState.getDate() + " " + numState.getA() + " " + kepState.getA() + " "
                            + numState.getE() + " " + kepState.getE() + " "
                            + FastMath.toDegrees(numState.getI()) + " " + FastMath.toDegrees(kepState.getI())
                            + " " + FastMath.toDegrees(MathUtils.normalizeAngle(numState.getLM(), FastMath.PI))
                            + " "
                            + FastMath.toDegrees(MathUtils.normalizeAngle(kepState.getLM(), FastMath.PI)));
                    break;
                }
            }
        }
        stream.close();
        System.out.println("Results saved as file " + output);

        File output1 = new File(new File(System.getProperty("user.home")), "elts_pv.dat");
        PrintStream stream1 = new PrintStream(output1);
        stream.println("# date pxn pyn pzn vxn vyn vzn pxk pyk pzk vxk vyk vzk");
        for (SpacecraftState numState : numStates) {
            for (SpacecraftState kepState : kepStates) {
                if (numState.getDate().compareTo(kepState.getDate()) == 0) {
                    final double pxn = numState.getPVCoordinates().getPosition().getX();
                    final double pyn = numState.getPVCoordinates().getPosition().getY();
                    final double pzn = numState.getPVCoordinates().getPosition().getZ();
                    final double vxn = numState.getPVCoordinates().getVelocity().getX();
                    final double vyn = numState.getPVCoordinates().getVelocity().getY();
                    final double vzn = numState.getPVCoordinates().getVelocity().getZ();
                    final double pxk = kepState.getPVCoordinates().getPosition().getX();
                    final double pyk = kepState.getPVCoordinates().getPosition().getY();
                    final double pzk = kepState.getPVCoordinates().getPosition().getZ();
                    final double vxk = kepState.getPVCoordinates().getVelocity().getX();
                    final double vyk = kepState.getPVCoordinates().getVelocity().getY();
                    final double vzk = kepState.getPVCoordinates().getVelocity().getZ();
                    stream1.println(numState.getDate() + " " + pxn + " " + pyn + " " + pzn + " " + vxn + " "
                            + vyn + " " + vzn + " " + pxk + " " + pyk + " " + pzk + " " + vxk + " " + vyk + " "
                            + vzk);
                    break;
                }
            }
        }
        stream1.close();
        System.out.println("Results saved as file " + output1);

    } catch (OrekitException oe) {
        System.err.println(oe.getLocalizedMessage());
        System.exit(1);
    } catch (FileNotFoundException fnfe) {
        System.err.println(fnfe.getLocalizedMessage());
        System.exit(1);
    }
}

From source file:com.shoddytcg.server.GameServer.java

/**
 * If you don't know what this method does, you clearly don't know enough Java to be working on this.
 * @param args//from  w w  w.  j a  v  a  2 s  .  c om
 */
public static void main(String[] args) {
    /*
     * Pipe errors to a file
     */
    try {
        PrintStream p = new PrintStream(new File("./errors.txt"));
        System.setErr(p);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * Server settings
     */
    Options options = new Options();
    options.addOption("s", "settings", true, "Can be low, medium, or high.");
    options.addOption("p", "players", true, "Sets the max number of players.");
    options.addOption("ng", "nogui", false, "Starts server in headless mode.");
    options.addOption("ar", "autorun", false, "Runs without asking a single question.");
    options.addOption("h", "help", false, "Shows this menu.");

    if (args.length > 0) {

        CommandLineParser parser = new GnuParser();
        try {
            // parse the command line arguments
            CommandLine line = parser.parse(options, args);

            /*
             * The following sets the server's settings based on the
             * computing ability of the server specified by the server owner.
             */
            if (line.hasOption("settings")) {
                String settings = line.getOptionValue("settings");
                if (settings.equalsIgnoreCase("low")) {
                    m_movementThreads = 4;
                } else if (settings.equalsIgnoreCase("medium")) {
                    m_movementThreads = 8;
                } else if (settings.equalsIgnoreCase("high")) {
                    m_movementThreads = 12;
                } else {
                    System.err.println("Server requires a settings parameter");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("java GameServer [param] <args>", options);
                    System.exit(0);
                }
            } else {
                System.err.println("Server requires a settings parameter");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("java GameServer [param] <args>", options);
                System.exit(0);
            }

            if (line.hasOption("players")) {
                m_maxPlayers = Integer.parseInt(line.getOptionValue("players"));
                if (m_maxPlayers == 0 || m_maxPlayers == -1)
                    m_maxPlayers = 99999;
            } else {
                System.err.println("WARNING: No maximum player count provided. Will default to 500 players.");
                m_maxPlayers = 500;
            }

            if (line.hasOption("help")) {
                HelpFormatter formatter = new HelpFormatter();
                System.err.println("Server requires a settings parameter");
                formatter.printHelp("java GameServer [param] <args>", options);
            }

            /*
             * Create the server gui
             */
            @SuppressWarnings("unused")
            GameServer gs;
            if (line.hasOption("nogui")) {
                if (line.hasOption("autorun"))
                    gs = new GameServer(true);
                else
                    gs = new GameServer(false);
            } else {
                if (line.hasOption("autorun"))
                    System.out.println("autorun doesn't work with GUI");
                gs = new GameServer(false);
            }
        } catch (ParseException exp) {
            // oops, something went wrong
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java GameServer [param] <args>", options);
        }

    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        System.err.println("Server requires a settings parameter");
        formatter.printHelp("java GameServer [param] <args>", options);
    }
}

From source file:edu.cmu.tetrad.cli.search.FgsCli.java

/**
 * @param args the command line arguments
 *//*  ww  w  . j  av a2 s.  c  o m*/
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("fgs", MAIN_OPTIONS);
        return;
    }

    parseArgs(args);

    System.out.println("================================================================================");
    System.out.printf("FGS Discrete (%s)%n", DateTime.printNow());
    System.out.println("================================================================================");

    String argInfo = createArgsInfo();
    System.out.println(argInfo);
    LOGGER.info("=== Starting FGS Discrete: " + Args.toString(args, ' '));
    LOGGER.info(argInfo.trim().replaceAll("\n", ",").replaceAll(" = ", "="));

    Set<String> excludedVariables = (excludedVariableFile == null) ? Collections.EMPTY_SET
            : getExcludedVariables();

    runPreDataValidations(excludedVariables, System.err);
    DataSet dataSet = readInDataSet(excludedVariables);
    runOptionalDataValidations(dataSet, System.err);

    Path outputFile = Paths.get(dirOut.toString(), outputPrefix + ".txt");
    try (PrintStream writer = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String runInfo = createOutputRunInfo(excludedVariables, dataSet);
        writer.println(runInfo);
        String[] infos = runInfo.trim().replaceAll("\n\n", ";").split(";");
        for (String s : infos) {
            LOGGER.info(s.trim().replaceAll("\n", ",").replaceAll(":,", ":").replaceAll(" = ", "="));
        }

        Graph graph = runFgs(dataSet, writer);

        writer.println();
        writer.println(graph.toString());
    } catch (IOException exception) {
        LOGGER.error("FGS failed.", exception);
        System.err.printf("%s: FGS failed.%n", DateTime.printNow());
        System.out.println("Please see log file for more information.");
        System.exit(-128);
    }
    System.out.printf("%s: FGS finished!  Please see %s for details.%n", DateTime.printNow(),
            outputFile.getFileName().toString());
    LOGGER.info(
            String.format("FGS finished!  Please see %s for details.", outputFile.getFileName().toString()));
}

From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length < 5 || !areNCFiles(Arrays.copyOfRange(args, 3, args.length))) {
        throw new RuntimeException("Needs: \n" + "(1) mass value, e.g., 132.0772 for debugging, \n"
                + "(2) how many timepoints to process (-1 for all), \n"
                + "(3) prefix for .data and rendered .pdf \n" + "(4,5..) 2 or more NetCDF .nc files");
    }// w  ww.  j  ava2s . com

    String fmt = "pdf";
    Double mz = Double.parseDouble(args[0]);
    Integer numSpectraToProcess = Integer.parseInt(args[1]);
    String outPrefix = args[2];
    String outImg = outPrefix.equals("-") ? null : outPrefix + "." + fmt;
    String outData = outPrefix.equals("-") ? null : outPrefix + ".data";

    CompareTwoNetCDFAroundMass c = new CompareTwoNetCDFAroundMass();
    String[] netCDF_fnames = Arrays.copyOfRange(args, 3, args.length);
    List<List<Pair<Double, Double>>> spectra = c.getSpectraForMass(mz, netCDF_fnames, numSpectraToProcess);

    // Write data output to outfile
    PrintStream out = outData == null ? System.out : new PrintStream(new FileOutputStream(outData));

    // print out the spectra to outData
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        for (Pair<Double, Double> xy : spectraInFile) {
            out.format("%.4f\t%.4f\n", xy.getLeft(), xy.getRight());
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }
    // find the ymax across all spectra, so that we can have a uniform y scale
    Double yrange = 0.0;
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        Double ymax = 0.0;
        for (Pair<Double, Double> xy : spectraInFile) {
            Double intensity = xy.getRight();
            if (ymax < intensity)
                ymax = intensity;
        }
        if (yrange < ymax)
            yrange = ymax;
    }

    if (outData != null) {
        // if outData is != null, then we have written to .data file
        // now render the .data to the corresponding .pdf file

        // first close the .data
        out.close();

        // render outData to outFILE using gnuplo
        Gnuplotter plotter = new Gnuplotter();
        plotter.plot2D(outData, outImg, netCDF_fnames, "time in seconds", yrange, "intensity", fmt);
    }
}

From source file:edu.cmu.tetrad.cli.search.FgsDiscrete.java

/**
 * @param args the command line arguments
 *//*ww  w. ja  v a  2 s  .c o m*/
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("fgs-discrete", MAIN_OPTIONS);
        return;
    }

    parseArgs(args);

    System.out.println("================================================================================");
    System.out.printf("FGS Discrete (%s)%n", DateTime.printNow());
    System.out.println("================================================================================");

    String argInfo = createArgsInfo();
    System.out.println(argInfo);
    LOGGER.info("=== Starting FGS Discrete: " + Args.toString(args, ' '));
    LOGGER.info(argInfo.trim().replaceAll("\n", ",").replaceAll(" = ", "="));

    Set<String> excludedVariables = (excludedVariableFile == null) ? Collections.EMPTY_SET
            : getExcludedVariables();

    runPreDataValidations(excludedVariables, System.err);

    DataSet dataSet = readInDataSet(excludedVariables);

    runOptionalDataValidations(dataSet, System.err);

    Path outputFile = Paths.get(dirOut.toString(), outputPrefix + ".txt");
    try (PrintStream writer = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String runInfo = createOutputRunInfo(excludedVariables, dataSet);
        writer.println(runInfo);
        String[] infos = runInfo.trim().replaceAll("\n\n", ";").split(";");
        for (String s : infos) {
            LOGGER.info(s.trim().replaceAll("\n", ",").replaceAll(":,", ":").replaceAll(" = ", "="));
        }

        Graph graph = runFgsDiscrete(dataSet, writer);

        writer.println();
        writer.println(graph.toString());

        if (graphML) {
            writeOutGraphML(graph, Paths.get(dirOut.toString(), outputPrefix + "_graph.txt"));
        }
    } catch (IOException exception) {
        LOGGER.error("FGS Discrete failed.", exception);
        System.err.printf("%s: FGS Discrete failed.%n", DateTime.printNow());
        System.out.println("Please see log file for more information.");
        System.exit(-128);
    }
    System.out.printf("%s: FGS Discrete finished!  Please see %s for details.%n", DateTime.printNow(),
            outputFile.getFileName().toString());
    LOGGER.info(String.format("FGS Discrete finished!  Please see %s for details.",
            outputFile.getFileName().toString()));
}

From source file:edu.msu.cme.rdp.multicompare.Main.java

public static void main(String[] args) throws Exception {
    PrintStream hier_out = null;/*w w w. ja  va  2 s. c  o  m*/
    PrintWriter assign_out = new PrintWriter(new NullWriter());
    PrintStream bootstrap_out = null;
    File hier_out_filename = null;
    String propFile = null;
    File biomFile = null;
    File metadataFile = null;
    PrintWriter shortseq_out = null;
    List<MCSample> samples = new ArrayList();
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    float conf = CmdOptions.DEFAULT_CONF;
    String gene = null;
    int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        } else {
            throw new IllegalArgumentException("Require the output file for classification assignment");
        }
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT));
            hier_out = new PrintStream(hier_out_filename);
        }
        if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) {
            biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) {
            metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT));
        }

        if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) {
            if (gene != null) {
                throw new IllegalArgumentException(
                        "Already specified the gene from the default location. Can not specify train_propfile");
            } else {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) {
            String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT);
            if (f.equalsIgnoreCase("allrank")) {
                format = ClassificationResultFormatter.FORMAT.allRank;
            } else if (f.equalsIgnoreCase("fixrank")) {
                format = ClassificationResultFormatter.FORMAT.fixRank;
            } else if (f.equalsIgnoreCase("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("biom")) {
                format = ClassificationResultFormatter.FORMAT.biom;
            } else {
                throw new IllegalArgumentException(
                        "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (propFile != null) {
                throw new IllegalArgumentException(
                        "Already specified train_propfile. Can not specify gene any more");
            }
            gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase();

            if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE)
                    && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) {
                throw new IllegalArgumentException(gene + " not found, choose from"
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + ", "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) {
            min_bootstrap_words = Integer
                    .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT));
            if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) {
                throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT
                        + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS);
            }
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT);
            try {
                conf = Float.valueOf(confString);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Confidence must be a decimal number");
            }

            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) {
            shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) {
            bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT));
        }

        if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) {
            throw new IllegalArgumentException("biom format requires an input biom file");
        }
        if (biomFile != null) { // if input biom file provided, use biom format
            format = ClassificationResultFormatter.FORMAT.biom;
        }

        args = line.getArgs();
        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            File inputFile = new File(inFileNames[0]);
            File idmappingFile = null;
            if (!inputFile.exists()) {
                throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\"");
            }
            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\"");
                }
            }

            MCSample nextSample = new MCSample(inputFile, idmappingFile);
            samples.add(nextSample);
        }
        if (propFile == null && gene == null) {
            gene = CmdOptions.DEFAULT_GENE;
        }
        if (samples.size() < 1) {
            throw new IllegalArgumentException("Require at least one sample files");
        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, "");
        return;
    }

    MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile);
    MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format,
            min_bootstrap_words);
    assign_out.close();
    if (hier_out != null) {
        DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples);
        result.getRoot().topDownVisit(printVisitor);
        hier_out.close();
        if (multiClassifier.hasCopyNumber()) {
            // print copy number corrected counts
            File cn_corrected_s = new File(hier_out_filename.getParentFile(),
                    "cnadjusted_" + hier_out_filename.getName());
            PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s);
            printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true);
            result.getRoot().topDownVisit(printVisitor);
            cn_corrected_hier_out.close();
        }
    }

    if (bootstrap_out != null) {
        for (MCSample sample : samples) {
            MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample);
        }
        bootstrap_out.close();
    }

    if (shortseq_out != null) {
        for (String id : result.getBadSequences()) {
            shortseq_out.write(id + "\n");
        }
        shortseq_out.close();
    }

}

From source file:com.guns.media.tools.yuv.MediaTool.java

/**
 * @param args the command line arguments
 *//* w  ww . j  a  v a 2 s  .co m*/
public static void main(String[] args) throws IOException {

    try {
        Options options = getOptions();
        CommandLine cmd = null;
        int offset = 0;
        CommandLineParser parser = new GnuParser();
        cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            printHelp(options);
            exit(1);
        }

        if (cmd.hasOption("offset")) {
            offset = new Integer(cmd.getOptionValue("offset"));
        }
        int frame = new Integer(cmd.getOptionValue("f"));

        //  int scale = new Integer(args[2]);
        BufferedInputStream if1 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if1")));
        BufferedInputStream if2 = new BufferedInputStream(new FileInputStream(cmd.getOptionValue("if2")));

        DataStorage.create(new Integer(cmd.getOptionValue("f")));

        int width = new Integer(cmd.getOptionValue("w"));
        int height = new Integer(cmd.getOptionValue("h"));
        LookUp.initSSYUV(width, height);
        //  int[][] frame1 = new int[width][height];
        //  int[][] frame2 = new int[width][height];
        int nRead;
        int fRead;
        byte[] data = new byte[width * height + ((width * height) / 2)];
        byte[] data1 = new byte[width * height + ((width * height) / 2)];
        int frames = 0;
        long start_ms = System.currentTimeMillis() / 1000L;
        long end_ms = start_ms;

        if (offset > 0) {
            if1.skip(((width * height + ((width * height) / 2)) * offset));
        } else if (offset < 0) {
            if2.skip(((width * height + ((width * height) / 2)) * (-1 * offset)));
        }

        if (cmd.hasOption("psnr")) {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                PSNRCalculatorThread wt = new PSNRCalculatorThread(data_out, data1_out, frames, width, height);
                executor.execute(wt);
                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis();

            System.out.println("Frame Rate :" + frames * 1000 / ((end_ms - start_ms)));
            for (int i = 0; i < frames; i++) {
                System.out.println(
                        i + "," + 10 * Math.log10((255 * 255) / (DataStorage.getFrame(i) / (width * height))));

            }
        }
        if (cmd.hasOption("sub")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                ImageSubstractThread wt = new ImageSubstractThread(data_out, data1_out, frames, width, height,
                        raf);
                //wt.run();
                executor.execute(wt);

                frames++;

            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            raf.close();
        }
        if (cmd.hasOption("ss") && !cmd.getOptionValue("o").matches("-")) {

            RandomAccessFile raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw");

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        raf);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                executor.execute(wt);
            }
            executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;

            while (!executor.isTerminated()) {

            }

            raf.close();
        }
        if (cmd.hasOption("ss") && cmd.getOptionValue("o").matches("-")) {

            PrintStream stdout = new PrintStream(System.out);

            // RandomAccessFile ra =  new RandomAccessFile(cmd.getOptionValue("o"), "rw");
            // MappedByteBuffer raf = new RandomAccessFile(cmd.getOptionValue("o"), "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, ((width*height)+(width*height/2))*frame);
            // ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1) && frames < frame) {
                byte[] data_out = data.clone();
                byte[] data1_out = data1.clone();

                SidebySideImageThread wt = new SidebySideImageThread(data_out, data1_out, frames, width, height,
                        stdout);
                // MPSidebySideImageThread wt = new MPSidebySideImageThread(data_out, data1_out, frames, width, height, ra);
                frames++;
                // wt.run();

                wt.run();
            }

            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));

            stdout.close();
        }
        if (cmd.hasOption("image")) {

            System.setProperty("java.awt.headless", "true");
            //ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
            ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
            while ((nRead = if1.read(data)) != -1 && ((fRead = if2.read(data1)) != -1)) {

                if (frames == frame) {
                    byte[] data_out = data.clone();
                    byte[] data1_out = data1.clone();

                    Frame f1 = new Frame(data_out, width, height, Frame.YUV420);
                    Frame f2 = new Frame(data1_out, width, height, Frame.YUV420);
                    //       System.out.println(cmd.getOptionValue("o"));
                    ExtractImageThread wt = new ExtractImageThread(f1, frames,
                            cmd.getOptionValue("if1") + "frame1-" + cmd.getOptionValue("o"));
                    ExtractImageThread wt1 = new ExtractImageThread(f2, frames,
                            cmd.getOptionValue("if2") + "frame2-" + cmd.getOptionValue("o"));
                    //   executor.execute(wt);
                    executor.execute(wt);
                    executor.execute(wt1);
                }
                frames++;

            }
            executor.shutdown();
            //  executor.shutdown();
            end_ms = System.currentTimeMillis() / 1000L;
            System.out.println("Frame Rate :" + frames / ((end_ms - start_ms)));
        }

    } catch (ParseException ex) {
        Logger.getLogger(MediaTool.class.getName()).log(Level.SEVERE, null, ex);
    }
}