org.jgrapht.graph.DefaultEdge Java Examples

The following examples show how to use org.jgrapht.graph.DefaultEdge. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GraphEnricherImplTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
/**
 * The test data in this class is all written w/ case-sensitivy as the default.
 * If we pass caseInsensitive == true, then we enable that mode in the graph enricher and tweak the object names
 * a bit so that we can verify that the resolution works either way.
 */
private void testSchemaObjectDependencies(boolean caseInsensitive) {
    this.enricher = new GraphEnricherImpl(caseInsensitive ? String::toUpperCase : Functions.getStringPassThru()::valueOf);

    SortableDependencyGroup sch1Obj1 = newChange(schema1, type1, "obj1", Sets.immutable.with("obj3", schema2 + ".obj2"));
    SortableDependencyGroup sch1Obj2 = newChange(schema1, type2, "obj2", Sets.immutable.<String>with());
    // change the case of the object name to ensure others can still point to it
    SortableDependencyGroup sch1Obj3 = newChange(schema1, type1, caseInsensitive ? "obj3".toUpperCase() : "obj3", Sets.immutable.with("obj2"));
    // change the case of the dependency name to ensure that it can point to others
    SortableDependencyGroup sch2Obj1 = newChange(schema2, type1, "obj1", Sets.immutable.with(caseInsensitive ? "obj2".toUpperCase() : "obj2"));
    SortableDependencyGroup sch2Obj2 = newChange(schema2, type2, "obj2", Sets.immutable.with(schema1 + ".obj3"));

    Graph<SortableDependencyGroup, DefaultEdge> sortGraph = enricher.createDependencyGraph(Lists.mutable.with(
            sch1Obj1, sch1Obj2, sch1Obj3, sch2Obj1, sch2Obj2), false);

    validateChange(sortGraph, sch1Obj1, Sets.immutable.with(sch1Obj3, sch2Obj2), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sch1Obj2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sch1Obj3));
    validateChange(sortGraph, sch1Obj3, Sets.immutable.with(sch1Obj2), Sets.immutable.with(sch1Obj1, sch2Obj2));
    validateChange(sortGraph, sch2Obj1, Sets.immutable.with(sch2Obj2), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sch2Obj2, Sets.immutable.with(sch1Obj3), Sets.immutable.with(sch1Obj1, sch2Obj1));
}
 
Example #2
Source File: GenerateFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
public FormulaWithAdornments generate(IFormula formula, UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne, 
        UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphTwo, List<VariablePair> variablePairs) {
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraph = chooseSubgraphWithNoVirtualVertices(connectedSubgraphOne, connectedSubgraphTwo);
    if (connectedSubgraph == null) {
        throw new IllegalArgumentException("Please add explicit selection for variables to make the formula symmetric...");
    }

    FormulaWithAdornments formulaWithAdornment = new FormulaWithAdornments(formula.clone());
    List<IFormulaAtom> symmetricAtoms = extractFormulaAtoms(connectedSubgraph);
    if (logger.isDebugEnabled()) logger.debug("Symmetric atoms: " + symmetricAtoms);
    removeAtoms(formulaWithAdornment, symmetricAtoms);
    Set<FormulaVariable> variablesToKeep = findVariablesToKeep(formulaWithAdornment);
    if (logger.isDebugEnabled()) logger.debug("Variables to keep: " + variablesToKeep);
    removeUnneededVariables(formulaWithAdornment, variablesToKeep);
    removeUnneededVariableOccurrences(formulaWithAdornment, symmetricAtoms);
    equivalenceClassFinder.findVariableEquivalenceClasses(formulaWithAdornment.getFormula());
    addAdornments(formulaWithAdornment, variablePairs);
    if (logger.isDebugEnabled()) logger.debug("Result: " + formulaWithAdornment);
    return formulaWithAdornment;
}
 
