Search in sources :

Example 11 with DefaultEdge

use of org.jgrapht.graph.DefaultEdge in project evosuite by EvoSuite.

the class RegexDistanceUtils method cacheRegex.

private static void cacheRegex(String regex) {
    String r = expandRegex(regex);
    Automaton automaton = new RegExp(r, RegExp.NONE).toAutomaton();
    automaton.expandSingleton();
    // We convert this to a graph without self-loops in order to determine the topological order
    DirectedGraph<State, DefaultEdge> regexGraph = new DefaultDirectedGraph<State, DefaultEdge>(DefaultEdge.class);
    Set<State> visitedStates = new HashSet<State>();
    Queue<State> states = new LinkedList<State>();
    State initialState = automaton.getInitialState();
    states.add(initialState);
    while (!states.isEmpty()) {
        State currentState = states.poll();
        if (visitedStates.contains(currentState))
            continue;
        if (!regexGraph.containsVertex(currentState))
            regexGraph.addVertex(currentState);
        for (Transition t : currentState.getTransitions()) {
            // Need to get rid of back edges, otherwise there is no topological order!
            if (!t.getDest().equals(currentState)) {
                regexGraph.addVertex(t.getDest());
                regexGraph.addEdge(currentState, t.getDest());
                states.add(t.getDest());
                CycleDetector<State, DefaultEdge> det = new CycleDetector<State, DefaultEdge>(regexGraph);
                if (det.detectCycles()) {
                    regexGraph.removeEdge(currentState, t.getDest());
                }
            }
        }
        visitedStates.add(currentState);
    }
    TopologicalOrderIterator<State, DefaultEdge> iterator = new TopologicalOrderIterator<State, DefaultEdge>(regexGraph);
    List<State> topologicalOrder = new ArrayList<State>();
    while (iterator.hasNext()) {
        topologicalOrder.add(iterator.next());
    }
    regexStateCache.put(regex, topologicalOrder);
    regexAutomatonCache.put(regex, automaton);
}
Also used : Automaton(dk.brics.automaton.Automaton) RegExp(dk.brics.automaton.RegExp) DefaultDirectedGraph(org.jgrapht.graph.DefaultDirectedGraph) ArrayList(java.util.ArrayList) DefaultEdge(org.jgrapht.graph.DefaultEdge) TopologicalOrderIterator(org.jgrapht.traverse.TopologicalOrderIterator) LinkedList(java.util.LinkedList) CycleDetector(org.jgrapht.alg.CycleDetector) State(dk.brics.automaton.State) Transition(dk.brics.automaton.Transition) HashSet(java.util.HashSet)

Example 12 with DefaultEdge

use of org.jgrapht.graph.DefaultEdge in project bmoth by hhu-stups.

the class ExplicitStateModelChecker method labelStateSpace.

