Example usage for java.util Collections sort

List of usage examples for java.util Collections sort

Introduction

In this page you can find the example usage for java.util Collections sort.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void sort(List<T> list, Comparator<? super T> c) 

Source Link

Document

Sorts the specified list according to the order induced by the specified comparator.

Usage

From source file:com.act.lcms.db.io.PrintConstructInfo.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w  w  w.j a v a 2  s .  c  o  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        System.out.print("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        String construct = cl.getOptionValue(OPTION_CONSTRUCT);
        List<LCMSWell> lcmsWells = LCMSWell.getInstance().getByConstructID(db, construct);
        Collections.sort(lcmsWells, new Comparator<LCMSWell>() {
            @Override
            public int compare(LCMSWell o1, LCMSWell o2) {
                return o1.getId().compareTo(o2.getId());
            }
        });

        Set<String> uniqueMSIDs = new HashSet<>();
        Map<Integer, Plate> platesById = new HashMap<>();

        System.out.format("\n\n-- Construct %s --\n\n", construct);

        List<ChemicalAssociatedWithPathway> pathwayChems = ChemicalAssociatedWithPathway.getInstance()
                .getChemicalsAssociatedWithPathwayByConstructId(db, construct);
        System.out.print("Chemicals associated with pathway:\n");
        System.out.format("  %-8s%-15s%-45s\n", "index", "kind", "chemical");
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            System.out.format("  %-8d%-15s%-45s\n", chem.getIndex(), chem.getKind(), chem.getChemical());
        }

        System.out.print("\nLCMS wells:\n");
        System.out.format("  %-15s%-6s%-15s%-15s%-15s\n", "barcode", "well", "msid", "fed", "lcms_count");
        for (LCMSWell well : lcmsWells) {
            uniqueMSIDs.add(well.getMsid());

            Plate p = platesById.get(well.getPlateId());
            if (p == null) {
                // TODO: migrate Plate to be a subclass of BaseDBModel.
                p = Plate.getPlateById(db, well.getPlateId());
                platesById.put(p.getId(), p);
            }

            String chem = well.getChemical();
            List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, p.getId(),
                    well.getPlateRow(), well.getPlateColumn());

            System.out.format("  %-15s%-6s%-15s%-15s%-15d\n", p.getBarcode(), well.getCoordinatesString(),
                    well.getMsid(), chem == null || chem.isEmpty() ? "--" : chem, scanFiles.size());
            System.out.flush();
        }

        List<Integer> plateIds = Arrays.asList(platesById.keySet().toArray(new Integer[platesById.size()]));
        Collections.sort(plateIds);
        System.out.print("\nAppears in plates:\n");
        for (Integer id : plateIds) {
            Plate p = platesById.get(id);
            System.out.format("  %s: %s\n", p.getBarcode(), p.getName());
        }

        List<String> msids = Arrays.asList(uniqueMSIDs.toArray(new String[uniqueMSIDs.size()]));
        Collections.sort(msids);
        System.out.format("\nMSIDS: %s\n", StringUtils.join(msids, ", "));

        Set<String> availableNegativeControls = new HashSet<>();
        for (Map.Entry<Integer, Plate> entry : platesById.entrySet()) {
            List<LCMSWell> wells = LCMSWell.getInstance().getByPlateId(db, entry.getKey());
            for (LCMSWell well : wells) {
                if (!construct.equals(well.getComposition())) {
                    availableNegativeControls.add(well.getComposition());
                }
            }
        }

        // Print available standards for each step w/ plate barcodes and coordinates.
        System.out.format("\nAvailable Standards:\n");
        Map<Integer, Plate> plateCache = new HashMap<>();
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            List<StandardWell> matchingWells = StandardWell.getInstance().getStandardWellsByChemical(db,
                    chem.getChemical());
            for (StandardWell well : matchingWells) {
                if (!plateCache.containsKey(well.getPlateId())) {
                    Plate p = Plate.getPlateById(db, well.getPlateId());
                    plateCache.put(p.getId(), p);
                }
            }
            Map<Integer, List<StandardWell>> standardWellsByPlateId = new HashMap<>();
            for (StandardWell well : matchingWells) {
                List<StandardWell> plateWells = standardWellsByPlateId.get(well.getPlateId());
                if (plateWells == null) {
                    plateWells = new ArrayList<>();
                    standardWellsByPlateId.put(well.getPlateId(), plateWells);
                }
                plateWells.add(well);
            }
            List<Pair<String, Integer>> plateBarcodes = new ArrayList<>(plateCache.size());
            for (Plate p : plateCache.values()) {
                if (p.getBarcode() == null) {
                    plateBarcodes.add(Pair.of("(no barcode)", p.getId()));
                } else {
                    plateBarcodes.add(Pair.of(p.getBarcode(), p.getId()));
                }
            }
            Collections.sort(plateBarcodes);
            System.out.format("  %s:\n", chem.getChemical());
            for (Pair<String, Integer> barcodePair : plateBarcodes) {
                // TODO: hoist this whole sorting/translation step into a utility class.
                List<StandardWell> wells = standardWellsByPlateId.get(barcodePair.getRight());
                if (wells == null) {
                    // Don't print plates that don't apply to this chemical, which can happen because we're caching the plates.
                    continue;
                }
                Collections.sort(wells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        int c = o1.getPlateRow().compareTo(o2.getPlateRow());
                        if (c != 0)
                            return c;
                        return o1.getPlateColumn().compareTo(o2.getPlateColumn());
                    }
                });
                List<String> descriptions = new ArrayList<>(wells.size());
                for (StandardWell well : wells) {
                    descriptions.add(String.format("%s in %s%s", well.getCoordinatesString(), well.getMedia(),
                            well.getConcentration() == null ? ""
                                    : String.format(" c. %f", well.getConcentration())));
                }
                System.out.format("    %s: %s\n", barcodePair.getLeft(), StringUtils.join(descriptions, ", "));
            }
        }

        List<String> negativeControlStrains = Arrays
                .asList(availableNegativeControls.toArray(new String[availableNegativeControls.size()]));
        Collections.sort(negativeControlStrains);
        System.out.format("\nAvailable negative controls: %s\n", StringUtils.join(negativeControlStrains, ","));
        System.out.print("\n----------\n");
        System.out.print("\n\n");
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step5-linguistic-annotation/
    System.err.println("Starting step 6 HIT Preparation");

    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (outputDir.exists()) {
        outputDir.delete();/*from   w  ww  . j  a  v  a  2 s.co  m*/
    }
    outputDir.mkdir();

    List<String> queries = new ArrayList<>();

    // iterate over query containers
    int countClueWeb = 0;
    int countSentence = 0;
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        if (queries.contains(f.getName()) || queries.size() == 0) {
            // groups contain only non-empty documents
            Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>();

            // split to groups according to number of sentences
            for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
                if (rankedResult.originalXmi != null) {
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));
                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class);

                    int groupId = sentences.size() / 40;
                    if (rankedResult.originalXmi == null) {
                        System.err.println("Empty document: " + rankedResult.clueWebID);
                    } else {
                        if (!groups.containsKey(groupId)) {
                            groups.put(groupId, new ArrayList<>());

                        }
                    }
                    //handle it
                    groups.get(groupId).add(rankedResult);
                    countClueWeb++;
                }
            }

            for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) {
                Integer groupId = entry.getKey();
                List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue();

                // make sure the results are sorted
                // DEBUG
                //                for (QueryResultContainer.SingleRankedResult r : rankedResults) {
                //                    System.out.print(r.rank + "\t");
                //                }

                Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank));

                // iterate over results for one query and group
                for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) {
                    QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i);

                    QueryResultContainer.SingleRankedResult r = rankedResults.get(i);
                    int rank = r.rank;
                    MustacheFactory mf = new DefaultMustacheFactory();
                    Mustache mustache = mf.compile("template/template.html");
                    String queryId = queryResultContainer.qID;
                    String query = queryResultContainer.query;
                    // make the first letter uppercase
                    query = query.substring(0, 1).toUpperCase() + query.substring(1);

                    List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples;
                    List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples;
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    List<generators.Sentence> sentences = new ArrayList<>();
                    List<Integer> paragraphs = new ArrayList<>();
                    paragraphs.add(0);

                    for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) {
                        for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) {

                            String sentenceBegin = String.valueOf(s.getBegin());
                            generators.Sentence sentence = new generators.Sentence(s.getCoveredText(),
                                    sentenceBegin);
                            sentences.add(sentence);
                            countSentence++;
                        }
                        int SentenceID = paragraphs.get(paragraphs.size() - 1);
                        if (sentences.size() > 120)
                            while (SentenceID < sentences.size()) {
                                if (!paragraphs.contains(SentenceID))
                                    paragraphs.add(SentenceID);
                                SentenceID = SentenceID + 120;
                            }
                        paragraphs.add(sentences.size());

                    }
                    System.err.println("Output dir: " + outputDir);
                    int startID = 0;
                    int endID;

                    for (int j = 0; j < paragraphs.size(); j++) {

                        endID = paragraphs.get(j);
                        int sentLength = endID - startID;
                        if (sentLength > 120 || j == paragraphs.size() - 1) {
                            if (sentLength > 120) {

                                endID = paragraphs.get(j - 1);
                                j--;
                            }
                            sentLength = endID - startID;
                            if (sentLength <= 40)
                                groupId = 40;
                            else if (sentLength <= 80 && sentLength > 40)
                                groupId = 80;
                            else if (sentLength > 80)
                                groupId = 120;

                            File folder = new File(outputDir + "/" + groupId);
                            if (!folder.exists()) {
                                System.err.println("creating directory: " + outputDir + "/" + groupId);
                                boolean result = false;

                                try {
                                    folder.mkdir();
                                    result = true;
                                } catch (SecurityException se) {
                                    //handle it
                                }
                                if (result) {
                                    System.out.println("DIR created");
                                }
                            }

                            String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_"
                                    + rankedResult.clueWebID + "_" + sentLength + ".html";
                            System.err.println("Printing a file: " + newHtmlFile);
                            File newHTML = new File(newHtmlFile);
                            int t = 0;
                            while (newHTML.exists()) {
                                newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_"
                                        + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html");
                                t++;
                            }
                            mustache.execute(new PrintWriter(new FileWriter(newHTML)),
                                    new generators(query, relevantInformationExamples,
                                            irrelevantInformationExamples, sentences.subList(startID, endID),
                                            queryId, rank))
                                    .flush();
                            startID = endID;
                        }
                    }
                }
            }

        }
    }
    System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences");
}