Example #3
Source File: InvocationGraphImpl.java    From custom-bytecode-analyzer with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Collection<Call> pathsToParents(MethodGraph element) {
  Collection<Call> paths = new HashSet<>();
    logger.debug("Finding path to parents for: {} ", element);
  if (!directedGraph.containsVertex(element)) {
    logger.warn("Graph does not contain vertex: {} . Returning empty collection.", element);
    return paths;
  }
  Set<DefaultEdge> incomingEdges = directedGraph.incomingEdgesOf(element);
  if (incomingEdges.isEmpty()) {
    Call lonelyCall = new Call(element, null);
    paths.add(lonelyCall);
    return paths;
  }
  for (DefaultEdge incomingEdge : incomingEdges) {
    MethodGraph father = directedGraph.getEdgeSource(incomingEdge);
    logger.debug("Finding path to parents, element={}, father={} . About to find paths from father", element, father);
    Call call = new Call(father, element);
    paths.add(call);
    paths.addAll(pathsToParents(father));
  }
  return paths;
}
 
Example #4
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private UndirectedGraph<FormulaGraphVertex, DefaultEdge> initJoinGraph(IFormula formula) {
    Map<FormulaVariable, FormulaGraphVertex> vertexMap = new HashMap<FormulaVariable, FormulaGraphVertex>();
    UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph = new SimpleGraph<FormulaGraphVertex, DefaultEdge>(DefaultEdge.class);
    for (FormulaVariable formulaVariable : formula.getLocalVariables()) {
        FormulaGraphVertex vertex = new FormulaGraphVertex(formulaVariable);
        graph.addVertex(vertex);
        vertexMap.put(formulaVariable, vertex);
    }
    for (IFormulaAtom atom : formula.getAtoms()) {
        if (atom.isRelational()) {
            addVerticesForRelationalAtom(atom, graph, vertexMap);
        }
        if (atom.isComparison()) {
            addVerticesForComparisonAtom(atom, graph, vertexMap);
        }
    }
    return graph;
}
 
Example #5
Source File: ResourceManager.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
/**
 * Find the resources in {@link #resourcesGraph} matching the given {@code query}.
 *
 * @param query a location eventually containing wildcards
 * @param locationResolver the {@link LocationResolver} to perform the matching of graph nodes against the given
 *            {@code query}
 * @return an unmodifiable list of {@link Resources} that match the given {@code query}
 */
public List<Resource<L>> findResources(L query, LocationResolver<L> locationResolver) {
    graphLockRead.lock();
    try {
        List<Resource<L>> result = new ArrayList<Resource<L>>();
        GraphIterator<Resource<L>, DefaultEdge> it = new BreadthFirstIterator<Resource<L>, DefaultEdge>(
                this.resourcesGraph);
        while (it.hasNext()) {
            Resource<L> resource = it.next();
            if (locationResolver.matches(query, resource.getLocation())) {
                result.add(resource);
            }
        }
        return Collections.unmodifiableList(result);
    } finally {
        graphLockRead.unlock();
    }
}
 
Example #6
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private FormulaWithAdornments findFormulaWithAdornments(UndirectedGraph<FormulaGraphVertex, DefaultEdge> formulaGraph,
        List<VariablePair> variablePairs, List<FormulaVariable> anonymousVariables, IFormula formula) {
    Set<FormulaGraphVertex> vertices = new HashSet<FormulaGraphVertex>(formulaGraph.vertexSet());
    for (VariablePair variablePair : variablePairs) {
        vertices.remove(variablePair.getVertex());
    }
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> subgraph = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, vertices, formulaGraph.edgeSet());
    ConnectivityInspector<FormulaGraphVertex, DefaultEdge> inspector = new ConnectivityInspector<FormulaGraphVertex, DefaultEdge>(subgraph);
    List<Set<FormulaGraphVertex>> connectedVertices = inspector.connectedSets();
    if (connectedVertices.size() != 2) {
        return null;
    }
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, connectedVertices.get(0), formulaGraph.edgeSet());
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphTwo = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, connectedVertices.get(1), formulaGraph.edgeSet());
    VertexEquivalenceComparator vertexComparator = new VertexEquivalenceComparator(variablePairs, anonymousVariables);
    UniformEquivalenceComparator<DefaultEdge, Graph<FormulaGraphVertex, DefaultEdge>> edgeComparator = new UniformEquivalenceComparator<DefaultEdge, Graph<FormulaGraphVertex, DefaultEdge>>();
    GraphIsomorphismInspector<Graph<FormulaGraphVertex, DefaultEdge>> isomorphismInspector = AdaptiveIsomorphismInspectorFactory.createIsomorphismInspector(connectedSubgraphOne, connectedSubgraphTwo, vertexComparator, edgeComparator);
    boolean areIsomorphic = isomorphismInspector.isIsomorphic();
    if (logger.isDebugEnabled()) logger.debug("Graph One: \n" + connectedSubgraphOne + "\nGraph Two: \n" + connectedSubgraphTwo + "\nAre isomorphic: " + areIsomorphic);
    if (!areIsomorphic) {
        return null;
    }
    return formulaWithAdornmentsGenerator.generate(formula, connectedSubgraphOne, connectedSubgraphTwo, variablePairs);
}
 
