Example usage for java.util HashSet retainAll

List of usage examples for java.util HashSet retainAll

Introduction

In this page you can find the example usage for java.util HashSet retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:fr.lip6.segmentations.ProcessHTML5.java

public void run() {
    //ArrayList<String> s1 = new ArrayList<String>();
    //ArrayList<String> s2= new ArrayList<String>();;
    String s1 = "";
    String s2 = "";
    try {//from w  ww.jav a 2  s.c  o m
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://" + Config.mysqlHost + "/" + Config.mysqlDatabase + "", Config.mysqlUser,
                Config.mysqlPassword);
        Statement st2 = con.createStatement();
        ResultSet rs = st2.executeQuery("select * from html5repo where descriptorbom<>''");
        while (rs.next()) {
            s1 = "";
            s2 = "";
            String d1 = rs.getString("descriptor");
            String d2 = rs.getString("descriptorbom");
            int dsize = d1.split(",").length;
            int d2size = d2.split(",").length;
            for (String s : d1.split(",")) {
                String[] part = s.split("=");
                if (!part[0].equals("PAGE")) {
                    if (part[1].equals("SECTION"))
                        s1 += "S";
                    if (part[1].equals("ARTICLE"))
                        s1 += "A";
                    if (part[1].equals("ASIDE"))
                        s1 += "D";
                    if (part[1].equals("HEADER"))
                        s1 += "H";
                    if (part[1].equals("FOOTER"))
                        s1 += "F";
                    if (part[1].equals("NAV"))
                        s1 += "N";
                }
            }

            for (String s : d2.split(",")) {
                String[] part = s.split("=");
                if (!part[0].equals("PAGE")) {
                    if (part[1].equals("SECTION"))
                        s2 += "S";
                    if (part[1].equals("ARTICLE"))
                        s2 += "A";
                    if (part[1].equals("ASIDE"))
                        s2 += "D";
                    if (part[1].equals("HEADER"))
                        s2 += "H";
                    if (part[1].equals("FOOTER"))
                        s2 += "F";
                    if (part[1].equals("NAV"))
                        s2 += "N";
                }
            }
            int ed = StringUtils.getLevenshteinDistance(s1.toString(), s2.toString());
            int edtotal = Math.max(s1.length(), s2.length());
            HashSet<Character> h1 = new HashSet<Character>(), h2 = new HashSet<Character>();
            for (int i = 0; i < s1.length(); i++) {
                h1.add(s1.charAt(i));
            }
            for (int i = 0; i < s2.length(); i++) {
                h2.add(s2.charAt(i));
            }
            h1.retainAll(h2);
            int inter = h1.size();

            char[] code1 = s1.toCharArray();
            char[] code2 = s2.toCharArray();

            Set set1 = new HashSet();

            for (char c : code1) {
                set1.add(c);
            }

            Set set2 = new HashSet();

            for (char c : code2) {
                set2.add(c);
            }

            int total = set1.size();

            System.out.println(set1);
            System.out.println(set2);
            System.out.println(s1);
            System.out.println(s2);
            System.out.println(rs.getString("id") + ". " + rs.getString("datafolder") + "=" + ed + "/" + edtotal
                    + "=" + ((double) ed / edtotal) + "," + inter + " of " + total + " Prec:("
                    + ((double) inter / total) + ")");
            Statement st3 = con.createStatement();
            //base=distancemax
            st3.execute("update html5repo set distance='" + ed + "',base='" + edtotal + "',found='" + inter
                    + "', expected='" + total + "' where datafolder='" + rs.getString("datafolder") + "'");
            File f = new File("/home/sanojaa/Documents/00_Tesis/work/dataset/dataset/data/"
                    + rs.getString("datafolder") + "/" + rs.getString("datafolder") + ".5.html");
            if (!f.exists()) {
                f.createNewFile();
            }
            FileOutputStream fop = new FileOutputStream(f);
            fop.write(rs.getString("src").getBytes());
            fop.flush();
            fop.close();

        }
    } catch (SQLException ex) {
        Logger.getLogger(SeleniumWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(HTML5Bom.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ProcessHTML5.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ProcessHTML5.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.elasticsearch.common.geo.builders.BasePolygonBuilder.java

/**
 * Validates only 1 vertex is tangential (shared) between the interior and exterior of a polygon
 *//*from w w w . jav  a 2  s  .  c  om*/
protected void validateHole(BaseLineStringBuilder shell, BaseLineStringBuilder hole) {
    HashSet exterior = Sets.newHashSet(shell.points);
    HashSet interior = Sets.newHashSet(hole.points);
    exterior.retainAll(interior);
    if (exterior.size() >= 2) {
        throw new InvalidShapeException(
                "Invalid polygon, interior cannot share more than one point with the exterior");
    }
}

From source file:pathwaynet.PathwayCalculator.java

private <E> void testForGivenListWithClustering(Graph<E, String> graph, Collection<E> componentsInGroup,
        Collection<E> componentsConsidered, int clusteringMethod, int test) {
    HashSet<E> componentsInGroupAvailable = new HashSet<>();
    componentsInGroupAvailable.addAll(componentsInGroup);
    componentsInGroupAvailable.retainAll(componentsConsidered);

    HierarchicalClusterer<E> clusterer = new HierarchicalClusterer(graph, componentsInGroupAvailable,
            clusteringMethod);// ww w . j  ava  2  s  .co m
    ArrayList<ArrayList<E>> clusters = clusterer.getReasonableNumberOfClusters();

    ArrayList<TestResultForList> testResults = new ArrayList<>();
    clusters.forEach((componentsInCluster) -> {
        if (componentsInCluster.size() >= 2) {
            if (test == PERMUTATION_BASED)
                testResults.add(PathwayCalculator.this.testForGivenListPermutationBased(graph,
                        componentsInCluster, componentsConsidered, false));
            else if (test == WILCOXON_BASED)
                testResults.add(PathwayCalculator.this.testForGivenListWilcoxBased(graph, componentsInCluster,
                        componentsConsidered, false));
            else
                testResults.add(null);
        } else
            testResults.add(null);
    });

    for (int i = 0; i < testResults.size(); i++) {
        if (testResults.get(i) != null)
            System.out.println(clusters.get(i) + "\t" + testResults.get(i));
    }
}

From source file:pathwaynet.PathwayCalculator.java

private <T> HashMap<T, Map<T, Number>> getDistancesWithGroup(HashMap<T, Map<T, Number>> distancesMap,
        Collection<T> componentsInGroup, Collection<T> componentsConsidered, boolean onlyFromSource,
        boolean insideGroup) {
    // get the in-group set and out-group set of enzymes
    HashSet<T> componentsOutsideGroupAvailable = new HashSet<>();
    componentsOutsideGroupAvailable.addAll(distancesMap.keySet());
    componentsOutsideGroupAvailable.retainAll(componentsConsidered);
    componentsOutsideGroupAvailable.removeAll(componentsInGroup);

    HashSet<T> componentsInGroupAvailable = new HashSet<>();
    componentsInGroupAvailable.addAll(distancesMap.keySet());
    componentsInGroupAvailable.retainAll(componentsConsidered);
    componentsInGroupAvailable.removeAll(componentsOutsideGroupAvailable);

    // obtain distance
    HashMap<T, Map<T, Number>> distancesFromGroup = new HashMap<>();
    if (insideGroup && componentsInGroupAvailable.size() < 2)
        System.err.println("WARNING: Fewer than TWO given components are involved in the pathway.");
    else if ((!insideGroup)
            && (componentsInGroupAvailable.isEmpty() || componentsOutsideGroupAvailable.isEmpty()))
        System.err.println(//  w w  w  .j  av  a2 s  .  c o m
                "WARNING: There is either no or full overlap between the given components and the ones involving in the pathway.");
    else {
        componentsInGroupAvailable.stream().forEach((component1) -> {
            distancesFromGroup.put(component1, new HashMap<>());
            distancesMap.keySet().stream().forEach((component2) -> {
                Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);

                if (insideGroup
                        && (componentsInGroupAvailable.contains(component2) && (!component1.equals(component2)))
                        && minDist != null) {
                    distancesFromGroup.get(component1).put(component2, minDist);
                } else if ((!insideGroup) && componentsOutsideGroupAvailable.contains(component2)
                        && minDist != null) {
                    distancesFromGroup.get(component1).put(component2, minDist);
                }
            });

            //System.err.println(component1 + "\t" + componentsInGroupAvailable.size() +"\t" + componentsOutsideGroupAvailable.size() + "\t" + distancesFromGroup.get(component1).values());
        });
    }
    return distancesFromGroup;
}

From source file:pathwaynet.PathwayCalculator.java

private <E> TestResultForList testForGivenListPermutationBased(Graph<E, String> graph,
        Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) {
    // calculate and cache all distances
    DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph);
    HashMap<E, Map<E, Number>> distancesMap = new HashMap<>();
    graph.getVertices().stream().forEach((component) -> {
        Map<E, Number> distancesFromThis = distances.getDistanceMap(component);
        distancesMap.put(component, distancesFromThis);
    });//from  w w w .  j a v  a  2  s.  com

    // generate in-group list and all-available list
    HashSet<E> componentsInGroupAvailable = new HashSet<>();
    componentsInGroupAvailable.addAll(graph.getVertices());
    componentsInGroupAvailable.retainAll(componentsConsidered);
    componentsInGroupAvailable.retainAll(componentsInGroup);
    HashSet<E> componentsAvailable = new HashSet<>();
    componentsAvailable.addAll(graph.getVertices());
    componentsAvailable.retainAll(componentsConsidered);

    // store within-group distances for the given list
    if (componentsInGroupAvailable.size() < 2
            || componentsInGroupAvailable.size() > componentsAvailable.size() - 2) {
        System.err.println(
                "ERROE! Please check your component list: too few or too many components in the list.");
        return new TestResultForList(Double.NaN, Double.NaN, Double.NaN);
    }
    ArrayList<Double> distInGroup = new ArrayList<>();
    componentsInGroupAvailable.forEach((component1) -> {
        componentsInGroupAvailable.forEach((component2) -> {
            Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);
            if (!component1.equals(component2) && minDist != null) {
                distInGroup.add(minDist.doubleValue());
            }
        });
    });
    double[] distInGroupVector = new double[distInGroup.size()];
    for (int i = 0; i < distInGroup.size(); i++)
        distInGroupVector[i] = distInGroup.get(i);
    double meanInGroup = new Mean().evaluate(distInGroupVector);

    // permutations
    ArrayList<Double> meansInPermutGroups = new ArrayList<>();
    ArrayList<HashSet<E>> permutatedGroups = generatePermutatedGroups(componentsAvailable,
            componentsInGroupAvailable.size());
    permutatedGroups.forEach((componentsInPermutatedGroup) -> {
        ArrayList<Double> distInPermutGroup = new ArrayList<>();
        componentsInPermutatedGroup.forEach((component1) -> {
            componentsInPermutatedGroup.forEach((component2) -> {
                Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);
                if (!component1.equals(component2) && minDist != null) {
                    distInPermutGroup.add(minDist.doubleValue());
                }
            });
        });
        double[] distInPermutGroupVector = new double[distInPermutGroup.size()];
        for (int i = 0; i < distInPermutGroup.size(); i++)
            distInPermutGroupVector[i] = distInPermutGroup.get(i);
        meansInPermutGroups.add(new Mean().evaluate(distInPermutGroupVector));
    });
    double[] meansInPermutGroupsVector = new double[meansInPermutGroups.size()];
    for (int i = 0; i < meansInPermutGroups.size(); i++)
        meansInPermutGroupsVector[i] = meansInPermutGroups.get(i);
    double medianPermut = new Median().evaluate(meansInPermutGroupsVector);
    double p = ((double) meansInPermutGroups.stream().filter(notGreaterThan(meanInGroup)).count())
            / meansInPermutGroups.size();

    return new TestResultForList(p, meanInGroup, medianPermut);
}