From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java

/**
 * @param cmdArgs Arguments./*from   w  w  w .  ja v a 2  s . c  o m*/
 */
public static void main(String[] cmdArgs) {
    try {
        JFreeChartGraphPlotterArguments args = new JFreeChartGraphPlotterArguments();

        JCommander jCommander = jcommander(cmdArgs, args, "<graph-plotter>");

        if (args.help()) {
            jCommander.usage();

            return;
        }

        if (args.inputFolders().isEmpty()) {
            errorHelp("Input folders are not defined.");

            return;
        }

        List<String> inFoldersAsString = args.inputFolders();

        List<File> inFolders = new ArrayList<>(inFoldersAsString.size());

        for (String folderAsString : inFoldersAsString)
            inFolders.add(new File(folderAsString).getAbsoluteFile());

        for (File inFolder : inFolders) {
            if (!inFolder.exists()) {
                errorHelp("Folder does not exist: " + inFolder.getAbsolutePath());

                return;
            }
        }

        List<List<List<File>>> benchFolders = new ArrayList<>();

        for (File inFolder : inFolders) {
            File[] dirs0 = inFolder.listFiles();

            if (dirs0 == null || dirs0.length == 0)
                continue;

            List<File> dirs = new ArrayList<>(Arrays.asList(dirs0));

            Collections.sort(dirs, FILE_NAME_COMP);

            boolean multipleDrivers = false;

            for (File f : dirs) {
                if (f.isFile() && MULTIPLE_DRIVERS_MARKER_FILE.equals(f.getName())) {
                    multipleDrivers = true;

                    break;
                }
            }

            List<List<File>> mulDrvFiles = new ArrayList<>();

            if (multipleDrivers) {
                for (File f : dirs) {
                    List<File> files = getFiles(f);

                    if (files != null)
                        mulDrvFiles.add(files);
                }
            } else {
                List<File> files = getFiles(inFolder);

                if (files != null)
                    mulDrvFiles.add(files);
            }

            benchFolders.add(mergeMultipleDriverLists(mulDrvFiles));
        }

        if (benchFolders.isEmpty()) {
            errorHelp("Input folders are empty or have invalid structure: " + inFoldersAsString);

            return;
        }

        String outputFolder = outputFolder(inFolders);

        JFreeChartGenerationMode mode = args.generationMode();

        if (mode == COMPOUND)
            processCompoundMode(outputFolder, benchFolders, args);
        else if (mode == COMPARISON)
            processComparisonMode(outputFolder, benchFolders, args);
        else if (mode == STANDARD)
            processStandardMode(benchFolders, args);
        else
            errorHelp("Unknown generation mode: " + args.generationMode());
    } catch (ParameterException e) {
        errorHelp("Invalid parameter.", e);
    } catch (Exception e) {
        errorHelp("Failed to execute graph generator.", e);
    }
}