Example #7
Source File: GraphEnricherImplTest.java    From obevo with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetChangesCaseInsensitive() {
    this.enricher = new GraphEnricherImpl(String::toUpperCase);
    String schema1 = "schema1";
    String schema2 = "schema2";
    String type1 = "type1";

    SortableDependencyGroup sp1 = newChange(schema1, type1, "SP1", "n/a", 0, Sets.immutable.with("sp2"));
    SortableDependencyGroup sp2 = newChange(schema1, type1, "SP2", Sets.immutable.<String>with());
    SortableDependencyGroup sp3 = newChange(schema1, type1, "SP3", Sets.immutable.with("sp1", "sp2"));
    SortableDependencyGroup spA = newChange(schema1, type1, "SPA", Sets.immutable.with("sp3"));
    SortableDependencyGroup sp1Schema2 = newChange(schema2, type1, "sp1", "n/a", 0, Sets.immutable.with("sp2", schema1 + ".sp3"));
    SortableDependencyGroup sp2Schema2 = newChange(schema2, type1, "sP2", "n/a", 0, Sets.immutable.<String>with());

    Graph<SortableDependencyGroup, DefaultEdge> sortGraph = enricher.createDependencyGraph(Lists.mutable.with(
            sp1, sp2, sp3, spA, sp1Schema2, sp2Schema2), false);

    validateChange(sortGraph, sp1, Sets.immutable.with(sp2), Sets.immutable.with(sp3));
    validateChange(sortGraph, sp2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sp1, sp3));
    validateChange(sortGraph, sp3, Sets.immutable.with(sp1, sp2), Sets.immutable.with(spA, sp1Schema2));
    validateChange(sortGraph, spA, Sets.immutable.with(sp3), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sp1Schema2, Sets.immutable.with(sp2Schema2, sp3), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sp2Schema2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sp1Schema2));
}
 
Example #8
Source File: MinimumSteinerTreeApproximation.java    From jReto with MIT License 6 votes vote down vote up
/**
   * Reconstructs the original graph from a metric closure (i.e. a graph that contains all vertices that were used in the edges of the metric closure).
   * @param metricClosure a metric closure
   * @return The reconstructed graph
   */
public static <T> DirectedMultigraph<T, DefaultEdge> reconstructGraphFromMetricClosure(DirectedWeightedPseudograph<T, MetricClosureEdge<T>> metricClosure) {
	DirectedMultigraph<T, DefaultEdge> reconstructedGraph = new DirectedMultigraph<>(DefaultEdge.class);
	
	for (MetricClosureEdge<T> edge : metricClosure.edgeSet()) {
		T previousVertex = metricClosure.getEdgeSource(edge);
		T endVertex = metricClosure.getEdgeTarget(edge);
		reconstructedGraph.addVertex(previousVertex);
		reconstructedGraph.addVertex(endVertex);
		
		for (T subedge : edge.path) {
			if (reconstructedGraph.addVertex(subedge)) {
				reconstructedGraph.addEdge(previousVertex, subedge);
			}
			previousVertex = subedge;
		}
		
		reconstructedGraph.addEdge(previousVertex, endVertex);
	}
	
	return reconstructedGraph;
}
 
Example #9
Source File: ResourceManager.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
/**
 * Remove the resources from {@link #resourcesGraph} matching the given {@code query} including all direct and
 * indirect descendants.
 *
 * @param query a location eventually containing wildcards
 * @param locationResolver the {@link LocationResolver} to perform the matching of graph nodes against the given
 *            {@code query}
 * @return an unmodifiable list of {@link Resources} that were removed by this method
 */
