Example usage for com.google.common.collect Ordering sortedCopy

List of usage examples for com.google.common.collect Ordering sortedCopy

Introduction

In this page you can find the example usage for com.google.common.collect Ordering sortedCopy.

Prototype

public <E extends T> List<E> sortedCopy(Iterable<E> elements) 

Source Link

Document

Returns a mutable list containing elements sorted by this ordering; use this only when the resulting list may need further modification, or may contain null .

Usage

From source file:org.apache.ctakes.temporal.data.analysis.PrintInconsistentAnnotations.java

public static void main(String[] args) throws Exception {
    Options options = CliFactory.parseArguments(Options.class, args);
    int windowSize = 50;

    List<Integer> patientSets = options.getPatients().getList();
    List<Integer> trainItems = THYMEData.getPatientSets(patientSets, THYMEData.TRAIN_REMAINDERS);
    List<File> files = THYMEData.getFilesFor(trainItems, options.getRawTextDirectory());

    CollectionReader reader = UriCollectionReader.getCollectionReaderFromFiles(files);
    AggregateBuilder aggregateBuilder = new AggregateBuilder();
    aggregateBuilder.add(UriToDocumentTextAnnotator.getDescription());
    aggregateBuilder.add(AnalysisEngineFactory.createEngineDescription(XMIReader.class,
            XMIReader.PARAM_XMI_DIRECTORY, options.getXMIDirectory()));

    int totalDocTimeRels = 0;
    int totalInconsistentDocTimeRels = 0;
    for (Iterator<JCas> casIter = new JCasIterator(reader, aggregateBuilder.createAggregate()); casIter
            .hasNext();) {//from w  w  w.j a  v  a 2 s  .c o m
        JCas jCas = casIter.next();
        String text = jCas.getDocumentText();
        JCas goldView = jCas.getView("GoldView");

        // group events by their narrative container
        Multimap<Annotation, EventMention> containers = HashMultimap.create();
        for (TemporalTextRelation relation : JCasUtil.select(goldView, TemporalTextRelation.class)) {
            if (relation.getCategory().equals("CONTAINS")) {
                Annotation arg1 = relation.getArg1().getArgument();
                Annotation arg2 = relation.getArg2().getArgument();
                if (arg2 instanceof EventMention) {
                    EventMention event = (EventMention) arg2;
                    containers.put(arg1, event);
                }
            }
        }

        // check each container for inconsistent DocTimeRels
        for (Annotation container : containers.keySet()) {
            Set<String> docTimeRels = Sets.newHashSet();
            for (EventMention event : containers.get(container)) {
                docTimeRels.add(event.getEvent().getProperties().getDocTimeRel());
            }
            totalDocTimeRels += docTimeRels.size();

            boolean inconsistentDocTimeRels;
            if (container instanceof EventMention) {
                EventMention mention = ((EventMention) container);
                String containerDocTimeRel = mention.getEvent().getProperties().getDocTimeRel();
                inconsistentDocTimeRels = false;
                for (String docTimeRel : docTimeRels) {
                    if (docTimeRel.equals(containerDocTimeRel)) {
                        continue;
                    }
                    if (containerDocTimeRel.equals("BEFORE/OVERLAP")
                            && (docTimeRel.equals("BEFORE") || docTimeRel.equals("OVERLAP"))) {
                        continue;
                    }
                    inconsistentDocTimeRels = true;
                    break;
                }
            } else {
                if (docTimeRels.size() == 1) {
                    inconsistentDocTimeRels = false;
                } else if (docTimeRels.contains("BEFORE/OVERLAP")) {
                    inconsistentDocTimeRels = docTimeRels.size() == 1
                            && (docTimeRels.contains("BEFORE") || docTimeRels.contains("OVERLAP"));
                } else {
                    inconsistentDocTimeRels = true;
                }
            }

            // if inconsistent: print events, DocTimeRels and surrounding context
            if (inconsistentDocTimeRels) {
                totalInconsistentDocTimeRels += docTimeRels.size();

                List<Integer> offsets = Lists.newArrayList();
                offsets.add(container.getBegin());
                offsets.add(container.getEnd());
                for (EventMention event : containers.get(container)) {
                    offsets.add(event.getBegin());
                    offsets.add(event.getEnd());
                }
                Collections.sort(offsets);
                int begin = Math.max(offsets.get(0) - windowSize, 0);
                int end = Math.min(offsets.get(offsets.size() - 1) + windowSize, text.length());
                System.err.printf("Inconsistent DocTimeRels in %s, ...%s...\n",
                        new File(ViewUriUtil.getURI(jCas)).getName(),
                        text.substring(begin, end).replaceAll("([\r\n])[\r\n]+", "$1"));
                if (container instanceof EventMention) {
                    System.err.printf("Container: \"%s\" (docTimeRel=%s)\n", container.getCoveredText(),
                            ((EventMention) container).getEvent().getProperties().getDocTimeRel());
                } else {
                    System.err.printf("Container: \"%s\"\n", container.getCoveredText());
                }
                Ordering<EventMention> byBegin = Ordering.natural()
                        .onResultOf(new Function<EventMention, Integer>() {
                            @Override
                            public Integer apply(@Nullable EventMention event) {
                                return event.getBegin();
                            }
                        });
                for (EventMention event : byBegin.sortedCopy(containers.get(container))) {
                    System.err.printf("* \"%s\" (docTimeRel=%s)\n", event.getCoveredText(),
                            event.getEvent().getProperties().getDocTimeRel());
                }
                System.err.println();
            }
        }
    }

    System.err.printf("Inconsistent DocTimeRels: %.1f%% (%d/%d)\n",
            100.0 * totalInconsistentDocTimeRels / totalDocTimeRels, totalInconsistentDocTimeRels,
            totalDocTimeRels);
}