private void labelStateSpace() {
    Queue<State> statesToUpdate = new ArrayDeque<>();
    statesToUpdate.addAll(stateSpace.vertexSet());
    while (!statesToUpdate.isEmpty()) {
        State current = statesToUpdate.poll();
        final Set<BuechiAutomatonNode> buechiNodes = new HashSet<>();
        final Set<BuechiAutomatonNode> candidates = new HashSet<>();
        if (stateSpace.rootVertexSet().contains(current)) {
            candidates.addAll(buechiAutomaton.getInitialStates());
        } else {
            Set<DefaultEdge> incomingEdges = stateSpace.incomingEdgesOf(current);
            for (DefaultEdge incomingEdge : incomingEdges) {
                State predecessor = stateSpace.getEdgeSource(incomingEdge);
                predecessor.getBuechiNodes().forEach(n -> candidates.addAll(n.getSuccessors()));
            }
        }
        for (BuechiAutomatonNode node : candidates) {
            if (node.getLabels().isEmpty()) {
                buechiNodes.add(node);
            }
            // TODO use all labels?
            for (PredicateNode label : node.getLabels()) {
                labelSolver.reset();
                labelSolver.add(FormulaToZ3Translator.translatePredicate(label, getContext(), getMachineTranslator().getZ3TypeInference()));
                labelSolver.add(current.getStateConstraint(getContext()));
                Status status = labelSolver.check();
                switch(status) {
                    case UNSATISFIABLE:
                        break;
                    case UNKNOWN:
                        throw new UnsupportedOperationException("should not be undefined");
                    case SATISFIABLE:
                        buechiNodes.add(node);
                }
            }
        }
        buechiNodes.stream().filter(n -> !current.getBuechiNodes().contains(n)).forEach(newBuechiNode -> {
            // found a new node, need to update successors again
            current.addBuechiNode(newBuechiNode);
            Set<DefaultEdge> outgoingEdges = stateSpace.outgoingEdgesOf(current);
            for (DefaultEdge outgoingEdge : outgoingEdges) {
                State successor = stateSpace.getEdgeTarget(outgoingEdge);
                if (!statesToUpdate.contains(successor)) {
                    statesToUpdate.add(successor);
                }
            }
        });
    }
}
Also used : Status(com.microsoft.z3.Status) Z3SolverFactory(de.bmoth.backend.z3.Z3SolverFactory) de.bmoth.modelchecker(de.bmoth.modelchecker) java.util(java.util) FormulaToZ3Translator(de.bmoth.backend.z3.FormulaToZ3Translator) DefaultEdge(org.jgrapht.graph.DefaultEdge) Solver(com.microsoft.z3.Solver) MachineNode(de.bmoth.parser.ast.nodes.MachineNode) SolutionFinder(de.bmoth.backend.z3.SolutionFinder) ModelCheckingResult(de.bmoth.modelchecker.ModelCheckingResult) NOT(de.bmoth.parser.ast.nodes.ltl.LTLPrefixOperatorNode.Kind.NOT) TarjanSimpleCycles(org.jgrapht.alg.cycle.TarjanSimpleCycles) Model(com.microsoft.z3.Model) PredicateNode(de.bmoth.parser.ast.nodes.PredicateNode) de.bmoth.parser.ast.nodes.ltl(de.bmoth.parser.ast.nodes.ltl) BoolExpr(com.microsoft.z3.BoolExpr) LTLTransformations(de.bmoth.backend.ltl.LTLTransformations) Status(com.microsoft.z3.Status) TranslationOptions(de.bmoth.backend.TranslationOptions) BMothPreferences(de.bmoth.preferences.BMothPreferences) PredicateNode(de.bmoth.parser.ast.nodes.PredicateNode) DefaultEdge(org.jgrapht.graph.DefaultEdge)

Example 13 with DefaultEdge

use of org.jgrapht.graph.DefaultEdge in project Smack by igniterealtime.

the class ModularXmppClientToServerConnectionStateGraphTest method testStateGraphDotOutput.

@Test
public void testStateGraphDotOutput() throws IOException, ImportException {
    URL stateGraphDotFileUrl = Resources.getResource("state-graph.dot");
    String expectedStateGraphDot = Resources.toString(stateGraphDotFileUrl, StandardCharsets.UTF_8);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ModularXmppClientToServerConnectionTool.printStateGraph(pw, false);
    String currentStateGraphDot = sw.toString();
    @SuppressWarnings("serial") DOTImporter<String, DefaultEdge> dotImporter = new DOTImporter<>((id, attributes) -> id, (from, to, label, attributes) -> {
        return new DefaultEdge() {

            @Override
            public int hashCode() {
                return HashCode.builder().append(getSource()).append(getTarget()).build();
            }

            @Override
            public boolean equals(Object other) {
                return EqualsUtil.equals(this, other, (b, o) -> b.append(getSource(), o.getSource()).append(getTarget(), o.getTarget()));
            }
        };
    });
    DirectedPseudograph<String, DefaultEdge> currentStateGraph = new DirectedPseudograph<>(DefaultEdge.class);
    DirectedPseudograph<String, DefaultEdge> expectedStateGraph = new DirectedPseudograph<>(DefaultEdge.class);
    dotImporter.importGraph(expectedStateGraph, new StringReader(expectedStateGraphDot));
    dotImporter.importGraph(currentStateGraph, new StringReader(currentStateGraphDot));
    assertEquals(expectedStateGraph, currentStateGraph);
}
Also used : DOTImporter(org.jgrapht.io.DOTImporter) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) DefaultEdge(org.jgrapht.graph.DefaultEdge) DirectedPseudograph(org.jgrapht.graph.DirectedPseudograph) URL(java.net.URL) PrintWriter(java.io.PrintWriter) Test(org.junit.jupiter.api.Test)