public List<Resource<L>> removeResources(L query, LocationResolver<L> locationResolver) {
    graphLockWrite.lock();
    try {
        List<Resource<L>> doomedResources = new ArrayList<Resource<L>>();
        GraphIterator<Resource<L>, DefaultEdge> it = new DepthFirstIterator<>(this.resourcesGraph);
        while (it.hasNext()) {
            Resource<L> resource = it.next();
            if (locationResolver.matches(query, resource.getLocation())) {
                getAllDescendants(resource, doomedResources);
                doomedResources.add(resource);
            }
        }

        // we couldn't do this while iterating (a ConcurrentModificationException would have resulted)
        // but now that we have the doomed resources, we can remove them from the graph now
        for (Resource<L> doomedResource : doomedResources) {
            this.resourcesGraph.removeVertex(doomedResource);
        }

        return Collections.unmodifiableList(doomedResources);
    } finally {
        graphLockWrite.unlock();
    }
}
 
Example #10
Source File: CavMerger.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void modify(JCas jcas) throws AnalysisEngineProcessException {
  Collection<CandidateAnswerVariant> cavs = TypeUtil.getCandidateAnswerVariants(jcas);
  UndirectedGraph<Object, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
  cavs.forEach(cav -> {
    graph.addVertex(cav);
    for (String name : TypeUtil.getCandidateAnswerVariantNames(cav)) {
      graph.addVertex(name);
      graph.addEdge(cav, name);
    }
  } );
  ConnectivityInspector<Object, DefaultEdge> ci = new ConnectivityInspector<>(graph);
  ci.connectedSets().stream().map(subgraph -> {
    List<CandidateAnswerVariant> subCavs = subgraph.stream()
            .filter(CandidateAnswerVariant.class::isInstance)
            .map(CandidateAnswerVariant.class::cast).collect(toList());
    return TypeFactory.createAnswer(jcas, TypeConstants.SCORE_UNKNOWN, subCavs);
  } ).forEach(Answer::addToIndexes);
}
 
Example #11
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private void addEdgesForEquivalenceClass(String constant, FormulaVariable variable, String operator,
        IFormula formula, UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph, Map<FormulaVariable, FormulaGraphVertex> vertexMap) {
    VariableEquivalenceClass equivalenceClass = DependencyUtility.findEquivalenceClassForVariable(variable, formula.getLocalVariableEquivalenceClasses());
    if (logger.isDebugEnabled()) logger.debug("Adding edges for equivalence class " + equivalenceClass);
    for (FormulaVariable otherVariable : equivalenceClass.getVariables()) {
        if (otherVariable.equals(variable)) {
            continue;
        }
        if (existComparison(otherVariable, constant, formula)) {
            continue;
        }
        Expression expression = new Expression(otherVariable.getId() + operator + constant);
        ComparisonAtom virtualComparisonAtom = new ComparisonAtom(formula, expression, otherVariable.getId(), null, null, constant, operator);
        virtualComparisonAtom.addVariable(otherVariable);
        FormulaGraphVertex virtualComparisonVertex = new FormulaGraphVertex(virtualComparisonAtom);
        virtualComparisonVertex.setVirtual(true);
        graph.addVertex(virtualComparisonVertex);
        FormulaGraphVertex variableVertex = vertexMap.get(otherVariable);
        graph.addEdge(virtualComparisonVertex, variableVertex);
        createConstantVertex(constant, virtualComparisonVertex, graph);
    }
}
 
Example #12
Source File: OozieWorkflowGenerator.java    From arbiter with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the OK transition for an action
 *
 * @param workflowGraph The graph from which to get the transition
 * @param a The action for which to get the transition
 * @return The OK transition for the given action
 */
private Action getTransition(DirectedAcyclicGraph<Action, DefaultEdge> workflowGraph, Action a) {
    Set<DefaultEdge> transitions = workflowGraph.outgoingEdgesOf(a);
    // end and kill nodes do not transition at all
    // forks have multiple transitions and are handled specially
    if (a.getType().equals("end") || a.getType().equals("kill") || a.getType().equals("fork")) {
        return null;
    }
    // This would be a very odd case, as only forks can have multiple transitions
    // This should be impossible, but just in case we catch it and throw an exception
    if (transitions.size() != 1)  {
        throw new RuntimeException("Multiple transitions found for action " + a.getName());
    }

    DefaultEdge transition = transitions.iterator().next();
    return workflowGraph.getEdgeTarget(transition);
}
 