From source file:com.wrmsr.nativity.x86.App.java

public static void main(String[] args) throws Exception {
    logger.info("hi");

    Document doc;//w  ww  .j av a2s.co  m
    try (InputStream is = App.class.getClassLoader().getResourceAsStream("x86reference.xml")) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(is);
    }

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    List<Ref.Entry> entries = Lists.newArrayList();
    Ref.Parsing.parseRoot(doc, entries);
    ByteTrie<Ref.Entry> trie = DisImpl.buildTrie(entries);

    System.out.println(trie.toDetailedString());
    System.out.println();
    System.out.println();

    // Dis.run(trie);

    Ordering<Pair<Ref.Operand.Type, Ref.Operand.Address>> ord = Ordering.from((o1, o2) -> {
        int c = ObjectUtils.compare(o1.getLeft(), o2.getLeft());
        if (c == 0) {
            c = ObjectUtils.compare(o1.getRight(), o2.getRight());
        }
        return c;
    });

    Set<Pair<Ref.Operand.Type, Ref.Operand.Address>> set = Sets.newHashSet();
    for (Ref.Entry entry : entries) {
        for (Ref.Syntax syntax : entry.getSyntaxes()) {
            for (Ref.Operand operand : syntax.getOperands()) {
                set.add(new ImmutablePair<>(operand.type, operand.address));
            }
        }
    }
    for (Pair<Ref.Operand.Type, Ref.Operand.Address> pair : ord.sortedCopy(set)) {
        System.out.println(pair);
    }
    System.out.println("\n");

    DisImpl.run(trie);
}

From source file:org.apache.ctakes.temporal.eval.EvaluationOfTimeSpans.java