From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinatorExerciser.java

public static void main(String[] args) throws InterruptedException, DependencyException, InvalidStateException,
        ProvisionedThroughputException, IOException {

    int numCoordinators = 9;
    int numLeases = 73;
    int leaseDurationMillis = 10000;
    int epsilonMillis = 100;

    AWSCredentialsProvider creds = new DefaultAWSCredentialsProviderChain();
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(creds);

    ILeaseManager<KinesisClientLease> leaseManager = new KinesisClientLeaseManager("nagl_ShardProgress", ddb);

    if (leaseManager.createLeaseTableIfNotExists(10L, 50L)) {
        LOG.info("Waiting for newly created lease table");
        if (!leaseManager.waitUntilLeaseTableExists(10, 300)) {
            LOG.error("Table was not created in time");
            return;
        }//from  w  ww.j  a v a2  s  .  co  m
    }

    CWMetricsFactory metricsFactory = new CWMetricsFactory(creds, "testNamespace", 30 * 1000, 1000);
    final List<LeaseCoordinator<KinesisClientLease>> coordinators = new ArrayList<LeaseCoordinator<KinesisClientLease>>();
    for (int i = 0; i < numCoordinators; i++) {
        String workerIdentifier = "worker-" + Integer.toString(i);

        LeaseCoordinator<KinesisClientLease> coord = new LeaseCoordinator<KinesisClientLease>(leaseManager,
                workerIdentifier, leaseDurationMillis, epsilonMillis, metricsFactory);

        coordinators.add(coord);
    }

    leaseManager.deleteAll();

    for (int i = 0; i < numLeases; i++) {
        KinesisClientLease lease = new KinesisClientLease();
        lease.setLeaseKey(Integer.toString(i));
        lease.setCheckpoint(new ExtendedSequenceNumber("checkpoint"));
        leaseManager.createLeaseIfNotExists(lease);
    }

    final JFrame frame = new JFrame("Test Visualizer");
    frame.setPreferredSize(new Dimension(800, 600));
    final JPanel panel = new JPanel(new GridLayout(coordinators.size() + 1, 0));
    final JLabel ticker = new JLabel("tick");
    panel.add(ticker);
    frame.getContentPane().add(panel);

    final Map<String, JLabel> labels = new HashMap<String, JLabel>();
    for (final LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        JPanel coordPanel = new JPanel();
        coordPanel.setLayout(new BoxLayout(coordPanel, BoxLayout.X_AXIS));
        final Button button = new Button("Stop " + coord.getWorkerIdentifier());
        button.setMaximumSize(new Dimension(200, 50));
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (coord.isRunning()) {
                    coord.stop();
                    button.setLabel("Start " + coord.getWorkerIdentifier());
                } else {
                    try {
                        coord.start();
                    } catch (LeasingException e) {
                        LOG.error(e);
                    }
                    button.setLabel("Stop " + coord.getWorkerIdentifier());
                }
            }

        });
        coordPanel.add(button);

        JLabel label = new JLabel();
        coordPanel.add(label);
        labels.put(coord.getWorkerIdentifier(), label);
        panel.add(coordPanel);
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    new Thread() {

        // Key is lease key, value is green-ness as a value from 0 to 255.
        // Great variable name, huh?
        private Map<String, Integer> greenNesses = new HashMap<String, Integer>();

        // Key is lease key, value is last owning worker
        private Map<String, String> lastOwners = new HashMap<String, String>();

        @Override
        public void run() {
            while (true) {
                for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
                    String workerIdentifier = coord.getWorkerIdentifier();

                    JLabel label = labels.get(workerIdentifier);

                    List<KinesisClientLease> asgn = new ArrayList<KinesisClientLease>(coord.getAssignments());
                    Collections.sort(asgn, new Comparator<KinesisClientLease>() {

                        @Override
                        public int compare(KinesisClientLease arg0, KinesisClientLease arg1) {
                            return arg0.getLeaseKey().compareTo(arg1.getLeaseKey());
                        }

                    });

                    StringBuilder builder = new StringBuilder();
                    builder.append("<html>");
                    builder.append(workerIdentifier).append(":").append(asgn.size()).append("          ");

                    for (KinesisClientLease lease : asgn) {
                        String leaseKey = lease.getLeaseKey();
                        String lastOwner = lastOwners.get(leaseKey);

                        // Color things green when they switch owners, decay the green-ness over time.
                        Integer greenNess = greenNesses.get(leaseKey);
                        if (greenNess == null || lastOwner == null
                                || !lastOwner.equals(lease.getLeaseOwner())) {
                            greenNess = 200;
                        } else {
                            greenNess = Math.max(0, greenNess - 20);
                        }
                        greenNesses.put(leaseKey, greenNess);
                        lastOwners.put(leaseKey, lease.getLeaseOwner());

                        builder.append(String.format("<font color=\"%s\">%03d</font>",
                                String.format("#00%02x00", greenNess), Integer.parseInt(leaseKey))).append(" ");
                    }
                    builder.append("</html>");

                    label.setText(builder.toString());
                    label.revalidate();
                    label.repaint();
                }

                if (ticker.getText().equals("tick")) {
                    ticker.setText("tock");
                } else {
                    ticker.setText("tick");
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                }
            }
        }

    }.start();

    frame.pack();
    frame.setVisible(true);

    for (LeaseCoordinator<KinesisClientLease> coord : coordinators) {
        coord.start();
    }
}