Example 14 with DefaultEdge

use of org.jgrapht.graph.DefaultEdge in project symja_android_library by axkr.

the class Export method evaluate.

@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
    if (Config.isFileSystemEnabled(engine)) {
        if (!(ast.arg1() instanceof IStringX)) {
            return F.NIL;
        }
        IStringX arg1 = (IStringX) ast.arg1();
        Extension format = Extension.exportFilename(arg1.toString());
        if (ast.size() == 4) {
            if (!(ast.arg3() instanceof IStringX)) {
                return F.NIL;
            }
            // format = ((IStringX) ast.arg3()).toString();
            format = Extension.exportExtension(((IStringX) ast.arg3()).toString());
        }
        IExpr arg2 = ast.arg2();
        try (FileWriter writer = new FileWriter(arg1.toString())) {
            if (arg2 instanceof GraphExpr) {
                graphExport(((GraphExpr<DefaultEdge>) arg2).toData(), writer, format);
                return arg1;
            }
            if (format.equals(Extension.CSV) || format.equals(Extension.TSV)) {
                if (arg2.isDataset()) {
                    ((IASTDataset) arg2).csv(writer);
                    return arg1;
                }
            } else if (format.equals(Extension.TABLE)) {
                int[] dims = arg2.isMatrix();
                if (dims != null) {
                    for (int j = 0; j < dims[0]; j++) {
                        IAST rowList = (IAST) arg2.getAt(j + 1);
                        for (int i = 1; i <= dims[1]; i++) {
                            if (rowList.get(i).isReal()) {
                                writer.append(rowList.get(i).toString());
                            } else {
                                writer.append("\"");
                                writer.append(rowList.get(i).toString());
                                writer.append("\"");
                            }
                            if (i < dims[1]) {
                                writer.append(" ");
                            }
                        }
                        writer.append("\n");
                    }
                    return arg1;
                } else {
                    if (arg2.isList()) {
                    }
                }
            } else if (format.equals(Extension.DAT)) {
                File file = new File(arg1.toString());
                com.google.common.io.Files.write(arg2.toString(), file, Charset.defaultCharset());
                return arg1;
            } else if (format.equals(Extension.WXF)) {
                File file = new File(arg1.toString());
                byte[] bArray = WL.serialize(arg2);
                com.google.common.io.Files.write(bArray, file);
                return arg1;
            }
        } catch (IOException ioe) {
            LOGGER.log(engine.getLogLevel(), "Export: file {} not found!", arg1, ioe);
        } catch (Exception ex) {
            LOGGER.log(engine.getLogLevel(), "Export: file {}", arg1, ex);
        }
    }
    return F.NIL;
}
Also used : Extension(org.matheclipse.core.io.Extension) IASTDataset(org.matheclipse.core.interfaces.IASTDataset) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) FileWriter(java.io.FileWriter) DefaultEdge(org.jgrapht.graph.DefaultEdge) IStringX(org.matheclipse.core.interfaces.IStringX) IExpr(org.matheclipse.core.interfaces.IExpr) IAST(org.matheclipse.core.interfaces.IAST) IOException(java.io.IOException) File(java.io.File) ExportException(org.jgrapht.nio.ExportException) IOException(java.io.IOException)

Example 15 with DefaultEdge

use of org.jgrapht.graph.DefaultEdge in project symja_android_library by axkr.

the class ExportString method evaluate.