From source file:pathwaynet.PathwayCalculator.java

private <E> HashMap<E, TestResultForEachVertex> testForEachComponent(Graph<E, String> graph,
        Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) {
    HashMap<E, TestResultForEachVertex> significance = new HashMap<>();

    // calculate and cache all distances
    DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph);
    HashMap<E, Map<E, Number>> distancesMap = new HashMap<>();
    graph.getVertices().stream().forEach((component) -> {
        Map<E, Number> distancesFromThis = distances.getDistanceMap(component);
        distancesMap.put(component, distancesFromThis);
    });//from www.  j  av a  2s  . com

    // calculate real in-group and out-group distances
    HashMap<E, Map<E, Number>> distancesInsideGroup = getDistancesWithGroup(distancesMap, componentsInGroup,
            componentsConsidered, onlyFromSource, true);
    HashMap<E, Map<E, Number>> distancesOutsideGroup = getDistancesWithGroup(distancesMap, componentsInGroup,
            componentsConsidered, onlyFromSource, false);

    if (distancesInsideGroup.isEmpty() || distancesOutsideGroup.isEmpty()) {
        System.err.println("WARNING: Please double check the enzyme list!");
    } else {
        HashMap<E, ArrayList<Double>> differencesProp = new HashMap<>();
        distancesInsideGroup.keySet().stream().forEach((component) -> {
            ArrayList<Double> diffIncreaseProp = estimateDifferenceOfProportionAtDistances(
                    distancesInsideGroup.get(component).values(),
                    distancesOutsideGroup.get(component).values());
            differencesProp.put(component, diffIncreaseProp);
            //System.err.println(enzyme.getID()+"\t"+diffIncreaseProp);
        });

        // for each enzyme in the given group, estimate its significance of neighbor enrichment of enzymes in the group
        //System.err.println();
        distancesInsideGroup.keySet().stream().forEach((component) -> {
            // do permutation (for numPermutations times) to generate random group with the same size and with this enzyme
            HashSet<E> allComponentsAvailable = new HashSet<>();
            allComponentsAvailable.addAll(graph.getVertices());
            allComponentsAvailable.retainAll(componentsConsidered);
            ArrayList<HashSet<E>> componentsInGroupPermutations = generatePermutatedGroupsWithFixedNode(
                    component, allComponentsAvailable, distancesInsideGroup.size());

            // for each permutation, calculate the differences of proportion between within-group and between-group path at each path length
            ArrayList<ArrayList<Double>> differencesPropPermutations = new ArrayList<>();
            componentsInGroupPermutations.stream().forEach((componentsInGroupThisPermutation) -> {
                HashSet<E> componentsOutGroupThisPermutation = new HashSet<>();
                componentsOutGroupThisPermutation.addAll(graph.getVertices());
                componentsOutGroupThisPermutation.removeAll(componentsInGroupThisPermutation);

                HashMap<E, Number> distancesInPermut = new HashMap<>();
                HashMap<E, Number> distancesOutPermut = new HashMap<>();
                allComponentsAvailable.forEach((component2) -> {
                    Number minDist = getShortestDistance(distancesMap, component, component2, onlyFromSource);

                    if (componentsInGroupThisPermutation.contains(component2) && (!component.equals(component2))
                            && minDist != null)
                        distancesInPermut.put(component2, minDist);
                    else if (componentsOutGroupThisPermutation.contains(component2) && minDist != null)
                        distancesOutPermut.put(component2, minDist);
                });
                differencesPropPermutations.add(estimateDifferenceOfProportionAtDistances(
                        distancesInPermut.values(), distancesOutPermut.values()));
            });

            // calculate the significance
            // P: based on Pearson's correlation between differences of proportions and distances
            // domain: based on the quantile of difference at each distance
            //System.err.println(component);
            double p = calculatePValue(differencesProp.get(component), differencesPropPermutations);
            int radius = estimateDomainRadius(differencesProp.get(component), differencesPropPermutations, 0.9);
            significance.put(component, new TestResultForEachVertex(p, radius));

            if (cache) {

            }
        });
    }

    return significance;
}