From source file:com.github.christofluyten.experiment.MeasureGendreau.java

/**
 * @param args/*from www  .  j  av a  2  s.  c  o  m*/
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    final List<Gendreau06Scenario> scns = new ArrayList<>(
            Gendreau06Parser.parser().addDirectory("files/gendreau2006/requests").parse());

    Collections.sort(scns, new Comparator<Gendreau06Scenario>() {
        @Override
        public int compare(Gendreau06Scenario o1, Gendreau06Scenario o2) {
            final int compare = o1.getProblemClass().getId().compareTo(o2.getProblemClass().getId());
            if (compare == 0) {
                return o1.getProblemInstanceId().compareTo(o2.getProblemInstanceId());
            }
            return compare;
        }
    });

    final List<Map<Property, Object>> propsList = new ArrayList<>();
    for (final Gendreau06Scenario scen : scns) {
        final StatisticalSummary urgency = Metrics.measureUrgency(scen);
        final Multiset<Class<?>> counts = Metrics.getEventTypeCounts(scen);

        final long scenarioLength = scen.getProblemClass().duration * 60000;
        final double dyn = Metrics.measureDynamism(scen, scenarioLength);

        final ImmutableMap<Property, Object> prop = ImmutableMap.<Property, Object>builder()
                .put(Property.PROBLEM_CLASS, scen.getProblemClass().getId())
                .put(Property.INSTANCE_ID, scen.getProblemInstanceId()).put(Property.DYNAMISM, dyn)
                .put(Property.URGENCY_MEAN, urgency.getMean() / 60000d)
                .put(Property.URGENCY_SD, urgency.getStandardDeviation() / 60000d)
                .put(Property.NUM_ORDERS, counts.count(AddParcelEvent.class))
                .put(Property.NUM_VEHICLES, counts.count(AddVehicleEvent.class))
                .putAll(MAP.get(scen.getProblemInstanceId() + scen.getProblemClass().getId())).build();

        propsList.add(prop);
    }

    final File targetFile = new File(PROPS_FILE);
    write(propsList, targetFile, asList(Property.values()));
    System.out.println("Results written to " + targetFile.getAbsolutePath());
}

From source file:com.twentyn.patentScorer.ScoreMerger.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();/*from ww  w . j ava  2  s.  c  o  m*/
    Options opts = new Options();
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());

    opts.addOption(Option.builder("r").longOpt("results").required().hasArg()
            .desc("A directory of search results to read").build());
    opts.addOption(Option.builder("s").longOpt("scores").required().hasArg()
            .desc("A directory of patent classification scores to read").build());
    opts.addOption(Option.builder("o").longOpt("output").required().hasArg()
            .desc("The output file where results will be written.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }
    File scoresDirectory = new File(cmdLine.getOptionValue("scores"));
    if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) {
        LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores"));
    }

    File resultsDirectory = new File(cmdLine.getOptionValue("results"));
    if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) {
        LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results"));
    }

    FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    FilenameFilter jsonFilter = new FilenameFilter() {
        public final Pattern JSON_PATTERN = Pattern.compile("\\.json$");

        public boolean accept(File dir, String name) {
            return JSON_PATTERN.matcher(name).find();
        }
    };

    Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>();
    LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath());
    for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) {
        BufferedReader reader = new BufferedReader(new FileReader(scoreFile));
        int count = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            PatentScorer.ClassificationResult res = objectMapper.readValue(line,
                    PatentScorer.ClassificationResult.class);
            scores.put(res.docId, res);
            count++;
        }
        LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath());
    }

    Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>();
    Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>();
    LOGGER.info("Reading results from directory at " + resultsDirectory);
    // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference.
    JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class,
            DocumentSearch.SearchResult.class);

    List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter));
    Collections.sort(resultsFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (File resultsFile : resultsFiles) {
        BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
        CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue());
        int bytesRead = reader.read(buffer);
        LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is "
                + resultsFile.length() + ")");
        List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()),
                resultsType);

        LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath());

        int count = 0;
        for (DocumentSearch.SearchResult sres : results) {
            for (DocumentSearch.ResultDocument resDoc : sres.getResults()) {
                String docId = resDoc.getDocId();
                PatentScorer.ClassificationResult classificationResult = scores.get(docId);
                if (classificationResult == null) {
                    LOGGER.warn("No classification result found for " + docId);
                } else {
                    resDoc.setClassifierScore(classificationResult.getScore());
                }
            }
            if (!synonymsToResults.containsKey(sres.getSynonym())) {
                synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>());
            }
            synonymsToResults.get(sres.getSynonym()).add(sres);
            count++;
            if (count % 1000 == 0) {
                LOGGER.info("Processed " + count + " search result documents");
            }
        }
    }

    Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() {
        @Override
        public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) {
            int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore());
            if (cmp != 0) {
                return cmp;
            }
            cmp = o2.getScore().compareTo(o1.getScore());
            return cmp;
        }
    };

    for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) {
        DocumentSearch.SearchResult newSearchRes = null;
        // Merge all result documents into a single search result.
        for (DocumentSearch.SearchResult sr : entry.getValue()) {
            if (newSearchRes == null) {
                newSearchRes = sr;
            } else {
                newSearchRes.getResults().addAll(sr.getResults());
            }
        }
        if (newSearchRes == null || newSearchRes.getResults() == null) {
            LOGGER.error("Search results for " + entry.getKey() + " are null.");
            continue;
        }
        Collections.sort(newSearchRes.getResults(), resultDocumentComparator);
        if (!inchisToResults.containsKey(newSearchRes.getInchi())) {
            inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>());
        }
        inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes);
    }

    List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet());
    Collections.sort(sortedKeys);
    List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size());
    Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() {
        @Override
        public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) {
            return o1.getSynonym().compareTo(o2.getSynonym());
        }
    };
    for (String inchi : sortedKeys) {
        List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi);
        Collections.sort(res, synonymSorter);
        orderedResults.add(new GroupedInchiResults(inchi, res));
    }

    objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults);
    outputWriter.close();
}