public static void main(String[] args) throws Exception {
    Options options = CliFactory.parseArguments(Options.class, args);
    List<Integer> trainItems = null;
    List<Integer> devItems = null;
    List<Integer> testItems = null;

    List<Integer> patientSets = options.getPatients().getList();
    if (options.getXMLFormat() == XMLFormat.I2B2) {
        trainItems = I2B2Data.getTrainPatientSets(options.getXMLDirectory());
        devItems = I2B2Data.getDevPatientSets(options.getXMLDirectory());
        testItems = I2B2Data.getTestPatientSets(options.getXMLDirectory());
    } else {/*from   ww  w  . j a  v  a  2 s. c o  m*/
        trainItems = THYMEData.getPatientSets(patientSets, options.getTrainRemainders().getList());
        devItems = THYMEData.getPatientSets(patientSets, options.getDevRemainders().getList());
        testItems = THYMEData.getPatientSets(patientSets, options.getTestRemainders().getList());
    }

    List<Integer> allTrain = new ArrayList<>(trainItems);
    List<Integer> allTest = null;

    if (options.getTest()) {
        allTrain.addAll(devItems);
        allTest = new ArrayList<>(testItems);
    } else {
        allTest = new ArrayList<>(devItems);
    }

    // specify the annotator classes to use
    List<Class<? extends JCasAnnotator_ImplBase>> annotatorClasses = Lists.newArrayList();
    if (options.getRunBackwards())
        annotatorClasses.add(BackwardsTimeAnnotator.class);
    if (options.getRunForwards())
        annotatorClasses.add(TimeAnnotator.class);
    if (options.getRunParserBased())
        annotatorClasses.add(ConstituencyBasedTimeAnnotator.class);
    if (options.getRunCrfBased())
        annotatorClasses.add(CRFTimeAnnotator.class);
    if (annotatorClasses.size() == 0) {
        // run all
        annotatorClasses.add(BackwardsTimeAnnotator.class);
        annotatorClasses.add(TimeAnnotator.class);
        annotatorClasses.add(ConstituencyBasedTimeAnnotator.class);
        annotatorClasses.add(CRFTimeAnnotator.class);
    }
    Map<Class<? extends JCasAnnotator_ImplBase>, String[]> annotatorTrainingArguments = Maps.newHashMap();

    // THYME best params: Backwards: 0.1, CRF 0.3, Time 0.1, Constituency 0.3
    // i2b2 best params: Backwards 0.1, CRF 3.0, Time 0.1, Constituency 0.3
    //      String gridParam = "0.01";
    annotatorTrainingArguments.put(BackwardsTimeAnnotator.class, new String[] { "-c", "0.1" });
    annotatorTrainingArguments.put(TimeAnnotator.class, new String[] { "-c", "0.1" });
    annotatorTrainingArguments.put(ConstituencyBasedTimeAnnotator.class, new String[] { "-c", "0.3" });
    annotatorTrainingArguments.put(CRFTimeAnnotator.class, new String[] { "-p", "c2=" + "0.3" });

    // run one evaluation per annotator class
    final Map<Class<?>, AnnotationStatistics<?>> annotatorStats = Maps.newHashMap();
    for (Class<? extends JCasAnnotator_ImplBase> annotatorClass : annotatorClasses) {
        EvaluationOfTimeSpans evaluation = new EvaluationOfTimeSpans(new File("target/eval/time-spans"),
                options.getRawTextDirectory(), options.getXMLDirectory(), options.getXMLFormat(),
                options.getSubcorpus(), options.getXMIDirectory(), options.getTreebankDirectory(),
                options.getFeatureSelectionThreshold(), options.getSMOTENeighborNumber(), annotatorClass,
                options.getPrintOverlappingSpans(), annotatorTrainingArguments.get(annotatorClass));
        evaluation.prepareXMIsFor(patientSets);
        evaluation.setSkipTrain(options.getSkipTrain());
        evaluation.printErrors = options.getPrintErrors();
        if (options.getI2B2Output() != null)
            evaluation.setI2B2Output(options.getI2B2Output() + "/" + annotatorClass.getSimpleName());
        String name = String.format("%s.errors", annotatorClass.getSimpleName());
        evaluation.setLogging(Level.FINE, new File("target/eval", name));
        AnnotationStatistics<String> stats = evaluation.trainAndTest(allTrain, allTest);
        annotatorStats.put(annotatorClass, stats);
    }

    // allow ordering of models by F1
    Ordering<Class<? extends JCasAnnotator_ImplBase>> byF1 = Ordering.natural()
            .onResultOf(new Function<Class<? extends JCasAnnotator_ImplBase>, Double>() {
                @Override
                public Double apply(Class<? extends JCasAnnotator_ImplBase> annotatorClass) {
                    return annotatorStats.get(annotatorClass).f1();
                }
            });

    // print out models, ordered by F1
    for (Class<?> annotatorClass : byF1.sortedCopy(annotatorClasses)) {
        System.err.printf("===== %s =====\n", annotatorClass.getSimpleName());
        System.err.println(annotatorStats.get(annotatorClass));
    }
}

From source file:com.intel.podm.allocation.mappers.Sorter.java

