List of usage examples for java.io PrintStream PrintStream
public PrintStream(File file) throws FileNotFoundException
From source file:edu.oregonstate.eecs.mcplan.domains.blackjack.Experiments.java
/** * @param args/*w w w . j ava 2 s .co m*/ * @throws FileNotFoundException */ public static void main(final String[] args) throws FileNotFoundException { final PrintStream data_out = new PrintStream("data_r2.csv"); data_out.println("abstraction,game,Ngames,Nepisodes,p,mean,var,conf"); final BlackjackParameters params = new BlackjackParameters(); final BlackjackMdp mdp = new BlackjackMdp(params); System.out.println("Solving MDP"); final Pair<String[][], String[][]> soln = mdp.solve(); final String[][] hard_actions = soln.first; final String[][] soft_actions = soln.second; // for( final int Nepisodes : new int[] { 512, 1024 } ) { // runExperiment( new IdentityRepresenter(), Nepisodes, 0.0, Ngames, data_out ); // runExperiment( new BlackjackAggregator(), Nepisodes, 0.0, Ngames, data_out ); // runExperiment( new NoisyAStarAggregator( rng, 0.0 ), Nepisodes, 0.0, Ngames, data_out ); // } // for( final int Nepisodes : new int[] { 4, 8, 16, 32, 64, 128, 256, 512, 1024 } ) { // for( final double p : new double[] { 0.02, 0.04, 0.08, 0.16, 0.32 } ) { // runExperiment( new NoisyAStarAggregator( rng, p ), Nepisodes, p, Ngames, data_out ); // } // } final int Ngames = 100000; for (final int Nepisodes : new int[] { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 }) { // for( final int Nepisodes : new int[] { 8192 } ) { for (final double p : new double[] { 0, 0.3 }) { runExperiment(new NoisyAStarAggregator(rng, p, hard_actions, soft_actions, params), params, Nepisodes, p, Ngames, data_out); } runExperiment(new BlackjackAggregator(), params, Nepisodes, 0.0, Ngames, data_out); runExperiment(new BlackjackPrimitiveRepresenter(), params, Nepisodes, 0.0, Ngames, data_out); } }
From source file:net.k3rnel.arena.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/* w ww .ja va2 s . c o m*/ */ 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.msu.cme.rdp.unifrac.Unifrac.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); CommandLine line = null;/* w w w.j a v a 2 s. c o m*/ try { line = parser.parse(options, args); } catch (UnrecognizedOptionException e) { System.err.println(e.getMessage()); printUsage(); return; } UnifracTree unifracTree = null; PrintStream out = System.out; if (line.hasOption("tree") && line.hasOption("sequence-files")) { printUsage(); } else if (!(line.hasOption("weighted") || line.hasOption("unweighted") || line.hasOption("significance"))) { System.err.println("Must specify at least one calculation option"); printUsage(); } else if (line.hasOption("sample-mapping")) { Map<String, UnifracSample> sampleMap = readSampleMap(line.getOptionValue("sample-mapping")); if (line.hasOption("tree")) { unifracTree = parseNewickTree(line.getOptionValue("tree"), sampleMap); } } else { if (!line.hasOption("sample-mapping")) { System.err.println("A sample mapping file must be provided"); } printUsage(); } if (line.hasOption("outfile")) { out = new PrintStream(line.getOptionValue("outfile")); } if (unifracTree != null) { if (line.hasOption("unweighted")) { printResults(out, unifracTree.computeUnifrac(), "Unweighted Unifrac"); if (line.hasOption("significance")) { printResults(out, unifracTree.computeUnifracSig(1000, false), "Unweighted Unifrac Significance"); } } if (line.hasOption("weighted")) { printResults(out, unifracTree.computeWeightedUnifrac(), "Weighted Unifrac"); if (line.hasOption("significance")) { printResults(out, unifracTree.computeUnifracSig(1000, true), "Weighted Unifrac Significance"); } } } }
From source file:edu.oregonstate.eecs.mcplan.domains.yahtzee2.subtask.StraightMdp.java
public static void main(final String[] argv) throws FileNotFoundException { // final StraightMdp M = new StraightMdp( false ); // final YahtzeeDiceState s = new YahtzeeDiceState( new Hand( new int[] { 0, 2, 2, 1, 0, 0 } ), 1 ); // final KeepAction a = new KeepAction( new int[] { 0, 1, 1, 0, 0, 0 } ); ///*ww w . ja v a2s . c o m*/ // final Pair<ArrayList<YahtzeeDiceState>, ArrayList<Double>> P = M.sparseP( s, a ); // // for( int i = 0; i < P.first.size(); ++i ) { // System.out.println( P.first.get( i ) + " (" + P.second.get( i ) + ")" ); // } final RandomGenerator rng = new MersenneTwister(42); final double discount = 1.0; final boolean small = false; final StraightMdp mdp = new StraightMdp(small); final int Nfeatures = Hand.Nfaces + 1; // +1 for rerolls final SparseValueIterationSolver<YahtzeeDiceState, YahtzeeAction> vi = new SparseValueIterationSolver<YahtzeeDiceState, YahtzeeAction>( mdp, discount, 1e-16); vi.run(); final ArrayList<Attribute> attr = new ArrayList<Attribute>(); attr.addAll(YahtzeeSubtaskStateSpace.attributes()); attr.add(WekaUtil.createNominalAttribute("__label__", mdp.A().cardinality())); final Instances instances = WekaUtil .createEmptyInstances("yahtzee_straight_" + (small ? "small" : "large") + "_pistar", attr); final Policy<YahtzeeDiceState, YahtzeeAction> pistar = vi.pistar(); final Generator<YahtzeeDiceState> g = mdp.S().generator(); while (g.hasNext()) { final YahtzeeDiceState s = g.next(); if (s.isTerminal()) { continue; } pistar.setState(s, 0L); final YahtzeeAction astar = pistar.getAction(); System.out.println("" + s + " -> " + astar); final double[] phi = new double[Nfeatures + 1]; int idx = 0; for (int i = 0; i < Hand.Nfaces; ++i) { phi[idx++] = s.hand.dice[i]; } phi[idx++] = s.rerolls; phi[Nfeatures] = mdp.A().index(astar); WekaUtil.addInstance(instances, new DenseInstance(1.0, phi)); } WekaUtil.writeDataset(new File("."), instances); final Csv.Writer csv = new Csv.Writer( new PrintStream(new FileOutputStream(new File(instances.relationName() + "_action-key.csv")))); for (final Map.Entry<ValueType<int[]>, Integer> e : YahtzeeSubtaskActionSpace.index_map.entrySet()) { csv.cell(e.getValue()).cell(new KeepAction(e.getKey().get())).newline(); } // final MeanVarianceAccumulator ret = new MeanVarianceAccumulator(); // final MeanVarianceAccumulator steps = new MeanVarianceAccumulator(); // final int Ngames = 100000; // for( int i = 0; i < Ngames; ++i ) { // final FuelWorldState s0; // if( choices ) { // s0 = FuelWorldState.createDefaultWithChoices( rng ); // } // else { // s0 = FuelWorldState.createDefault( rng ); // } // final FuelWorldSimulator sim = new FuelWorldSimulator( s0 ); // // final Episode<FuelWorldState, FuelWorldAction> episode // = new Episode<FuelWorldState, FuelWorldAction>( sim, JointPolicy.create( pistar ) ); // final RewardAccumulator<FuelWorldState, FuelWorldAction> racc // = new RewardAccumulator<FuelWorldState, FuelWorldAction>( sim.nagents(), discount ); // episode.addListener( racc ); // // final long tstart = System.nanoTime(); // episode.run(); // final long tend = System.nanoTime(); // final double elapsed_ms = (tend - tstart) * 1e-6; // // ret.add( racc.v()[0] ); // steps.add( racc.steps() ); // } // // System.out.println( "****************************************" ); // System.out.println( "Average return: " + ret.mean() ); // System.out.println( "Return variance: " + ret.variance() ); // System.out.println( "Confidence: " + ret.confidence() ); // System.out.println( "Steps (mean): " + steps.mean() ); // System.out.println( "Steps (var): " + steps.variance() ); }
From source file:edu.msu.cme.rdp.graph.utils.ContigMerger.java
public static void main(String[] args) throws IOException { final BufferedReader hmmgsResultReader; final IndexedSeqReader nuclContigReader; final double minBits; final int minProtLength; final Options options = new Options(); final PrintStream out; final ProfileHMM hmm; final FastaWriter protSeqOut; final FastaWriter nuclSeqOut; final boolean prot; final boolean all; final String shortSampleName; options.addOption("a", "all", false, "Generate all combinations for multiple paths, instead of just the best"); options.addOption("b", "min-bits", true, "Minimum bits score"); options.addOption("l", "min-length", true, "Minimum length"); options.addOption("s", "short_samplename", true, "short sample name, to be used as part of contig identifiers. This allow analyzing contigs together from different samples in downstream analysis "); options.addOption("o", "out", true, "Write output to file instead of stdout"); try {//from w w w .j a v a 2 s. c o m CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("min-bits")) { minBits = Double.valueOf(line.getOptionValue("min-bits")); } else { minBits = Double.NEGATIVE_INFINITY; } if (line.hasOption("min-length")) { minProtLength = Integer.valueOf(line.getOptionValue("min-length")); } else { minProtLength = 0; } if (line.hasOption("short_samplename")) { shortSampleName = line.getOptionValue("short_samplename") + "_"; } else { shortSampleName = ""; } if (line.hasOption("out")) { out = new PrintStream(line.getOptionValue("out")); } else { out = System.err; } all = line.hasOption("all"); args = line.getArgs(); if (args.length != 3) { throw new Exception("Unexpected number of arguments"); } hmmgsResultReader = new BufferedReader(new FileReader(new File(args[1]))); nuclContigReader = new IndexedSeqReader(new File(args[2])); hmm = HMMER3bParser.readModel(new File(args[0])); prot = (hmm.getAlphabet() == SequenceType.Protein); if (prot) { protSeqOut = new FastaWriter(new File("prot_merged.fasta")); } else { protSeqOut = null; } nuclSeqOut = new FastaWriter(new File("nucl_merged.fasta")); } catch (Exception e) { new HelpFormatter().printHelp("USAGE: ContigMerger [options] <hmm> <hmmgs_file> <nucl_contig>", options); System.err.println("Error: " + e.getMessage()); System.exit(1); throw new RuntimeException("I hate you javac"); } String line; SearchDirection lastDir = SearchDirection.left; //So this has an assumption built in //It depends on hmmgs always outputting left fragments, then right //We can't just use the kmer to figure out if we've switched to another starting point //because we allow multiple starting model pos, so two different starting //positions can have the same starting kmer Map<String, Sequence> leftContigs = new HashMap(); Map<String, Sequence> rightContigs = new HashMap(); int contigsMerged = 0; int writtenMerges = 0; long startTime = System.currentTimeMillis(); String kmer = null; String geneName = null; while ((line = hmmgsResultReader.readLine()) != null) { if (line.startsWith("#")) { continue; } String[] lexemes = line.trim().split("\t"); if (lexemes.length != 12 || lexemes[0].equals("-")) { System.err.println("Skipping line: " + line); continue; } //contig_53493 nirk 1500:6:35:16409:3561/1 ADV15048 tcggcgctctacacgttcctgcagcccggg 40 210 70 left -44.692 184 0 int index = 0; String seqid = lexemes[0]; geneName = lexemes[1]; String readid = lexemes[2]; String refid = lexemes[3]; kmer = lexemes[4]; int modelStart = Integer.valueOf(lexemes[5]); int nuclLength = Integer.valueOf(lexemes[6]); int protLength = Integer.valueOf(lexemes[7]); SearchDirection dir = SearchDirection.valueOf(lexemes[8]); if (dir != lastDir) { if (dir == SearchDirection.left) { List<MergedContig> mergedContigs = all ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm) : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm); contigsMerged++; for (MergedContig mc : mergedContigs) { String mergedId = shortSampleName + geneName + "_" + mc.leftContig + "_" + mc.rightContig; out.println(mergedId + "\t" + mc.length + "\t" + mc.score); if (mc.score > minBits && mc.length > minProtLength) { if (prot) { protSeqOut.writeSeq(mergedId, mc.protSeq); } nuclSeqOut.writeSeq(mergedId, mc.nuclSeq); writtenMerges++; } } leftContigs.clear(); rightContigs.clear(); } lastDir = dir; } Sequence seq = nuclContigReader.readSeq(seqid); if (dir == SearchDirection.left) { leftContigs.put(seqid, seq); } else if (dir == SearchDirection.right) { rightContigs.put(seqid, seq); } else { throw new IOException("Cannot handle search direction " + dir); } } if (!leftContigs.isEmpty() || !rightContigs.isEmpty()) { List<MergedContig> mergedContigs = all ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm) : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm); for (MergedContig mc : mergedContigs) { String mergedId = shortSampleName + mc.gene + "_" + mc.leftContig + "_" + mc.rightContig; out.println(mergedId + "\t" + mc.length + "\t" + mc.score); contigsMerged++; if (mc.score > minBits && mc.length > minProtLength) { if (prot) { protSeqOut.writeSeq(mergedId, mc.protSeq); } nuclSeqOut.writeSeq(mergedId, mc.nuclSeq); writtenMerges++; } } } out.close(); if (prot) { protSeqOut.close(); } nuclSeqOut.close(); System.err.println("Read in " + contigsMerged + " contigs, wrote out " + writtenMerges + " merged contigs in " + ((double) (System.currentTimeMillis() - startTime) / 1000) + "s"); }
From source file:edu.msu.cme.rdp.alignment.pairwise.PairwiseKNN.java
public static void main(String[] args) throws Exception { File queryFile;/*from ww w. j ava 2 s.c o m*/ File refFile; AlignmentMode mode = AlignmentMode.glocal; int k = 1; int wordSize = 0; int prefilter = 10; // The top p closest protein targets PrintStream out = new PrintStream(System.out); Options options = new Options(); options.addOption("m", "mode", true, "Alignment mode {global, glocal, local, overlap, overlap_trimmed} (default= glocal)"); options.addOption("k", true, "K-nearest neighbors to return. (default = 1)"); options.addOption("o", "out", true, "Redirect output to file instead of stdout"); options.addOption("p", "prefilter", true, "The top p closest targets from kmer prefilter step. Set p=0 to disable the prefilter step. (default = 10) "); options.addOption("w", "word-size", true, "The word size used to find closest targets during prefilter. (default " + ProteinWordGenerator.WORDSIZE + " for protein, " + GoodWordIterator.DEFAULT_WORDSIZE + " for nucleotide)"); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("mode")) { mode = AlignmentMode.valueOf(line.getOptionValue("mode")); } if (line.hasOption('k')) { k = Integer.valueOf(line.getOptionValue('k')); if (k < 1) { throw new Exception("k must be at least 1"); } } if (line.hasOption("word-size")) { wordSize = Integer.parseInt(line.getOptionValue("word-size")); if (wordSize < 3) { throw new Exception("Word size must be at least 3"); } } if (line.hasOption("prefilter")) { prefilter = Integer.parseInt(line.getOptionValue("prefilter")); // prefilter == 0 means no prefilter if (prefilter > 0 && prefilter < k) { throw new Exception("prefilter must be at least as big as k " + k); } } if (line.hasOption("out")) { out = new PrintStream(line.getOptionValue("out")); } args = line.getArgs(); if (args.length != 2) { throw new Exception("Unexpected number of command line arguments"); } queryFile = new File(args[0]); refFile = new File(args[1]); } catch (Exception e) { new HelpFormatter().printHelp("PairwiseKNN <options> <queryFile> <dbFile>", options); System.err.println("ERROR: " + e.getMessage()); return; } PairwiseKNN theObj = new PairwiseKNN(queryFile, refFile, out, mode, k, wordSize, prefilter); theObj.match(); }
From source file:eu.learnpad.simulator.mon.MainMonitoring.java
/** * Read the properties and init the connections to the enterprise service bus * /*w w w.j a va 2 s .com*/ * @param is the systemSettings file */ public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream("glimpseLog.log"); PrintStream ps = new PrintStream(fos); System.setErr(ps); if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) { System.out.println("Running ActiveMQ instance on " + environmentParameters.getProperty("java.naming.provider.url")); ActiveMQRunner anActiveMQInstance = new ActiveMQRunner( environmentParameters.getProperty("java.naming.provider.url")); new Thread(anActiveMQInstance).start(); while (!anActiveMQInstance.isBrokerStarted()) { Thread.sleep(1000); } System.out.println("ActiveMQ is running"); System.out.println("Running GLIMPSE"); SplashScreen.Show(); System.out.println("Please wait until setup is done..."); //the buffer where the events are stored to be analyzed, in this version //the buffer object is not used because Drools has it's own eventStream object EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>(); //The complex event engine that will be used (in this case drools) ComplexEventProcessor engineOne = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE), buffer, connFact, initConn); engineOne.start(); RestNotifier notifierEngine = new RestNotifier(); notifierEngine.start(); //using H2 database DBController databaseController = new H2Controller(Manager.Read(DATABASECONNECTIONSTRINGH2)); //using MYSQL database //DBController databaseController = new MySqlController(Manager.Read(DATABASECONNECTIONSTRINGMYSQL)); LearnerAssessmentManager lam = new LearnerAssessmentManagerImpl(databaseController); lam.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } RuleTemplateManager templateManager = new RuleTemplateManager(DROOLSRULEREQUESTTEMPLATE1, DROOLSRULEREQUESTTEMPLATE2, DROOLSRULEREQUESTTEMPLATE3_1, DROOLSRULEREQUESTTEMPLATE3_2); //the component in charge to locate services and load specific rules. ServiceLocatorFactory.getServiceLocatorParseViolationReceivedFromBSM(engineOne, templateManager, REGEXPATTERNFILEPATH).start(); //start MailNotifier component MailNotification mailer = new MailNotification(Manager.Read(MAILNOTIFICATIONSETTINGSFILEPATH)); mailer.start(); //the manager of all the architecture GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn, engineOne.getRuleManager(), lam); manager.start(); } } catch (Exception e) { System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\""); } }
From source file:edu.ntnu.EASY.Main.java
public static void main(String[] args) { CommandLine cl = null;//from w ww . j a v a 2 s. c o m CommandLineParser clp = new BasicParser(); HelpFormatter hf = new HelpFormatter(); try { cl = clp.parse(options, args); } catch (ParseException e) { e.printStackTrace(); hf.printHelp(USAGE, options); System.exit(1); } if (cl.hasOption('h') || cl.hasOption('?')) { hf.printHelp(USAGE, options); System.exit(0); } Environment env = new Environment(); env.populationSize = Integer.parseInt(cl.getOptionValue('p', "200")); env.maxGenerations = Integer.parseInt(cl.getOptionValue('g', "1000")); env.fitnessThreshold = 2.0; env.mutationRate = Double.parseDouble(cl.getOptionValue('m', "0.01")); env.crossoverRate = Double.parseDouble(cl.getOptionValue('c', "0.01")); env.numChildren = Integer.parseInt(cl.getOptionValue('b', "200")); env.numParents = Integer.parseInt(cl.getOptionValue('f', "20")); env.rank = Integer.parseInt(cl.getOptionValue('r', "10")); env.elitism = Integer.parseInt(cl.getOptionValue('e', "3")); ParentSelector<double[]> parentSelector = null; int parent = Integer.parseInt(cl.getOptionValue('P', "1")); switch (parent) { case 1: parentSelector = new FitnessProportionateSelector<double[]>(env.numParents); break; case 2: parentSelector = new RankSelector<double[]>(env.rank); break; case 3: parentSelector = new SigmaScaledSelector<double[]>(env.numParents); break; case 4: parentSelector = new TournamentSelector<double[]>(env.rank, env.numParents); break; case 5: parentSelector = new StochasticTournamentSelector<double[]>(env.rank, env.numParents, 0.3); break; case 6: parentSelector = new BoltzmanSelector<double[]>(env.numParents); break; default: System.out.printf("No such parent selector: %d%n", parent); hf.printHelp(USAGE, options); System.exit(1); } AdultSelector<double[]> adultSelector = null; int adult = Integer.parseInt(cl.getOptionValue('A', "1")); switch (adult) { case 1: adultSelector = new FullGenerationalReplacement<double[]>(); break; case 2: adultSelector = new GenerationalMixing<double[]>(env.numAdults); break; case 3: adultSelector = new Overproduction<double[]>(env.numAdults); break; default: System.out.printf("No such adult selector: %d%n", adult); hf.printHelp(USAGE, options); System.exit(1); } String targetFile = cl.getOptionValue('t', "target.dat"); double[] target = null; try { target = Util.readTargetSpikeTrain(targetFile); } catch (IOException e) { System.out.printf("Couldn't read target file: %s%n", targetFile); hf.printHelp(USAGE, options); System.exit(1); } FitnessCalculator<double[]> fitCalc = null; int calc = Integer.parseInt(cl.getOptionValue('C', "1")); switch (calc) { case 1: fitCalc = new SpikeTimeFitnessCalculator(target); break; case 2: fitCalc = new SpikeIntervalFitnessCalculator(target); break; case 3: fitCalc = new WaveformFitnessCalculator(target); break; default: System.out.printf("No such fitness calculator: %d%n", calc); hf.printHelp(USAGE, options); System.exit(1); } String output = cl.getOptionValue('o', "neuron"); Incubator<double[], double[]> incubator = new NeuronIncubator( new NeuronReplicator(env.mutationRate, env.crossoverRate), env.numChildren); Evolution<double[], double[]> evo = new Evolution<double[], double[]>(fitCalc, adultSelector, parentSelector, incubator); NeuronReport report = new NeuronReport(env.maxGenerations); evo.runEvolution(env, report); try { PrintStream ps = new PrintStream(new FileOutputStream(output + ".log")); report.writeToStream(ps); } catch (FileNotFoundException e) { System.out.printf("Could not write to %s.log%n", output); } double[] bestPhenome = report.getBestPhenome(); Plot train = Plot.newPlot("Neuron").setAxis("x", "ms").setAxis("y", "activation") .with("bestPhenome", bestPhenome).with("target", target).make(); double[] averageFitness = report.getAverageFitness(); double[] bestFitness = report.getBestFitness(); Plot fitness = Plot.newPlot("Fitness").setAxis("x", "generation").setAxis("y", "fitness") .with("average", averageFitness).with("best", bestFitness).make(); train.plot(); fitness.plot(); train.writeToFile(output + "-train"); fitness.writeToFile(output + "-fitness"); }
From source file:edu.msu.cme.rdp.alignment.errorcheck.RmPartialSeqs.java
/** * This program detects partial sequences based on the best pairwise alignment for each query sequence, * @param args/*from w ww . jav a 2 s . c om*/ * @throws Exception */ public static void main(String[] args) throws Exception { String trainseqFile = null; String queryFile = null; PrintStream seqOutStream = null; PrintStream alignOutStream = null; AlignmentMode mode = AlignmentMode.overlap; int k = 10; int min_gaps = 50; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("alignment-mode")) { String m = line.getOptionValue("alignment-mode").toLowerCase(); mode = AlignmentMode.valueOf(m); } if (line.hasOption("min_gaps")) { min_gaps = Integer.parseInt(line.getOptionValue("min_gaps")); } if (line.hasOption("knn")) { k = Integer.parseInt(line.getOptionValue("knn")); } if (line.hasOption("alignment-out")) { alignOutStream = new PrintStream(new File(line.getOptionValue("alignment-out"))); } args = line.getArgs(); if (args.length != 3) { throw new Exception("wrong number of arguments"); } trainseqFile = args[0]; queryFile = args[1]; seqOutStream = new PrintStream(new File(args[2])); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); new HelpFormatter().printHelp(80, " [options] fulllengthSeqFile queryFile passedSeqOutFile\n sequences can be either protein or nucleotide", "", options, ""); return; } RmPartialSeqs theObj = new RmPartialSeqs(trainseqFile, queryFile, mode, k, min_gaps); theObj.checkPartial(seqOutStream, alignOutStream); }
From source file:io.compgen.cgpipe.CGPipe.java
public static void main(String[] args) { String fname = null;/*from www .j a va2 s . co m*/ String logFilename = null; String outputFilename = null; PrintStream outputStream = null; int verbosity = 0; boolean silent = false; boolean dryrun = false; boolean silenceStdErr = false; boolean showHelp = false; List<String> targets = new ArrayList<String>(); Map<String, VarValue> confVals = new HashMap<String, VarValue>(); String k = null; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (i == 0) { if (new File(arg).exists()) { fname = arg; silenceStdErr = true; continue; } } else if (args[i - 1].equals("-f")) { fname = arg; continue; } else if (args[i - 1].equals("-l")) { logFilename = arg; continue; } else if (args[i - 1].equals("-o")) { outputFilename = arg; continue; } if (arg.equals("-h") || arg.equals("-help") || arg.equals("--help")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } showHelp = true; } else if (arg.equals("-license")) { license(); System.exit(1); } else if (arg.equals("-s")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } silent = true; } else if (arg.equals("-nolog")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } silenceStdErr = true; } else if (arg.equals("-v")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } verbosity++; } else if (arg.equals("-vv")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } verbosity += 2; } else if (arg.equals("-vvv")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } verbosity += 3; } else if (arg.equals("-dr")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } dryrun = true; } else if (arg.startsWith("--")) { if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } k = arg.substring(2); } else if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } if (confVals.containsKey(k)) { try { VarValue val = confVals.get(k); if (val.getClass().equals(VarList.class)) { ((VarList) val).add(VarValue.parseStringRaw(arg)); } else { VarList list = new VarList(); list.add(val); list.add(VarValue.parseStringRaw(arg)); confVals.put(k, list); } } catch (VarTypeException e) { System.err.println("Error setting variable: " + k + " => " + arg); System.exit(1); ; } } else { confVals.put(k, VarValue.parseStringRaw(arg)); } k = null; } else if (arg.charAt(0) != '-') { targets.add(arg); } } if (k != null) { if (k.contains("-")) { k = k.replaceAll("-", "_"); } confVals.put(k, VarBool.TRUE); } confVals.put("cgpipe.loglevel", new VarInt(verbosity)); if (fname == null) { usage(); System.exit(1); } if (!showHelp) { switch (verbosity) { case 0: SimpleFileLoggerImpl.setLevel(Level.INFO); break; case 1: SimpleFileLoggerImpl.setLevel(Level.DEBUG); break; case 2: SimpleFileLoggerImpl.setLevel(Level.TRACE); break; case 3: default: SimpleFileLoggerImpl.setLevel(Level.ALL); break; } } else { SimpleFileLoggerImpl.setLevel(Level.FATAL); } SimpleFileLoggerImpl.setSilent(silenceStdErr || showHelp); Log log = LogFactory.getLog(CGPipe.class); log.info("Starting new run: " + fname); if (logFilename != null) { confVals.put("cgpipe.log", new VarString(logFilename)); } if (System.getenv("CGPIPE_DRYRUN") != null && !System.getenv("CGPIPE_DRYRUN").equals("")) { dryrun = true; } JobRunner runner = null; try { // Load config values from global config. RootContext root = new RootContext(); loadInitFiles(root); // Load settings from environment variables. root.loadEnvironment(); // Set cmd-line arguments if (silent) { root.setOutputStream(null); } if (outputFilename != null) { outputStream = new PrintStream(new FileOutputStream(outputFilename)); root.setOutputStream(outputStream); } for (String k1 : confVals.keySet()) { log.info("config: " + k1 + " => " + confVals.get(k1).toString()); } root.update(confVals); root.set("cgpipe.procs", new VarInt(Runtime.getRuntime().availableProcessors())); // update the URL Source loader configs SourceLoader.updateRemoteHandlers(root.cloneString("cgpipe.remote")); // Now check for help, only after we've setup the remote handlers... if (showHelp) { try { Parser.showHelp(fname); System.exit(0); } catch (IOException e) { System.err.println("Unable to find pipeline: " + fname); System.exit(1); } } // Set the global config values // globalConfig.putAll(root.cloneValues()); // Parse the AST and run it Parser.exec(fname, root); // Load the job runner *after* we execute the script to capture any config changes runner = JobRunner.load(root, dryrun); // find a build-target, and submit the job(s) to a runner if (targets.size() > 0) { for (String target : targets) { log.debug("building: " + target); BuildTarget initTarget = root.build(target); if (initTarget != null) { runner.submitAll(initTarget, root); } else { System.out.println("CGPIPE ERROR: Unable to find target: " + target); } } } else { BuildTarget initTarget = root.build(); if (initTarget != null) { runner.submitAll(initTarget, root); // Leave this commented out - it should be allowed to run cgpipe scripts w/o a target defined (testing) // } else { // System.out.println("CGPIPE ERROR: Unable to find default target"); } } runner.done(); if (outputStream != null) { outputStream.close(); } } catch (ASTParseException | ASTExecException | RunnerException | FileNotFoundException e) { if (outputStream != null) { outputStream.close(); } if (runner != null) { runner.abort(); } if (e.getClass().equals(ExitException.class)) { System.exit(((ExitException) e).getReturnCode()); } System.out.println("CGPIPE ERROR " + e.getMessage()); if (verbosity > 0) { e.printStackTrace(); } System.exit(1); } }