From source file:com.net2plan.gui.utils.topologyPane.jung.JUNGCanvas.java

/**
 * Default constructor.//from w w  w .  j  av a  2 s. c  om
 *
 * @since 0.2.3
 */
public JUNGCanvas(IVisualizationCallback callback, TopologyPanel topologyPanel) {
    this.callback = callback;

    transformNetPlanCoordinatesToJungCoordinates = vertex -> {
        final int vlIndex = this.callback.getVisualizationState()
                .getCanvasVisualizationOrderRemovingNonVisible(vertex.getLayer());
        final double interLayerDistanceInNpCoord = currentInterLayerDistanceInNpCoordinates;
        final Point2D basePositionInNetPlanCoord = vertex.getAssociatedNetPlanNode().getXYPositionMap();
        return new Point2D.Double(basePositionInNetPlanCoord.getX(),
                -(basePositionInNetPlanCoord.getY() + (vlIndex * interLayerDistanceInNpCoord)));
    };

    g = new DirectedOrderedSparseMultigraph<>();
    l = new StaticLayout<>(g, transformNetPlanCoordinatesToJungCoordinates);
    vv = new VisualizationViewer<>(l);

    osmStateManager = new OSMStateManager(callback, topologyPanel, this);

    originalEdgeShapeTransformer = new EdgeShape.QuadCurve<>();
    ((EdgeShape.QuadCurve<GUINode, GUILink>) originalEdgeShapeTransformer).setControlOffsetIncrement(10); // how much they separate from the direct line (default is 20)
    //((EdgeShape.QuadCurve<GUINode, GUILink>) originalEdgeShapeTransformer).setEdgeIndexFunction(DefaultParallelEdgeIndexFunction.<GUINode, GUILink>getInstance()); // how much they separate from the direct line (default is 20)
    /* This functions gives an index to the links to show separate (curved): the order among the parallel links (BUT NOW only among the separated ones among them) */
    ((EdgeShape.QuadCurve<GUINode, GUILink>) originalEdgeShapeTransformer)
            .setEdgeIndexFunction(new EdgeIndexFunction<GUINode, GUILink>() {
                public void reset(Graph<GUINode, GUILink> graph, GUILink e) {
                }

                public void reset() {
                }

                public int getIndex(Graph<GUINode, GUILink> graph, GUILink e) {
                    final GUINode u = e.getOriginNode();
                    final GUINode v = e.getDestinationNode();
                    final HashSet<GUILink> commonEdgeSet = new HashSet<>(graph.getInEdges(v));
                    commonEdgeSet.retainAll(graph.getOutEdges(u));
                    commonEdgeSet.removeIf(ee -> !ee.isShownSeparated());
                    int count = 0;
                    for (GUILink other : commonEdgeSet)
                        if (other == e)
                            return count;
                        else
                            count++;
                    throw new RuntimeException();
                }
            });
    /* Customize the graph */
    vv.getRenderContext().setVertexDrawPaintTransformer(n -> n.getDrawPaint());
    vv.getRenderContext().setVertexFillPaintTransformer(n -> n.getFillPaint());
    vv.getRenderContext().setVertexFontTransformer(n -> n.getFont());

    vv.getRenderContext().setVertexIconTransformer(gn -> gn.getIcon());

    vv.getRenderContext().setVertexIncludePredicate(
            guiNodeContext -> callback.getVisualizationState().isVisibleInCanvas(guiNodeContext.element));
    vv.getRenderer().setVertexLabelRenderer(new NodeLabelRenderer());
    vv.setVertexToolTipTransformer(node -> node.getToolTip());

    vv.getRenderContext().setEdgeIncludePredicate(
            context -> callback.getVisualizationState().isVisibleInCanvas(context.element));
    vv.getRenderContext().setEdgeArrowPredicate(
            context -> callback.getVisualizationState().isVisibleInCanvas(context.element)
                    && context.element.getHasArrow());
    vv.getRenderContext().setEdgeArrowStrokeTransformer(i -> i.getArrowStroke());
    vv.getRenderContext()
            .setEdgeArrowTransformer(new ConstantTransformer(ArrowFactory.getNotchedArrow(7, 10, 5)));
    vv.getRenderContext().setEdgeLabelClosenessTransformer(new ConstantDirectionalEdgeValueTransformer(.6, .6));
    vv.getRenderContext().setEdgeStrokeTransformer(i -> i.getEdgeStroke());

    vv.getRenderContext().setEdgeDrawPaintTransformer(e -> e.getEdgeDrawPaint());
    vv.getRenderContext().setArrowDrawPaintTransformer(e -> e.getArrowDrawPaint());
    vv.getRenderContext().setArrowFillPaintTransformer(e -> e.getArrowFillPaint());

    vv.getRenderContext().setEdgeLabelRenderer(new DefaultEdgeLabelRenderer(Color.BLUE));
    vv.getRenderer().setEdgeLabelRenderer(new BasicEdgeLabelRenderer<GUINode, GUILink>() {
        public void labelEdge(RenderContext<GUINode, GUILink> rc, Layout<GUINode, GUILink> layout, GUILink e,
                String label) {
            if (callback.getVisualizationState().isCanvasShowLinkLabels())
                super.labelEdge(rc, layout, e, e.getLabel());
        }
    });
    vv.setEdgeToolTipTransformer(link -> link.getToolTip());
    vv.getRenderContext().setEdgeShapeTransformer(
            c -> c.element.isShownSeparated() ? originalEdgeShapeTransformer.transform(c)
                    : new Line2D.Float(0.0f, 0.0f, 1.0f, 0.0f));

    // Background controller
    this.paintableAssociatedToBackgroundImage = null;

    gm = new PluggableGraphMouse();
    vv.setGraphMouse(gm);

    scalingControl = new LayoutScalingControl();
    ITopologyCanvasPlugin scalingPlugin = new ScalingCanvasPlugin(scalingControl, MouseEvent.NOBUTTON);
    addPlugin(scalingPlugin);

    vv.setOpaque(false);
    vv.setBackground(new Color(0, 0, 0, 0));

    this.updateInterLayerDistanceInNpCoordinates(callback.getVisualizationState().getInterLayerSpaceInPixels());

    //        reset();
}