Example #13
Source File: CycleHandler.java    From dkpro-jwpl with Apache License 2.0 6 votes vote down vote up
private DefaultEdge visit(int node) {
    colorMap.put(node, Color.grey);
    Set<DefaultEdge> outgoingEdges = categoryGraph.getGraph().outgoingEdgesOf(node);
    for (DefaultEdge edge : outgoingEdges) {
        int outNode = categoryGraph.getGraph().getEdgeTarget(edge);
        if (colorMap.get(outNode).equals(Color.grey)) {
            return edge;
        }
        else if (colorMap.get(outNode).equals(Color.white)) {
            DefaultEdge e = visit(outNode);
            if (e != null) {
                return e;
            }
        }
    }
    colorMap.put(node, Color.black);
    return null;
}
 
Example #14
Source File: ExactPricingProblemSolver.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Build the MIP model. Essentially this model calculates maximum weight independent sets.
 */
private void buildModel(){
    try {
        cplex=new IloCplex();
        cplex.setParam(IloCplex.IntParam.AdvInd, 0);
        cplex.setParam(IloCplex.IntParam.Threads, 1);
        cplex.setOut(null);

        //Create the variables (a single variable per edge)
        vars=cplex.boolVarArray(dataModel.getNrVertices());

        //Create the objective function
        obj=cplex.addMaximize();

        //Create the constraints z_i+z_j <= 1 for all (i,j)\in E:
        for(DefaultEdge edge : dataModel.edgeSet())
            cplex.addLe(cplex.sum(vars[dataModel.getEdgeSource(edge)], vars[dataModel.getEdgeTarget(edge)]), 1);

        branchingConstraints=new HashMap<>();
    } catch (IloException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private void addVerticesForRelationalAtom(IFormulaAtom atom, UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph, Map<FormulaVariable, FormulaGraphVertex> vertexMap) {
    RelationalAtom relationalAtom = (RelationalAtom) atom;
    FormulaGraphVertex atomVertex = new FormulaGraphVertex(relationalAtom);
    graph.addVertex(atomVertex);
    for (FormulaAttribute formulaAttribute : relationalAtom.getAttributes()) {
        if (formulaAttribute.getValue().isVariable()) {
            String variableId = ((FormulaVariableOccurrence) formulaAttribute.getValue()).getVariableId();
            FormulaVariable variable = AlgebraUtility.findVariable(variableId, new ArrayList<FormulaVariable>(vertexMap.keySet()));
            FormulaGraphVertex variableVertex = vertexMap.get(variable);
            assert (variableVertex != null) : "Unable to find vertex for variable " + variableId;
            graph.addEdge(atomVertex, variableVertex);
        } else if (formulaAttribute.getValue().isConstant() || formulaAttribute.getValue().isNull()) {
            createConstantVertex(formulaAttribute.getValue().toString(), atomVertex, graph);
        } else if (formulaAttribute.getValue().isExpression()) {
            throw new UnsupportedOperationException("Unable to check symmetry with expression");
        }
    }
}
 
Example #16
Source File: ResourceTypeManager.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
/**
 * Adds the given types to the manager, building a graph to represent the type hierarchy.
 *
 * @param resourceTypeSetMap a full set of types, must be immutable
 * @param setsToUse optional set of type names that the manager to care about - it will ignore others it finds. If
 *            null, then the full set is used (by "full set" it means the resourceTypeSetMap param).
 * @throws IllegalStateException if types are missing (e.g. a type needs a parent but the parent is missing)
 */
public ResourceTypeManager(Map<Name, TypeSet<ResourceType<L>>> resourceTypeSetMap, Collection<Name> setsToUse)
        throws IllegalStateException {
    // If setsToUse is null, that means we need to use all the ones in the incoming map.
    // If setsToUse is not null, just use those named sets and ignore the others.
    if (setsToUse == null) {
        this.typeSetMap = resourceTypeSetMap;
    } else {
        Map<Name, TypeSet<ResourceType<L>>> m = new HashMap<>();
        for (Name setToUse : setsToUse) {
            if (resourceTypeSetMap.containsKey(setToUse)) {
                m.put(setToUse, resourceTypeSetMap.get(setToUse));
            }
        }
        this.typeSetMap = Collections.unmodifiableMap(m);
    }

    this.resourceTypesGraph = new ListenableDirectedGraph<>(DefaultEdge.class);
    this.index = new DirectedNeighborIndex<>(this.resourceTypesGraph);
    this.resourceTypesGraph.addGraphListener(index);

    prepareGraph();
}
 
Example #17
Source File: ComputeInstanceSimilarityBlock.java    From BART with MIT License 5 votes vote down vote up
private void addInstance(List<TupleWithTable> tuples, UndirectedGraph<TupleWithTable, DefaultEdge> instancesGraph) {
    Map<IValue, Set<TupleWithTable>> placeholdersInverseMap = new HashMap<>();
    for (TupleWithTable tuple : tuples) {
        instancesGraph.addVertex(tuple);
        addPlaceholders(tuple, placeholdersInverseMap);
    }
    for (IValue placeholder : placeholdersInverseMap.keySet()) {
        Set<TupleWithTable> tuplesWithPlaceholder = placeholdersInverseMap.get(placeholder);
        addEdgesBtwTuples(tuplesWithPlaceholder, instancesGraph);
    }
}
 
Example #18
Source File: ComputeInstanceSimilarityBlock.java    From BART with MIT License 5 votes vote down vote up
private void findCompatibileTuples(List<TupleWithTable> srcTuples, List<TupleWithTable> destTuples, UndirectedGraph<TupleWithTable, DefaultEdge> instancesGraph) {
    SignatureMapCollection srcSignatureMap = signatureGenerator.generateIndexForTuples(srcTuples);
    for (TupleWithTable destTuple : destTuples) {
        if (logger.isDebugEnabled()) logger.debug("Finding a tuple that can be mapped in " + destTuple);
        List<SignatureAttributes> signatureAttributesForTable = srcSignatureMap.getRankedAttributesForTable(destTuple.getTable());
        if (logger.isDebugEnabled()) logger.debug("Signature for table " + destTuple.getTable() + ": " + signatureAttributesForTable);
        List<TupleMatch> matchingTuples = findMatchingTuples(destTuple, signatureAttributesForTable, srcSignatureMap);
        if (logger.isDebugEnabled()) logger.debug("Possible matching tuples: " + matchingTuples);
        addEdgesBtwMatchingTuples(matchingTuples, instancesGraph);
    }
}
 
Example #19
Source File: WorkflowGraphBuilderTest.java    From arbiter with Apache License 2.0 5 votes vote down vote up
private Set<String> getEdges(final DirectedAcyclicGraph<Action, DefaultEdge> graph) {
    return Sets.newHashSet(Collections2.transform(graph.edgeSet(), new Function<DefaultEdge, String>() {
        @Override
        public String apply(DefaultEdge input) {
            return String.format("%s:%s", graph.getEdgeSource(input).getName(), graph.getEdgeTarget(input).getName());
        }
    }));
}
 
Example #20
Source File: OozieWorkflowGenerator.java    From arbiter with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the first action in the graph of a given type
 * This is intended for use when only one action of the given type exists
 * If more than one exists the traversal order and thus the resulting action is not guaranteed
 *
 * @param workflowGraph The graph in which to find the action
 * @param type The type of action to find
 * @return The action of the given type, or null if none exists
 */
private Action getActionByType(DirectedAcyclicGraph<Action, DefaultEdge> workflowGraph, final String type) {
    List<Action> actionList = Lists.newArrayList(Collections2.filter(workflowGraph.vertexSet(), new Predicate<Action>() {
        @Override
        public boolean apply(Action input) {
            return input.getType().equals(type);
        }
    }));
    if (actionList.size() > 0) {
        return actionList.get(0);
    } else {
        return null;
    }
}
 
Example #21
Source File: GenerateStratification.java    From BART with MIT License 5 votes vote down vote up
public DependencyStratification generate(List<Dependency> dependencies, EGTask task) {
    Map<Dependency, Set<AttributeRef>> affectedAttributes = findAllAffectedAttributes(dependencies, task);
    if (logger.isDebugEnabled()) logger.debug("Affected attributes: " + SpeedyUtility.printMap(affectedAttributes));
    Map<Dependency, Set<AttributeRef>> queriedAttributes = findAllQueriedAttributes(dependencies, task);
    if (logger.isDebugEnabled()) logger.debug("Queried attributes: " + SpeedyUtility.printMap(queriedAttributes));
    DirectedGraph<Dependency, DefaultEdge> dependencyGraph = initDependencyGraph(dependencies, affectedAttributes, queriedAttributes);
    if (logger.isDebugEnabled()) logger.debug("Dependency graph: \n" + dependencyGraph);
    StrongConnectivityInspector<Dependency, DefaultEdge> connectivityInstector = new StrongConnectivityInspector<Dependency, DefaultEdge>(dependencyGraph);
    List<Set<Dependency>> strata = connectivityInstector.stronglyConnectedSets();
    Collections.sort(strata, new StratumComparator(dependencyGraph));
    return new DependencyStratification(strata);
}
 
Example #22
Source File: ResourceManager.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an immutable {@link List} of all {@link Resource}s contained in {@link #resourcesGraph} in breadth-first
 * order.
 *
 * @return the list of all {@link Resource}s
 */
public List<Resource<L>> getResourcesBreadthFirst() {
    graphLockRead.lock();
    try {
        List<Resource<L>> result = new ArrayList<Resource<L>>();

        Set<Resource<L>> roots = getRootResources();
        if (roots.isEmpty()) {
            return Collections.emptyList();
        }

        // loop over each root resource and traverse their tree hierarchy breadth-first
        // roots.forEach(root -> new BreadthFirstIterator<>(ResourceManager.this.resourcesGraph, root)
        //     .forEachRemaining(it -> result.add(it)));
        for (Resource<L> root : roots) {
            GraphIterator<Resource<L>, DefaultEdge> it = new BreadthFirstIterator<Resource<L>, DefaultEdge>(
                    ResourceManager.this.resourcesGraph, root);
            while (it.hasNext()) {
                result.add(it.next());
            }
        }

        return Collections.unmodifiableList(result);
    } finally {
        graphLockRead.unlock();
    }
}
 
Example #23
Source File: OozieWorkflowGenerator.java    From arbiter with Apache License 2.0 5 votes vote down vote up
/**
 * Add the XML element for an action
 *
 * @param action The action for which to add the element
 * @param workflowGraph The full workflow graph
 * @param transition The OK transition for this action
 * @param errorTransition The error transition for this action if it is not inside a fork/join pair
 * @param directives The Xembly Directives object to which to add the new XML elements
 */
private void createActionElement(Action action, DirectedAcyclicGraph<Action, DefaultEdge> workflowGraph, Action transition, Action errorTransition, Directives directives) {
    ActionType type = getActionType(action.getType());

    directives.add("action")
            .attr("name", action.getName())
            .add(type.getTag());

    if (type.getXmlns() != null) {
        directives.attr("xmlns", type.getXmlns());
    }

    // There is an outer action tag and an inner tag corresponding to the action type
    Map<String, List<String>> interpolated = NamedArgumentInterpolator.interpolate(type.getDefaultArgs(), action.getNamedArgs(), type.getDefaultInterpolations(), action.getPositionalArgs());
    Map<String, String> mergedConfigurationProperties = new HashMap<>(type.getProperties());
    if (action.getConfigurationProperties() != null) {
        mergedConfigurationProperties.putAll(action.getConfigurationProperties());
    }
    addInnerActionElements(mergedConfigurationProperties, type.getConfigurationPosition(), directives, interpolated, action.getPositionalArgs());
    directives.up();

    String okTransitionName = action.getForceOk() != null ? action.getForceOk() : transition.getName();
    directives.add("ok")
            .attr("to", okTransitionName)
            .up();

    // We allow forcing a particular error transition regardless of other considerations
    String interpolatedForceError = NamedArgumentInterpolator.interpolate(action.getForceError(), ImmutableMap.of("okTransition", okTransitionName), type.getDefaultInterpolations());
    String errorTransitionName = interpolatedForceError != null ? interpolatedForceError : errorTransition.getName();
    // Find the enclosing fork/join pair
    // If an action is inside a fork/join, it should transition to the join on error
    String enclosingJoinName = getEnclosingForkJoinName(action, workflowGraph);
    if (enclosingJoinName != null) {
        errorTransitionName = interpolatedForceError != null ? interpolatedForceError : enclosingJoinName;
    }
    directives.add("error")
            .attr("to", errorTransitionName)
            .up();
}
 
Example #24
Source File: WorkflowGraphBuilder.java    From arbiter with Apache License 2.0 5 votes vote down vote up
/**
 * Create a fork/join pair and add it to a graph
 *
 * @param parentGraph The graph to which to add the fork/join actions
 * @return A Pair of actions. The left action is the fork and the right action is the join
 */
private static Pair<Action, Action> addForkJoin(DirectedAcyclicGraph<Action, DefaultEdge> parentGraph) {
    Action fork = new Action();
    fork.setName("fork-" + forkCount);
    fork.setType("fork");

    Action join = new Action();
    join.setName("join-" + forkCount);
    join.setType("join");
    forkCount++;
    parentGraph.addVertex(fork);
    parentGraph.addVertex(join);

    return Pair.of(fork, join);
}
 
Example #25
Source File: GraphSerialization.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the given {@link DirectedGraph} object to the given location.
 * 
 * @param graph Must not be {@code null}.
 * @param location Must not be {@code null} and a valid file path.
 * @throws IOException Thrown if errors occurred on the IO level.
 */
public static void saveGraph(DirectedGraph<Integer, DefaultEdge> graph, String location) throws IOException {
	File file = new File(location);
	file.createNewFile();
	if (!file.canWrite()) {
		throw new IOException("Cannot write to file " + location);
	}
	GraphSerialization.saveGraph(graph, file);
}
 
Example #26
Source File: GenerateFormulaWithAdornments.java    From BART with MIT License 5 votes vote down vote up
private UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> chooseSubgraphWithNoVirtualVertices(UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne, UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphTwo) {
    if (hasNoVirtual(connectedSubgraphOne)) {
        return connectedSubgraphOne;
    } else if (hasNoVirtual(connectedSubgraphTwo)) {
        return connectedSubgraphTwo;
    }
    return null;
}
 
Example #27
Source File: GenerateFormulaWithAdornments.java    From BART with MIT License 5 votes vote down vote up
private boolean hasNoVirtual(UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne) {
    for (FormulaGraphVertex formulaGraphVertex : connectedSubgraphOne.vertexSet()) {
        if (formulaGraphVertex.isVirtual()) {
            return false;
        }
    }
    return true;
}
 
Example #28
Source File: GenerateFormulaWithAdornments.java    From BART with MIT License 5 votes vote down vote up
private List<IFormulaAtom> extractFormulaAtoms(UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraph) {
    List<IFormulaAtom> result = new ArrayList<IFormulaAtom>();
    for (FormulaGraphVertex formulaGraphVertex : connectedSubgraph.vertexSet()) {
        if (formulaGraphVertex.isAtom()) {
            result.add(formulaGraphVertex.getAtom());
        }
    }
    return result;
}
 
Example #29
Source File: CategoryGraph.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * Get the neighbors of a given node.
 * The category graph is treated as an undirected graph.
 * @param node the reference node.
 * @return The set of category nodes that are neighbors of this category.
 */
protected Set<Integer> getNeighbors(int node) {

    Set<Integer> neighbors = new HashSet<Integer>();
    Set<DefaultEdge> edges = undirectedGraph.edgesOf(node);
    for (DefaultEdge edge : edges) {
        if (undirectedGraph.getEdgeSource(edge) != node) {
            neighbors.add(undirectedGraph.getEdgeSource(edge));
        }
        if (undirectedGraph.getEdgeTarget(edge) != node) {
            neighbors.add(undirectedGraph.getEdgeTarget(edge));
        }
    }
    return neighbors;
}
 
Example #30
Source File: WorkflowGraphBuilderTest.java    From arbiter with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoDependencies() throws WorkflowGraphException {
    DirectedAcyclicGraph<Action, DefaultEdge> graph = WorkflowGraphBuilder.buildWorkflowGraph(workflow, config, null, false, null);
    Set<String> expectedVertices = Sets.newHashSet("a1", "a2", "a3", "start", "end", "kill", "fork-0", "join-0");
    Set<String> expectedEdges = Sets.newHashSet("a3:join-0", "join-0:end", "a1:join-0", "fork-0:a2", "fork-0:a1", "a2:join-0", "fork-0:a3", "start:fork-0");
    assertEquals(expectedVertices, getVertices(graph));
    assertEquals(expectedEdges, getEdges(graph));
}