From source file:com.jslsolucoes.tagria.doc.generator.DocGenerator.java

public static void main(String[] args) throws IOException {

    String workspace = args[0];//  ww  w.j a  v a2 s.  c o  m
    Map<String, List<Tag>> groupments = new HashMap<>();

    String html = FileUtils.readFileToString(
            new File(workspace + "/tagria-lib/src/main/resources/META-INF/html.tld"), CHARSET);
    String ajax = FileUtils.readFileToString(
            new File(workspace + "/tagria-lib/src/main/resources/META-INF/ajax.tld"), CHARSET);
    XStream xStream = new XStream();
    xStream.processAnnotations(Taglib.class);
    Taglib taglibForHtml = (Taglib) xStream.fromXML(html);
    Taglib taglibForAjax = (Taglib) xStream.fromXML(ajax);
    List<Tag> tags = new ArrayList<Tag>();
    tags.addAll(taglibForHtml.getTags());
    tags.addAll(taglibForAjax.getTags());

    for (Tag tag : tags) {

        List<Tag> groups = groupments.get(tag.getGroup());
        if (groups == null) {
            groupments.put(tag.getGroup(), new ArrayList<>());
        }
        groupments.get(tag.getGroup()).add(tag);

        StringBuilder template = new StringBuilder(
                "<%@include file=\"../app/taglibs.jsp\"%>                              "
                        + "<html:view title=\"{title}\">                                 "
                        + "                  <html:panel>                                                      "
                        + "                     <html:panelHead label=\"" + tag.getName()
                        + "\"></html:panelHead>               "
                        + "                     <html:panelBody>                                                "
                        + "                        <html:tabPanel>                                                "
                        + "                           <html:tab label=\"{about}\" active=\"true\">                     "
                        + "                              <html:alert state=\"warning\">                              "
                        + "                                      " + tag.getDescription()
                        + "                           "
                        + "                              </html:alert>                                          "
                        + "                           </html:tab>                                                "
                        + "                           <html:tab label=\"{attributes}\">                              ");

        if (CollectionUtils.isEmpty(tag.getAttributes())) {
            template.append("<html:alert state=\"info\" label=\"{tag.empty.attributes}\"></html:alert>");
        } else {

            template.append("<html:table><html:tableLine>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.attribute\"/></html:tableColumn>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.required\"/></html:tableColumn>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.type\"/></html:tableColumn>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.description\"/></html:tableColumn>"
                    +

                    "</html:tableLine>");

            for (Attribute attribute : tag.getAttributes()) {

                template.append("<html:tableLine>" + "<html:tableColumn>" + attribute.getName()
                        + "</html:tableColumn>" + "<html:tableColumn>"
                        + (attribute.getRequired() == null ? false : true) + "</html:tableColumn>"
                        + "<html:tableColumn>" + attribute.getType() + "</html:tableColumn>"
                        + "<html:tableColumn>" + attribute.getDescription() + "</html:tableColumn>" +

                        "</html:tableLine>");
            }

            template.append("</html:table>");
        }

        template.append("                                                                        "
                + "                           </html:tab>                                                "
                + "                           <html:tab label=\"{demo}\">                                    "
                + "                              " + tag.getExample()
                + "                                          "
                + "                           </html:tab>                                                "
                + "                           <html:tab label=\"{source}\">                                 "
                + "                              <html:code>                                             "
                + "                                 &lt;html:view&gt;" + tag.getExampleEscaped()
                + "&lt;/html:view&gt;                                 "
                + "                              </html:code>                                          "
                + "                           </html:tab>                                                "
                + "                        </html:tabPanel>                                             "
                + "                     </html:panelBody>                                                "
                + "                  </html:panel>                                                      "
                + "               </html:view>                                                         ");
        FileUtils.writeStringToFile(new File(
                workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/component/" + tag.getName() + ".jsp"),
                template.toString(), CHARSET);
    }

    for (List<Tag> values : groupments.values()) {
        Collections.sort(values, new Comparator<Tag>() {
            @Override
            public int compare(Tag o1, Tag o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    StringBuilder menu = new StringBuilder("<html:div cssClass=\"menu\"><html:listGroup>");
    for (String key : new TreeSet<String>(groupments.keySet())) {
        menu.append("<html:listGroupItem><html:collapsable label=\"" + key + "\"><html:listGroup>");
        for (Tag tag : groupments.get(key)) {
            menu.append("<html:listGroupItem><html:link label=\"" + StringUtils.capitalize(tag.getName())
                    + "\" target=\"conteudo\" url=\"/component/" + tag.getName()
                    + "\"></html:link></html:listGroupItem>");
        }
        menu.append("</html:listGroup></html:collapsable></html:listGroupItem>");
    }
    menu.append("</html:listGroup></html:div>");

    File home = new File(workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/app/index.jsp");
    FileUtils.writeStringToFile(home, FileUtils.readFileToString(home, CHARSET)
            .replaceAll("<html:div cssClass=\"menu\">[\\s\\S]*?</html:div>", menu.toString()), CHARSET);

}

From source file:amie.keys.CSAKey.java

public static void main(String[] args) throws IOException, InterruptedException {
    final Triple<MiningAssistant, Float, String> parsedArgs = parseArguments(args);
    final Set<Rule> output = new LinkedHashSet<>();

    // Helper object that contains the implementation for the calculation
    // of confidence and support
    // The file with the non-keys, one per line
    long timea = System.currentTimeMillis();
    List<List<String>> inputNonKeys = Utilities.parseNonKeysFile(parsedArgs.third);
    System.out.println(inputNonKeys.size() + " input non-keys");
    final List<List<String>> nonKeys = pruneBySupport(inputNonKeys, parsedArgs.second,
            parsedArgs.first.getKb());/*  www  . ja v  a  2s .com*/
    Collections.sort(nonKeys, new Comparator<List<String>>() {

        @Override
        public int compare(List<String> o1, List<String> o2) {
            int r = Integer.compare(o2.size(), o1.size());
            if (r == 0) {
                return Integer.compare(o2.hashCode(), o1.hashCode());
            }

            return r;
        }

    });
    System.out.println(nonKeys.size() + " non-keys after pruning");
    int totalLoad = computeLoad(nonKeys);
    System.out.println(totalLoad + " is the total load");
    int nThreads = Runtime.getRuntime().availableProcessors();
    //int batchSize = Math.max(Math.min(maxBatchSize, totalLoad / nThreads), minBatchSize);
    int batchSize = Math.max(Math.min(maxLoad, totalLoad / nThreads), minLoad);

    final Queue<int[]> chunks = new PriorityQueue(50, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return Integer.compare(o2[2], o1[2]);
        }

    });

    final HashSet<HashSet<Integer>> nonKeysInt = new HashSet<>();
    final HashMap<String, Integer> property2Id = new HashMap<>();
    final HashMap<Integer, String> id2Property = new HashMap<>();
    final List<Integer> propertiesList = new ArrayList<>();
    int support = (int) parsedArgs.second.floatValue();
    KB kb = parsedArgs.first.getKb();
    buildDictionaries(nonKeys, nonKeysInt, property2Id, id2Property, propertiesList, support, kb);
    final List<HashSet<Integer>> nonKeysIntList = new ArrayList<>(nonKeysInt);
    int start = 0;
    int[] nextIdx = nextIndex(nonKeysIntList, 0, batchSize);
    int end = nextIdx[0];
    int load = nextIdx[1];
    while (start < nonKeysIntList.size()) {
        int[] chunk = new int[] { start, end, load };
        chunks.add(chunk);
        start = end;
        nextIdx = nextIndex(nonKeysIntList, end, batchSize);
        end = nextIdx[0];
        load = nextIdx[1];
    }

    Thread[] threads = new Thread[Math.min(Runtime.getRuntime().availableProcessors(), chunks.size())];
    for (int i = 0; i < threads.length; ++i) {
        threads[i] = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    int[] chunk = null;
                    synchronized (chunks) {
                        if (!chunks.isEmpty()) {
                            chunk = chunks.poll();
                        } else {
                            break;
                        }
                    }
                    System.out.println("Processing chunk " + Arrays.toString(chunk));
                    mine(parsedArgs, nonKeysIntList, property2Id, id2Property, propertiesList, chunk[0],
                            chunk[1], output);
                }

            }
        });
        threads[i].start();
    }

    for (int i = 0; i < threads.length; ++i) {
        threads[i].join();
    }
    long timeb = System.currentTimeMillis();
    System.out.println("==== Unique C-keys =====");
    for (Rule r : output) {
        System.out.println(Utilities.formatKey(r));
    }
    System.out.println(
            "VICKEY found " + output.size() + " unique conditional keys in " + (timeb - timea) + " ms");
}