From source file:es.pode.gestorFlujo.presentacion.objetosPendientes.Publicar.PublicarControllerImpl.java

private String[] interseccionNodos(String nodos) throws Exception {
    SrvNodoService nodosPlataforma = this.getSrvNodoService();

    String[] nodosListados = obtenNodosLocalesIds(nodosPlataforma);
    HashSet nodosTotal = new HashSet(Arrays.asList(nodosListados));
    ArrayList listaNodos = new ArrayList(Arrays.asList(nodos.split(",")));
    HashSet nodosLeidos = new HashSet(listaNodos);
    nodosLeidos.retainAll(nodosTotal);
    if (!nodosLeidos.contains(nodosListados[0])) {
        nodosLeidos.add(nodosListados[0]);
    }//from   w  w w . ja va 2  s .  c o m
    String[] retorno = (String[]) nodosLeidos.toArray(new String[0]);
    return retorno;
}

From source file:playground.meisterk.org.matsim.run.westumfahrung.CompareScenarios.java

/**
 * Gets all agents that use a set of links in one plans file and use another set in another plans file.
 * For example: Find all agents that use the Westtangente in a scenario without the Westumfahrung, that
 * switch to the Westumfahrung in a case study where the Westumfahrung was included in the scenario.
 *
 * Summarize their average trip travel times, the scores of their selected plans, and their home locations.
 *///from   w w  w .  j a v a2s.c  o m