@SafeVarargs
public static <T> List<T> sort(Collection<T> toBeSorted, Ordering<T>... orderings) {
    if (orderings == null || orderings.length == 0) {
        throw new IllegalArgumentException("At least one ordering method must be passed to sort.");
    }/*  w w  w .j a  v a 2  s .  c om*/

    Ordering<T> ordering = orderings[0];
    for (int i = 1; i < orderings.length; i++) {
        ordering = ordering.compound(orderings[i]);
    }

    return ordering.sortedCopy(toBeSorted);
}

From source file:org.sonar.server.ws.WebServicesWs.java

private static void writeController(JsonWriter writer, Controller controller, boolean includeInternals) {
    if (includeInternals || !controller.isInternal()) {
        writer.beginObject();// w ww .  ja  v  a  2 s  .co  m
        writer.prop("path", controller.path());
        writer.prop("since", controller.since());
        writer.prop("description", controller.description());
        // sort actions by key
        Ordering<Action> ordering = Ordering.natural().onResultOf(Action::key);
        writer.name("actions").beginArray();
        for (Action action : ordering.sortedCopy(controller.actions())) {
            writeAction(writer, action, includeInternals);
        }
        writer.endArray();
        writer.endObject();
    }
}

From source file:org.sonar.server.ws.ws.ListAction.java

private static void writeParameters(JsonWriter writer, WebService.Action action, boolean includeInternals) {
    List<WebService.Param> params = action.params().stream().filter(p -> includeInternals || !p.isInternal())
            .collect(MoreCollectors.toList());
    if (!params.isEmpty()) {
        // sort parameters by key
        Ordering<WebService.Param> ordering = Ordering.natural().onResultOf(WebService.Param::key);
        writer.name("params").beginArray();
        for (WebService.Param param : ordering.sortedCopy(params)) {
            writeParam(writer, param);/*w  w w .j ava2 s.  c  om*/
        }
        writer.endArray();
    }
}

From source file:org.sonar.server.ws.WebServicesWs.java

private static void writeAction(JsonWriter writer, Action action, boolean includeInternals) {
    if (includeInternals || !action.isInternal()) {
        writer.beginObject();//from   www. jav a2 s .c o  m
        writer.prop("key", action.key());
        writer.prop("description", action.description());
        writer.prop("since", action.since());
        writer.prop("deprecatedSince", action.deprecatedSince());
        writer.prop("internal", action.isInternal());
        writer.prop("post", action.isPost());
        writer.prop("hasResponseExample", action.responseExample() != null);
        List<Param> params = action.params().stream().filter(p -> includeInternals || !p.isInternal())
                .collect(Collectors.toList());
        if (!params.isEmpty()) {
            // sort parameters by key
            Ordering<Param> ordering = Ordering.natural().onResultOf(Param::key);
            writer.name("params").beginArray();
            for (Param param : ordering.sortedCopy(params)) {
                writeParam(writer, param);
            }
            writer.endArray();
        }
        writer.endObject();
    }
}

From source file:org.sonar.server.ws.ws.ListAction.java

private static void writeController(JsonWriter writer, WebService.Controller controller,
        boolean includeInternals) {
    if (includeInternals || !controller.isInternal()) {
        writer.beginObject();//ww w. j  a v a 2  s .  c om
        writer.prop("path", controller.path());
        writer.prop("since", controller.since());
        writer.prop("description", controller.description());
        // sort actions by key
        Ordering<WebService.Action> ordering = Ordering.natural().onResultOf(WebService.Action::key);
        writer.name("actions").beginArray();
        for (WebService.Action action : ordering.sortedCopy(controller.actions())) {
            writeAction(writer, action, includeInternals);
        }
        writer.endArray();
        writer.endObject();
    }
}

From source file:org.jpmml.evaluator.Classification.java

static public List<Map.Entry<String, Double>> getWinnerList(Type type,
        Collection<Map.Entry<String, Double>> entries) {
    Ordering<Map.Entry<String, Double>> ordering = (createOrdering(type)).reverse();

    return ordering.sortedCopy(entries);
}

From source file:edu.illinois.keshmesh.detector.Main.java

private static List<Entrypoint> sortedCopy(Iterable<Entrypoint> entryPoints) {
    Ordering<Entrypoint> ordering = Ordering.natural().onResultOf(new Function<Entrypoint, String>() {
        @Override//w w w.j  a  v a 2  s . co  m
        public String apply(Entrypoint entryPoint) {
            return entryPoint.toString();
        }
    });
    return ordering.sortedCopy(entryPoints);
}