@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
    IExpr arg1 = ast.arg1();
    if (!(ast.arg2() instanceof IStringX)) {
        return F.NIL;
    }
    Extension format = Extension.exportExtension(((IStringX) ast.arg2()).toString());
    try (StringWriter writer = new StringWriter()) {
        if (format.equals(Extension.EXPRESSIONJSON)) {
            if (arg1.isNumber() || arg1.isSymbol()) {
                return F.stringx(arg1.toString());
            } else if (arg1.isString()) {
                return F.stringx("'" + arg1.toString() + "'");
            }
            return ExpressionJSONConvert.exportExpressionJSONIStringX(arg1);
        }
        if (arg1 instanceof GraphExpr) {
            graphExport(((GraphExpr<DefaultEdge>) arg1).toData(), writer, format);
            return F.stringx(writer.toString());
        }
        if (format.equals(Extension.CSV) || format.equals(Extension.TSV)) {
            if (arg1.isDataset()) {
                ((IASTDataset) arg1).csv(writer);
                return F.stringx(writer.toString());
            }
        } else if (format.equals(Extension.TABLE)) {
            int[] dims = arg1.isMatrix();
            if (dims != null) {
                for (int j = 0; j < dims[0]; j++) {
                    IAST rowList = (IAST) arg1.getAt(j + 1);
                    for (int i = 1; i <= dims[1]; i++) {
                        if (rowList.get(i).isReal()) {
                            writer.append(rowList.get(i).toString());
                        } else {
                            writer.append("\"");
                            writer.append(rowList.get(i).toString());
                            writer.append("\"");
                        }
                        if (i < dims[1]) {
                            writer.append(" ");
                        }
                    }
                    writer.append("\n");
                }
                return F.stringx(writer.toString());
            } else {
                if (arg1.isList()) {
                }
            }
        // } else if (format.equals(Extension.DAT)) {
        // File file = new File(arg1.toString());
        // com.google.common.io.Files.write(arg2.toString(), file, Charset.defaultCharset());
        // return arg1;
        // } else if (format.equals(Extension.WXF)) {
        // File file = new File(arg1.toString());
        // byte[] bArray = WL.serialize(arg2);
        // com.google.common.io.Files.write(bArray, file);
        // return arg1;
        }
    // } catch (IOException ioe) {
    // return engine.printMessage("ExportString: " + arg1.toString() + " not found!");
    } catch (Exception ex) {
        LOGGER.log(engine.getLogLevel(), "format: {}", arg1, ex);
        return F.NIL;
    }
    return F.NIL;
}
Also used : Extension(org.matheclipse.core.io.Extension) IASTDataset(org.matheclipse.core.interfaces.IASTDataset) StringWriter(java.io.StringWriter) GraphExpr(org.matheclipse.core.expression.data.GraphExpr) DefaultEdge(org.jgrapht.graph.DefaultEdge) IExpr(org.matheclipse.core.interfaces.IExpr) IStringX(org.matheclipse.core.interfaces.IStringX) IAST(org.matheclipse.core.interfaces.IAST) ExportException(org.jgrapht.nio.ExportException)

Aggregations

DefaultEdge (org.jgrapht.graph.DefaultEdge)26 ClassInfo (com.jopdesign.common.ClassInfo)8 HashMap (java.util.HashMap)7 HashSet (java.util.HashSet)6 Set (java.util.Set)5 DefaultDirectedGraph (org.jgrapht.graph.DefaultDirectedGraph)5 BitSet (java.util.BitSet)4 FileWriter (java.io.FileWriter)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 TopologicalOrderIterator (org.jgrapht.traverse.TopologicalOrderIterator)3 File (java.io.File)2 StringWriter (java.io.StringWriter)2 LinkedList (java.util.LinkedList)2 TreeSet (java.util.TreeSet)2 ExportException (org.jgrapht.nio.ExportException)2 GraphExpr (org.matheclipse.core.expression.data.GraphExpr)2 IAST (org.matheclipse.core.interfaces.IAST)2 IASTDataset (org.matheclipse.core.interfaces.IASTDataset)2 IExpr (org.matheclipse.core.interfaces.IExpr)2