From source file:FaceRatios.java

@SuppressWarnings("serial")
public static void main(String[] args) {
    int r = FSDK.ActivateLibrary(FACE_SDK_LICENSE);
    if (r == FSDK.FSDKE_OK) {
        FSDK.Initialize();//from w w  w.  j  ava2s .  com
        FSDK.SetFaceDetectionParameters(true, true, 384);

        Map<String, Map<String, ArrayList<Double>>> faceProperties = new HashMap<>();

        for (String directory : new File(FACE_DIRECTORY).list()) {
            if (new File(FACE_DIRECTORY + directory).isDirectory()) {
                Map<String, ArrayList<Double>> properties = new HashMap<String, ArrayList<Double>>() {
                    {
                        for (String property : propertyNames)
                            put(property, new ArrayList<Double>());
                    }
                };

                File[] files = new File(FACE_DIRECTORY + directory).listFiles();
                System.out.println("Analyzing " + directory + " with " + files.length + " files\n");
                for (File file : files) {
                    if (file.isFile()) {
                        HImage imageHandle = new HImage();
                        FSDK.LoadImageFromFileW(imageHandle, file.getAbsolutePath());

                        FSDK.TFacePosition.ByReference facePosition = new FSDK.TFacePosition.ByReference();
                        if (FSDK.DetectFace(imageHandle, facePosition) == FSDK.FSDKE_OK) {
                            FSDK_Features.ByReference facialFeatures = new FSDK_Features.ByReference();
                            FSDK.DetectFacialFeaturesInRegion(imageHandle, (FSDK.TFacePosition) facePosition,
                                    facialFeatures);

                            Point[] featurePoints = new Point[FSDK.FSDK_FACIAL_FEATURE_COUNT];
                            for (int i = 0; i < FSDK.FSDK_FACIAL_FEATURE_COUNT; i++) {
                                featurePoints[i] = new Point(0, 0);
                                featurePoints[i].x = facialFeatures.features[i].x;
                                featurePoints[i].y = facialFeatures.features[i].y;
                            }

                            double eyeDistance = featureDistance(featurePoints, FeatureID.LEFT_EYE,
                                    FeatureID.RIGHT_EYE);
                            double rightEyeSize = featureDistance(featurePoints,
                                    FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.RIGHT_EYE_OUTER_CORNER);
                            double leftEyeSize = featureDistance(featurePoints, FeatureID.LEFT_EYE_INNER_CORNER,
                                    FeatureID.LEFT_EYE_OUTER_CORNER);
                            double averageEyeSize = (rightEyeSize + leftEyeSize) / 2;

                            double mouthLength = featureDistance(featurePoints, FeatureID.MOUTH_RIGHT_CORNER,
                                    FeatureID.MOUTH_LEFT_CORNER);
                            double mouthHeight = featureDistance(featurePoints, FeatureID.MOUTH_BOTTOM,
                                    FeatureID.MOUTH_TOP);
                            double noseHeight = featureDistance(featurePoints, FeatureID.NOSE_BOTTOM,
                                    FeatureID.NOSE_BRIDGE);
                            double chinHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM,
                                    FeatureID.MOUTH_BOTTOM);

                            double chinToBridgeHeight = featureDistance(featurePoints, FeatureID.CHIN_BOTTOM,
                                    FeatureID.NOSE_BRIDGE);

                            double faceContourLeft = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY()
                                    - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getY())
                                    / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX()
                                            - featurePoints[FeatureID.FACE_CONTOUR2.getIndex()].getX());
                            double faceContourRight = (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getY()
                                    - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getY())
                                    / (featurePoints[FeatureID.CHIN_BOTTOM.getIndex()].getX()
                                            - featurePoints[FeatureID.FACE_CONTOUR12.getIndex()].getX());

                            double bridgeLeftEyeDistance = featureDistance(featurePoints,
                                    FeatureID.LEFT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE);
                            double bridgeRightEyeDistance = featureDistance(featurePoints,
                                    FeatureID.RIGHT_EYE_INNER_CORNER, FeatureID.NOSE_BRIDGE);

                            properties.get("eyeSize/eyeDistance").add(averageEyeSize / eyeDistance);
                            properties.get("eyeSizeDisparity")
                                    .add(Math.abs(leftEyeSize - rightEyeSize) / averageEyeSize);
                            properties.get("bridgeToEyeDisparity")
                                    .add(Math.abs(bridgeLeftEyeDistance - bridgeRightEyeDistance)
                                            / ((bridgeLeftEyeDistance + bridgeRightEyeDistance) / 2));
                            properties.get("eyeDistance/mouthLength").add(eyeDistance / mouthLength);
                            properties.get("eyeDistance/noseHeight").add(eyeDistance / noseHeight);
                            properties.get("eyeSize/mouthLength").add(eyeDistance / mouthLength);
                            properties.get("eyeSize/noseHeight").add(eyeDistance / noseHeight);
                            properties.get("mouthLength/mouthHeight").add(mouthLength / mouthHeight);
                            properties.get("chinHeight/noseHeight").add(chinHeight / noseHeight);
                            properties.get("chinHeight/chinToBridgeHeight")
                                    .add(chinHeight / chinToBridgeHeight);
                            properties.get("noseHeight/chinToBridgeHeight")
                                    .add(noseHeight / chinToBridgeHeight);
                            properties.get("mouthHeight/chinToBridgeHeight")
                                    .add(mouthHeight / chinToBridgeHeight);
                            properties.get("faceCountourAngle")
                                    .add(Math.toDegrees(Math.atan((faceContourLeft - faceContourRight)
                                            / (1 + faceContourLeft * faceContourRight))));
                        }

                        FSDK.FreeImage(imageHandle);
                    }
                }

                System.out.format("%32s\t%8s\t%8s\t%3s%n", "Property", "", "", "c");
                System.out.println(new String(new char[76]).replace("\0", "-"));

                ArrayList<Entry<String, ArrayList<Double>>> propertyList = new ArrayList<>(
                        properties.entrySet());
                Collections.sort(propertyList, new Comparator<Entry<String, ArrayList<Double>>>() {
                    @Override
                    public int compare(Entry<String, ArrayList<Double>> arg0,
                            Entry<String, ArrayList<Double>> arg1) {
                        DescriptiveStatistics dStats0 = new DescriptiveStatistics(listToArray(arg0.getValue()));
                        DescriptiveStatistics dStats1 = new DescriptiveStatistics(listToArray(arg1.getValue()));
                        return new Double(dStats0.getStandardDeviation() / dStats0.getMean())
                                .compareTo(dStats1.getStandardDeviation() / dStats1.getMean());
                    }
                });

                for (Entry<String, ArrayList<Double>> property : propertyList) {
                    DescriptiveStatistics dStats = new DescriptiveStatistics(listToArray(property.getValue()));
                    System.out.format("%32s\t%4f\t%4f\t%3s%n", property.getKey(), dStats.getMean(),
                            dStats.getStandardDeviation(),
                            Math.round(dStats.getStandardDeviation() / dStats.getMean() * 100) + "%");
                }

                System.out.println("\n");
                faceProperties.put(directory, properties);
            }
        }

        for (String propertyName : propertyNames) {
            DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();
            for (Entry<String, Map<String, ArrayList<Double>>> face : faceProperties.entrySet()) {
                dataset.add(face.getValue().get(propertyName), "Default Series", face.getKey());
            }

            PropertyBoxWhisker plot = new PropertyBoxWhisker(propertyName, dataset);
            plot.pack();
            plot.setVisible(true);
        }
    }
}