private void doAnalyses(World world) {

    TreeMap<Integer, TreeMap<String, PersonIdRecorder>> personIdRecorders = new TreeMap<Integer, TreeMap<String, PersonIdRecorder>>();

    for (Integer analysis : this.analysisNames.keySet()) {
        personIdRecorders.put(analysis, new TreeMap<String, PersonIdRecorder>());
    }
    TreeMap<String, Population> scenarioPlans = new TreeMap<String, Population>();
    TreeMap<String, Network> scenarioNetworks = new TreeMap<String, Network>();

    PersonIdRecorder personIdRecorder = null;
    PersonFilter filterAlgorithm = null;

    for (String scenarioName : this.scenarioNames) {

        ScenarioImpl scenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
        Network network = scenario.getNetwork();
        new MatsimNetworkReader(scenario).readFile(this.networkInputFilenames.get(scenarioName));
        scenarioNetworks.put(scenarioName, network);

        //Plans plans = playground.meisterk.MyRuns.initMatsimAgentPopulation(plansInputFilenames.get(scenarioName), false, null, network);
        PopulationImpl plans = (PopulationImpl) scenario.getPopulation();
        PopulationReader plansReader = new MatsimPopulationReader(scenario);
        plansReader.readFile(this.plansInputFilenames.get(scenarioName));
        plans.printPlansCount();

        scenarioPlans.put(scenarioName, plans);

        for (Integer analysis : this.analysisNames.keySet()) {

            personIdRecorder = new PersonIdRecorder();

            // distinguish person filtering by analysis type
            switch (analysis.intValue()) {
            case TRANSIT_AGENTS_ANALYSIS_NAME:
                filterAlgorithm = new PersonIdFilter(TRANSIT_PERSON_ID_PATTERN, personIdRecorder);
                break;
            case NON_TRANSIT_AGENTS_ANALYSIS_NAME:
                filterAlgorithm = new PersonIdFilter(NON_TRANSIT_PERSON_ID_PATTERN, personIdRecorder);
                break;
            case ROUTE_SWITCHERS_ANALYSIS_NAME:
                RouteLinkFilter routeLinkFilter = new RouteLinkFilter(personIdRecorder);
                filterAlgorithm = new SelectedPlanFilter(routeLinkFilter);

                for (Id linkId : this.linkSets.get(scenarioName)) {
                    routeLinkFilter.addLink(linkId);
                }
                break;
            case WESTSTRASSE_NEIGHBORS_ANALYSIS_NAME:
                ActLinkFilter homeAtTheWeststrasseFilter = new ActLinkFilter(".*h.*", personIdRecorder);
                filterAlgorithm = new SelectedPlanFilter(homeAtTheWeststrasseFilter);

                for (Id linkId : this.weststrasseLinkIds) {
                    homeAtTheWeststrasseFilter.addLink(linkId);
                }
                break;
            default:
                break;
            }

            personIdRecorders.get(analysis).put(scenarioName, personIdRecorder);
            plans.addAlgorithm(filterAlgorithm);
        }
        plans.runAlgorithms();

    }

    // make this nicer, because all analyses are of the same kind :-)
    HashSet<Id> routeSwitchersPersonIds = (HashSet<Id>) personIdRecorders.get(ROUTE_SWITCHERS_ANALYSIS_NAME)
            .get(this.scenarioNameAfter).getIds().clone();
    routeSwitchersPersonIds.retainAll(
            personIdRecorders.get(ROUTE_SWITCHERS_ANALYSIS_NAME).get(this.scenarioNameBefore).getIds());

    HashSet<Id> neighborsPersonIds = personIdRecorders.get(WESTSTRASSE_NEIGHBORS_ANALYSIS_NAME)
            .get(this.scenarioNameBefore).getIds();
    HashSet<Id> transitAgentsIds = personIdRecorders.get(TRANSIT_AGENTS_ANALYSIS_NAME)
            .get(this.scenarioNameBefore).getIds();
    HashSet<Id> nonTransitAgentsIds = personIdRecorders.get(NON_TRANSIT_AGENTS_ANALYSIS_NAME)
            .get(this.scenarioNameBefore).getIds();

    log.info("Agents before: " + personIdRecorders.get(ROUTE_SWITCHERS_ANALYSIS_NAME)
            .get(this.scenarioNameBefore).getIds().size());
    log.info("Agents after: "
            + personIdRecorders.get(ROUTE_SWITCHERS_ANALYSIS_NAME).get(this.scenarioNameAfter).getIds().size());
    log.info("Route switchers: " + routeSwitchersPersonIds.size());
    log.info("number of neighbors: " + neighborsPersonIds.size());
    log.info("number of transit agents: " + transitAgentsIds.size());
    log.info("number of non transit agents: " + nonTransitAgentsIds.size());

    Iterator<Id> personIterator = null;
    //      HashSet<Id> subPop = new HashSet<Id>();
    for (Integer analysis : this.analysisNames.keySet()) {

        ArrayList<CaseStudyResult> results = new ArrayList<CaseStudyResult>();
        for (String scenarioName : this.scenarioNames) {

            ScenarioImpl subScenario = (ScenarioImpl) ScenarioUtils.createScenario(ConfigUtils.createConfig());
            subScenario.setNetwork(scenarioNetworks.get(scenarioName));
            Population plansSubPop = subScenario.getPopulation();
            switch (analysis.intValue()) {
            case TRANSIT_AGENTS_ANALYSIS_NAME:
                personIterator = transitAgentsIds.iterator();
                break;
            case NON_TRANSIT_AGENTS_ANALYSIS_NAME:
                personIterator = nonTransitAgentsIds.iterator();
                break;
            case ROUTE_SWITCHERS_ANALYSIS_NAME:
                personIterator = routeSwitchersPersonIds.iterator();
                break;
            case WESTSTRASSE_NEIGHBORS_ANALYSIS_NAME:
                personIterator = neighborsPersonIds.iterator();
                break;
            default:
                break;
            }

            while (personIterator.hasNext()) {
                try {
                    plansSubPop
                            .addPerson(scenarioPlans.get(scenarioName).getPersons().get(personIterator.next()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            Activity homeActivity = null;
            if (analysis.intValue() == ROUTE_SWITCHERS_ANALYSIS_NAME) {
                if (scenarioName.equals(this.scenarioNames[0])) {
                    this.routeSwitchersLines.add("person\thome_link\thome_x\thome_y");
                    for (Person person : plansSubPop.getPersons().values()) {
                        for (PlanElement pe : person.getSelectedPlan().getPlanElements()) {
                            if (pe instanceof Activity) {
                                homeActivity = (Activity) pe;
                                if (Pattern.matches(".*h.*", homeActivity.getType())) {
                                    continue;
                                }
                            }
                        }
                        this.routeSwitchersLines
                                .add(person.getId().toString() + "\t" + homeActivity.getLinkId().toString()
                                        + "\t" + Double.toString(homeActivity.getCoord().getX()) + "\t"
                                        + Double.toString(homeActivity.getCoord().getY()));

                        //                     routeSwitchersLines.add(new String(
                        //                           person.getId() + "\t" +
                        //                           homeActivity.getLinkId().toString() + "\t" +
                        //                           homeActivity.getCoord().getX() + "\t" +
                        //                           homeActivity.getCoord().getY()
                        //                     ));
                    }
                }
            }

            PlanAverageScore planAverageScore = new PlanAverageScore();
            planAverageScore.run(plansSubPop);
            CalcAverageTripLength calcAverageTripLength = new CalcAverageTripLength(
                    scenarioNetworks.get(scenarioName));
            calcAverageTripLength.run(plansSubPop);

            EventsManager events = EventsUtils.createEventsManager();

            CalcLegTimes calcLegTimes = new CalcLegTimes();
            events.addHandler(calcLegTimes);

            results.add(new CaseStudyResult(scenarioName, plansSubPop, calcLegTimes, planAverageScore,
                    calcAverageTripLength));

            //            EventsReaderDEQv1 eventsReader = new EventsReaderDEQv1(events);
            //            log.info("events filename: " + this.eventsInputFilenames.get(scenarioName));
            //            eventsReader.readFile(this.eventsInputFilenames.get(scenarioName));
            throw new RuntimeException("reading binary events is no longer supported.");

        }
        this.scenarioComparisonLines.add("Analysis: " + this.analysisNames.get(analysis));
        this.writeComparison(results);
        this.scenarioComparisonLines.add("");

    }

}

From source file:pathwaynet.PathwayCalculator.java

private <E> TestResultForList testForGivenListWilcoxBased(Graph<E, String> graph,
        Collection<E> componentsInGroup, Collection<E> componentsConsidered, boolean onlyFromSource) {
    double p = Double.NaN;
    double meanInGroup = Double.NaN;
    double meanOutGroup = Double.NaN;

    // calculate and cache all distances
    DijkstraDistance<E, String> distances = new DijkstraDistance<>(graph);
    HashMap<E, Map<E, Number>> distancesMap = new HashMap<>();
    graph.getVertices().stream().forEach((component) -> {
        Map<E, Number> distancesFromThis = distances.getDistanceMap(component);
        distancesMap.put(component, distancesFromThis);
    });//from  ww  w.  j  a v  a  2 s.c  o  m

    // generate in-group list and out-group list
    HashSet<E> componentsInGroupAvailable = new HashSet<>();
    HashSet<E> componentsOutGroupAvailable = new HashSet<>();
    componentsInGroupAvailable.addAll(graph.getVertices());
    componentsOutGroupAvailable.addAll(graph.getVertices());
    componentsInGroupAvailable.retainAll(componentsConsidered);
    componentsOutGroupAvailable.retainAll(componentsConsidered);
    componentsInGroupAvailable.retainAll(componentsInGroup);
    componentsOutGroupAvailable.removeAll(componentsInGroup);

    // store within-group distances for the given list, as well as distances between components in the list and ones out of the list
    ArrayList<Double> distInGroup = new ArrayList<>();
    ArrayList<Double> distOutGroup = new ArrayList<>();
    componentsInGroupAvailable.forEach((component1) -> {
        componentsInGroupAvailable.forEach((component2) -> {
            Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);
            if (!component1.equals(component2) && minDist != null) {
                distInGroup.add(minDist.doubleValue());
            }
        });
        componentsOutGroupAvailable.forEach((component2) -> {
            Number minDist = getShortestDistance(distancesMap, component1, component2, onlyFromSource);
            if (!component1.equals(component2) && minDist != null) {
                distOutGroup.add(minDist.doubleValue());
            }
        });
    });

    if (distInGroup.size() >= 2 && distOutGroup.size() >= 2) {
        double[] distInGroupVector = new double[distInGroup.size()];
        double[] distOutGroupVector = new double[distOutGroup.size()];
        for (int i = 0; i < distInGroup.size(); i++)
            distInGroupVector[i] = distInGroup.get(i);
        for (int i = 0; i < distOutGroup.size(); i++)
            distOutGroupVector[i] = distOutGroup.get(i);

        p = new MannWhitneyUTest().mannWhitneyUTest(distInGroupVector, distOutGroupVector);
        //System.err.println(distInGroup+"\t"+distOutGroup);
        meanInGroup = new Mean().evaluate(distInGroupVector);
        meanOutGroup = new Mean().evaluate(distOutGroupVector);

    } else {
        System.err.println("Error: please check your list: too few components involving in the pathway");
    }

    return new TestResultForList(p, meanInGroup, meanOutGroup);
}