From source file:mzmatch.ipeak.normalisation.VanDeSompele.java

public static void main(String args[]) {
    try {//www  . j  a  v  a2 s.c o  m
        Tool.init();

        // parse the commandline options
        Options options = new Options();
        CmdLineParser cmdline = new CmdLineParser(options);

        // check whether we need to show the help
        cmdline.parse(args);
        if (options.help) {
            Tool.printHeader(System.out, application, version);
            cmdline.printUsage(System.out, "");
            return;
        }

        if (options.verbose) {
            Tool.printHeader(System.out, application, version);
            cmdline.printOptions();
        }

        // check the command-line parameters
        {
            // if the output directories do not exist, create them
            if (options.output != null)
                Tool.createFilePath(options.output, true);
        }

        // load the data
        if (options.verbose)
            System.out.println("Loading data");
        ParseResult result = PeakMLParser.parse(new FileInputStream(options.input), true);

        Header header = result.header;
        IPeakSet<IPeakSet<? extends IPeak>> peaksets = (IPeakSet<IPeakSet<? extends IPeak>>) result.measurement;

        int nrmeasurements = header.getNrMeasurementInfos();

        // remove the stability factor annotation
        for (IPeak peak : peaksets)
            peak.removeAnnotation("stability factor");

        // load the database
        if (options.verbose)
            System.out.println("Loading the molecule database");
        HashMap<String, Molecule> database = MoleculeIO.parseXml(new FileInputStream(options.database));

        // filter the set to include only identifiable metabolites
        if (options.verbose)
            System.out.println("Creating selection");
        Vector<IPeakSet<? extends IPeak>> selection = new Vector<IPeakSet<? extends IPeak>>();
        for (Molecule molecule : database.values()) {
            double mass = molecule.getMass(Mass.MONOISOTOPIC);
            double delta = PeriodicTable.PPM(mass, options.ppm);

            // get the most intense peak containing all the measurements
            Vector<IPeakSet<? extends IPeak>> neighbourhoud = peaksets.getPeaksInMassRange(mass - delta,
                    mass + delta);
            Collections.sort(neighbourhoud, IPeak.sort_intensity_descending);
            for (IPeakSet<? extends IPeak> neighbour : neighbourhoud)
                if (count(neighbour) == nrmeasurements) {
                    selection.add(neighbour);
                    break;
                }
        }

        // calculate the stability factor for each peak in the selection
        if (options.verbose)
            System.out.println("Calculating stability factors");
        for (int peakid1 = 0; peakid1 < selection.size(); ++peakid1) {
            double stddeviations[] = new double[selection.size()];

            IPeakSet<? extends IPeak> peakset1 = selection.get(peakid1);
            for (int peakid2 = 0; peakid2 < selection.size(); ++peakid2) {
                IPeakSet<? extends IPeak> peakset2 = selection.get(peakid2);

                double values[] = new double[nrmeasurements];
                for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) {
                    int measurementid1 = peakset1.get(measurementid).getMeasurementID();
                    int setid1 = header.indexOfSetInfo(header.getSetInfoForMeasurementID(measurementid1));
                    int measurementid2 = peakset2.get(measurementid).getMeasurementID();
                    int setid2 = header.indexOfSetInfo(header.getSetInfoForMeasurementID(measurementid2));
                    if (setid1 != setid2 || measurementid1 != measurementid2)
                        System.err.println("[WARNING]: differing setid or spectrumid for comparison");

                    values[measurementid] = Math.log(peakset1.get(measurementid).getIntensity()
                            / peakset2.get(measurementid).getIntensity()) / Math.log(2);
                }
                stddeviations[peakid2] = Statistical.stddev(values);
            }

            peakset1.addAnnotation("stability factor", Statistical.mean(stddeviations));
        }

        // sort on the stability factor
        Collections.sort(selection, new IPeak.AnnotationAscending("stability factor"));

        // take the top 10% and calculate the geometric mean
        if (options.verbose)
            System.out.println("Calculating normalisation factors");
        int nrselected = (int) (0.1 * selection.size());
        if (nrselected < 10)
            nrselected = (10 < selection.size() ? 10 : selection.size());
        double normalization_factors[] = new double[nrmeasurements];
        for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) {
            double values[] = new double[nrselected];
            for (int i = 0; i < nrselected; ++i) {
                IPeak peak = selection.get(i).get(measurementid);
                values[i] = peak.getIntensity();
            }
            normalization_factors[measurementid] = Statistical.geomean(values);
        }

        // scale the found normalization factors
        double maxnf = Statistical.max(normalization_factors);
        for (int sampleid = 0; sampleid < nrmeasurements; ++sampleid)
            normalization_factors[sampleid] /= maxnf;

        // write the selection if needed
        if (options.selection != null) {
            if (options.verbose)
                System.out.println("Writing original selection data");

            PeakMLWriter.write(result.header, selection, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection)), null);
        }

        // normalize all the peaks
        if (options.verbose)
            System.out.println("Normalizing all the entries");
        for (IPeakSet<? extends IPeak> peakset : peaksets) {
            for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) {
                // TODO why did I do this again ?
                int id = 0;
                int setid = 0;
                int spectrumid = 0;
                for (int i = 0; i < header.getNrSetInfos(); ++i) {
                    SetInfo set = header.getSetInfos().get(i);

                    if (id + set.getNrMeasurementIDs() > measurementid) {
                        setid = i;
                        spectrumid = measurementid - id;
                        break;
                    } else
                        id += set.getNrMeasurementIDs();
                }

                MassChromatogram<Peak> masschromatogram = null;
                for (IPeak p : peakset) {
                    int mymeasurementid = p.getMeasurementID();
                    int mysetid = header.indexOfSetInfo(header.getSetInfoForMeasurementID(mymeasurementid));
                    if (mysetid == setid && mymeasurementid == spectrumid) {
                        masschromatogram = (MassChromatogram<Peak>) p;
                        break;
                    }
                }
                if (masschromatogram == null)
                    continue;

                for (IPeak peak : masschromatogram.getPeaks())
                    peak.setIntensity(peak.getIntensity() / normalization_factors[measurementid]);
            }
        }

        // write the selection if needed
        if (options.selection_normalized != null) {
            if (options.verbose)
                System.out.println("Writing the normalized selection data");

            PeakMLWriter.write(result.header, selection, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection_normalized)), null);
        }

        // write the factors if needed
        if (options.factors != null) {
            if (options.verbose)
                System.out.println("Writing the normalization factors");

            PrintStream out = new PrintStream(options.factors);
            for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid)
                out.println(header.getMeasurementInfo(measurementid).getLabel() + "\t"
                        + normalization_factors[measurementid]);
        }

        // write the plot if needed
        if (options.img != null) {
            if (options.verbose)
                System.out.println("Writing the graph");

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            JFreeChart linechart = ChartFactory.createLineChart(null, "measurement", "normalization factor",
                    dataset, PlotOrientation.VERTICAL, false, // legend
                    false, // tooltips
                    false // urls
            );

            CategoryPlot plot = (CategoryPlot) linechart.getPlot();
            CategoryAxis axis = (CategoryAxis) plot.getDomainAxis();
            axis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
            LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();

            renderer.setSeriesShapesFilled(0, true);
            renderer.setSeriesShapesVisible(0, true);

            linechart.setBackgroundPaint(Color.WHITE);
            linechart.setBorderVisible(false);
            linechart.setAntiAlias(true);

            plot.setBackgroundPaint(Color.WHITE);
            plot.setDomainGridlinesVisible(true);
            plot.setRangeGridlinesVisible(true);

            // create the datasets
            for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid)
                dataset.addValue(normalization_factors[measurementid], "",
                        header.getMeasurementInfo(measurementid).getLabel());
            JFreeChartTools.writeAsPDF(new FileOutputStream(options.img), linechart, 800, 500);
        }

        // write the normalized values
        if (options.verbose)
            System.out.println("Writing the normalized data");
        PeakMLWriter.write(result.header, peaksets.getPeaks(), null,
                new GZIPOutputStream(new FileOutputStream(options.output)), null);
    } catch (Exception e) {
        Tool.unexpectedError(e, application);
    }
}