public void DoUndo(IGraphProcessingEnvironment procEnv) { LGSPGraphProcessingEnvironment procEnv_ = (LGSPGraphProcessingEnvironment)procEnv; if (procEnv.Graph is LGSPNamedGraph) { if (_elem is LGSPNode) { ((LGSPNamedGraph)procEnv_.graph).AddNode((LGSPNode)_elem, _name); } else { ((LGSPNamedGraph)procEnv_.graph).AddEdge((LGSPEdge)_elem, _name); } } else { if (_elem is LGSPNode) { procEnv_.graph.AddNode((LGSPNode)_elem); } else { procEnv_.graph.AddEdge((LGSPEdge)_elem); } } if (_vars != null) { foreach (Variable var in _vars) { procEnv_.SetVariableValue(var.Name, _elem); } } }
private void ChangingElementAttribute(LGSPGraphProcessingEnvironment procEnv) { AttributeChangeType changeType; switch (_undoOperation) { case UndoOperation.Assign: changeType = AttributeChangeType.Assign; break; case UndoOperation.PutElement: changeType = AttributeChangeType.PutElement; break; case UndoOperation.RemoveElement: changeType = AttributeChangeType.RemoveElement; break; case UndoOperation.AssignElement: changeType = AttributeChangeType.AssignElement; break; default: throw new Exception("Internal error during transaction handling"); } LGSPNode node = _elem as LGSPNode; if (node != null) { procEnv.graph.ChangingNodeAttribute(node, _attrType, changeType, _value, _keyOfValue); } else { LGSPEdge edge = (LGSPEdge)_elem; procEnv.graph.ChangingEdgeAttribute(edge, _attrType, changeType, _value, _keyOfValue); } }
public static void Filter_TransformSingle_orderAscendingBy_order(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <na.Rule_TransformSingle.IMatch_TransformSingle> matches) { List <na.Rule_TransformSingle.IMatch_TransformSingle> matchesArray = matches.ToList(); matchesArray.Sort(new Comparer_TransformSingle_orderAscendingBy_order()); matches.FromList(); }
void DoIt() { graph = new LGSPGraph(new ProgramGraphsOriginalGraphModel()); actions = new ProgramGraphsOriginalActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // use new exact 2.5 interface IClass cls = null; IMethodBody mb = null; bool success = actions.createProgramGraphPullUp.Apply(procEnv, ref cls, ref mb); IMatchesExact<Rule_pullUpMethod.IMatch_pullUpMethod> matchesExact = actions.pullUpMethod.Match(procEnv, 0, cls, mb); Console.WriteLine(matchesExact.Count + " matches found."); Console.WriteLine(matchesExact.FirstExact.node_m5.ToString()); graph.Clear(); // and again with old inexact interface IMatches matchesInexact; object[] returns; Action_createProgramGraphPullUp createProgramGraph = Action_createProgramGraphPullUp.Instance; matchesInexact = createProgramGraph.Match(procEnv, 0); returns = createProgramGraph.Modify(procEnv, matchesInexact.First); IGraphElement[] param = new LGSPNode[2]; param[0] = (Class)returns[0]; param[1] = (MethodBody)returns[1]; matchesInexact = actions.GetAction("pullUpMethod").Match(procEnv, 0, param); Console.WriteLine(matchesInexact.Count + " matches found."); Console.WriteLine(matchesInexact.First.getNodeAt((int)Rule_pullUpMethod.pullUpMethod_NodeNums.m5).ToString()); }
public static void Filter_filterBass_auto(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <Rule_filterBass.IMatch_filterBass> matches) { if (matches.Count < 2) { return; } List <Rule_filterBass.IMatch_filterBass> matchesArray = matches.ToList(); for (int i = 0; i < matchesArray.Count; ++i) { if (matchesArray[i] == null) { continue; } for (int j = i + 1; j < matchesArray.Count; ++j) { if (matchesArray[j] == null) { continue; } if (GRGEN_LIBGR.SymmetryChecker.AreSymmetric(matchesArray[i], matchesArray[j], procEnv.graph)) { matchesArray[j] = null; } } } matches.FromList(); }
void DoIdpt() { graph = new LGSPGraph(new IndependentGraphModel()); actions = new IndependentActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); procEnv.ApplyGraphRewriteSequence("create"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); IMatches matches = actions.GetAction("findIndependent").Match(procEnv, 0, null); Console.WriteLine(matches.Count + " matches found."); graph.Clear(); procEnv.ApplyGraphRewriteSequence("createIterated"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); IAction_createIterated createIterated = actions.createIterated; IMatchesExact<Rule_createIterated.IMatch_createIterated> matchesCreateIterated = createIterated.Match(procEnv, 0); IintNode beg; INode end; createIterated.Modify(procEnv, matchesCreateIterated.FirstExact, out beg, out end); IMatchesExact<Rule_findChainPlusChainToIntIndependent.IMatch_findChainPlusChainToIntIndependent> matchesFindChain = actions.findChainPlusChainToIntIndependent.Match(procEnv, 0, beg, end); Console.WriteLine(matchesFindChain.Count + " matches found."); }
public static IList <GRGEN_LIBGR.IMatch> Filter_extshf(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, IList <GRGEN_LIBGR.IMatch> matches, System.Int32 f) { List <IMatch_shared> matchesArray = GRGEN_LIBGR.MatchListHelper.ToList <IMatch_shared>(matches); // some code, may set elements in matchesArray to null, they are then skipped when re-building matches in FromList GRGEN_LIBGR.MatchListHelper.FromList(matches, matchesArray); return(matches); }
public LGSPTransactionManager(LGSPGraphProcessingEnvironment procEnv) { this.procEnv = procEnv; #if LOG_TRANSACTION_HANDLING writer = new StreamWriter(procEnv.graph.Name + "_transaction_log.txt"); #endif }
public LGSPTransactionManager(LGSPGraphProcessingEnvironment procEnv) { this.procEnv = procEnv; #if LOG_TRANSACTION_HANDLING writer = new System.IO.StreamWriter(procEnv.graph.Name + "_transaction_log.txt"); #endif }
public static bool ApplyXGRS_createEdge(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.INode var_n1, GRGEN_LIBGR.INode var_n2, ref GRGEN_LIBGR.IEdge var_e) { // it is recommended to create an edge as in the function below, immediately adding it to the graph // then you must work with LGSPNodes, casting the INodes you receive as parameters to that concrete type (inheriting from INode) var_e = GRGEN_MODEL.E.TypeInstance.CreateEdge(var_n1, var_n2); procEnv.graph.AddEdge(var_e); return(true); }
public void ExecuteDeferredSequencesThenExitRuleModify(LGSPGraphProcessingEnvironment procEnv) { while (toBeExecuted.Peek().Count > 0) { toBeExecuted.Peek().Dequeue().exec(procEnv); } toBeExecuted.Pop(); }
public static bool ApplyXGRS_foo(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, int var_v1, double var_v2, GRGEN_MODEL.ENUM_Enu var_v3, string var_v4, bool var_v5, ref int var_r1, ref double var_r2, ref GRGEN_MODEL.ENUM_Enu var_r3, ref string var_r4, ref bool var_r5) { var_r1 = var_v1; var_r2 = var_v2; var_r3 = var_v3; var_r4 = var_v4; var_r5 = var_v5; return(true); }
static void Main(string[] args) { complModelNamedGraph graph = new complModelNamedGraph(); graph.ReuseOptimization = false; LGSPActions actions = new testActions(graph); LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions); /* Node_Process p1 = Node_Process.CreateNode(graph); p1.name = "Siegfried"; p1.val = 67; LGSPNode p2 = graph.AddNode(NodeType_Process.typeVar); p2.SetAttribute("name", "Dieter"); if((int) p2.GetAttribute("val") == 0) p2.SetAttribute("val", 9); // INode_Process p1_attr = (INode_Process) p1.attributes; // p1_attr.name = "Siegfried"; // p1_attr.val = 67; Edge_connection con = (Edge_connection) graph.AddEdge(EdgeType_connection.typeVar, p1, p2); con.bandwidth = 1000 + p1.val + p1.name.Length;*/ D231_4121 n1 = graph.CreateNodeD231_4121(); n1.a2 = 2; n1.a4 = 4; n1.a5 = 5; n1.b23 = 23; n1.b41 = 41; n1.b42 = 42; n1.d231_4121 = 231; B21 n2 = graph.CreateNodeB21(); n2.a2 = 10002; n2.b21 = 10021; D2211_2222_31 n3 = graph.CreateNodeD2211_2222_31(); n3.a2 = 20002; n3.a3 = 20003; n3.a4 = 20004; n3.b22 = 20022; n3.b41 = 20041; n3.c221 = 20221; n3.c222_411 = 20222; n3.d2211_2222_31 = 22221; graph.CreateEdgeEdge(n1, n2); graph.CreateEdgeEdge(n2, n3); Action_testRule.Instance.Apply(procEnv); using(VCGDumper dumper = new VCGDumper("test.vcg")) GraphDumper.Dump(graph, dumper); }
public readonly String _name; // for ToString only public LGSPUndoElemRetyped(IGraphElement oldElem, IGraphElement newElem, LGSPGraphProcessingEnvironment procEnv) { _oldElem = oldElem; _newElem = newElem; if (procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(newElem); } else { _name = "?"; } }
public static void Main(string[] args) { LGSPNamedGraph graph; LGSPActions actions; LGSPGraphProcessingEnvironment procEnv; try { new LGSPBackend().CreateNamedFromSpec("Mutex.grg", null, 0, out graph, out actions); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); } catch(Exception ex) { Console.WriteLine("Unable to create graph from specification: " + ex.Message); return; } DumpInfo dumpInfo = new DumpInfo(graph.GetElementName); YCompClient ycomp = YCompClient.CreateYCompClient(graph, "Organic", dumpInfo); // Let yComp observe any changes to the graph ycomp.RegisterLibGrEvents(); NodeType processType = graph.GetNodeType("Process"); EdgeType nextType = graph.GetEdgeType("next"); LGSPNode p1 = graph.AddLGSPNode(processType); LGSPNode p2 = graph.AddLGSPNode(processType); graph.AddEdge(nextType, p1, p2); graph.AddEdge(nextType, p2, p1); PrintAndWait("Initial 2-process ring constructed.", ycomp); procEnv.ApplyGraphRewriteSequence("newRule[5] && mountRule && requestRule[7]"); PrintAndWait("Initialized 7-process ring with resource and requests.", ycomp); ycomp.UnregisterLibGrEvents(); Console.WriteLine("Do many changes slowing down too much with YComp (not in this example)..."); procEnv.ApplyGraphRewriteSequence("(takeRule && releaseRule && giveRule)*"); PrintAndWait("Nothing changed so far on the display.", ycomp); ycomp.ClearGraph(); UploadGraph(graph, ycomp); PrintAndWait("Graph newly uploaded to yComp.", ycomp); ycomp.RegisterLibGrEvents(); actions.GetAction("newRule").ApplyMinMax(procEnv, 4, 4); PrintAndWait("Added 4 processes in the ring.", ycomp); ycomp.Close(); }
public readonly IGraph _graph; // for ToString only public LGSPUndoElemRemoved(IGraphElement elem, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; _vars = procEnv.GetElementVariables(_elem); if (procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); } else { _name = null; } _graph = procEnv.graph; }
public static void Filter_f3(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <Rule_filterBass.IMatch_filterBass> matches) { // inspect matches carefully and manipulate as needed, // transforming to a List<IMatch> for easier manipulation and back to an IMatchesExact if needed List <Rule_filterBass.IMatch_filterBass> matchesArray = matches.ToList(); matchesArray.Reverse(); Rule_filterBass.IMatch_filterBass match = matchesArray[matchesArray.Count - 1]; matchesArray[matchesArray.Count - 1] = null; // setting to null is an efficient way to delete, better than List.RemoveAt ++match.node_n.i; matchesArray.Add(match); matchesArray.Reverse(); matches.FromList(); }
public static void Filter_f2(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <Rule_filterBass.IMatch_filterBass> matches) { // inspect matches carefully and manipulate as needed IEnumerator <Rule_filterBass.IMatch_filterBass> e = matches.GetEnumeratorExact(); while (e.MoveNext()) { Rule_filterBass.IMatch_filterBass match = e.Current; if (match.node_n.i != 42) { break; } } }
void DoIter() { graph = new LGSPGraph(new StdGraphModel()); actions = new spanningTreeActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); IAction_initUndirected init = actions.initUndirected; IMatchesExact<Rule_initUndirected.IMatch_initUndirected> matchesInitUndirected = init.Match(procEnv, 0); INode root; init.Modify(procEnv, matchesInitUndirected.FirstExact, out root); IMatchesExact<Rule_spanningTree.IMatch_spanningTree> matchesSpanningTree = actions.spanningTree.Match(procEnv, 0, root); actions.spanningTree.Modify(procEnv, matchesSpanningTree.FirstExact); Console.WriteLine(matchesSpanningTree.Count + " matches found."); }
// Have a look at the .gm + .grg, the ExternalAttributeEvaluationModelExternalFunctions.cs, // and the ExternalAttributeEvaluationModelExternalFunctionsImpl.cs files. // They show how to declare external classes and actions in the model file, // and how to use them in the attribute calculations in the rule file. // The generated XXXExternalFunctions.cs file contains the partial classes of the data types and functions // and the manually coded XXXExternalFunctionsImpl.cs file exemplifies how to implement these external functions. void DoEAE() { graph = new ExternalAttributeEvaluationGraph(); actions = new ExternalAttributeEvaluationActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // use graph rewrite sequence procEnv.ApplyGraphRewriteSequence("init"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); // use new 2.5 exact interface IMatchesExact<Rule_r.IMatch_r> matchesExact = actions.r.Match(procEnv, 0); Console.WriteLine(matchesExact.Count + " matches found."); actions.r.Modify(procEnv, matchesExact.FirstExact); }
public static bool ApplyXGRS_huh(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv) { object x = procEnv.GetVariableValue("x"); GRGEN_LGSP.LGSPGraph graph = procEnv.graph; GRGEN_LGSP.LGSPActions actions = procEnv.curActions; object a = procEnv.GetVariableValue("a"); GRGEN_MODEL.N node_a = (GRGEN_MODEL.N)a; int val_x = (int)x; // announce change so that debugger can show new value or transaction manager can record it and roll it back graph.ChangingNodeAttribute(node_a, GRGEN_MODEL.NodeType_N.AttributeType_i, GRGEN_LIBGR.AttributeChangeType.Assign, val_x, null); node_a.i = val_x; // add reflexive edge GRGEN_MODEL.E someEdge = GRGEN_MODEL.E.CreateEdge(graph, node_a, node_a); // here you could do other nifty things like deleting nodes, retyping graph elements, or calling rules return(false); }
public static void Filter_fext(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, IList <GRGEN_LIBGR.IMatch> matches, System.Int32 f) { GRGEN_LIBGR.IGraph graph = procEnv.Graph; List <IMatch_mc> matchesExact = GRGEN_LIBGR.MatchListHelper.ToList <IMatch_mc>(matches); foreach (IMatch_mc m in matchesExact) { GRGEN_MODEL.IN n = (GRGEN_MODEL.IN)(m.node_n); m.var_idef = n.@i + f; procEnv.EmitWriter.Write("the value of variable \"n.i\" of type int is: "); procEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToStringNonNull(n.@i, graph, false, null, null)); procEnv.EmitWriter.Write("\n"); procEnv.EmitWriter.Write("the value of variable \"idef\" of type int is: "); procEnv.EmitWriter.Write(GRGEN_LIBGR.EmitHelper.ToStringNonNull(m.var_idef, graph, false, null, null)); procEnv.EmitWriter.Write("\n"); } matchesExact.RemoveRange(1, matchesExact.Count - 1); GRGEN_LIBGR.MatchListHelper.FromList(matches, matchesExact); return; }
public static void Filter_f4(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <Rule_filterHass.IMatch_filterHass> matches, System.Int32 i, System.String s) { // inspect matches carefully and manipulate as needed, depending on input parameters // transforming to a List<IMatch> for easier manipulation and back to an IMatchesExact if needed List <Rule_filterHass.IMatch_filterHass> matchesArray = matches.ToList(); for (int j = 0; j < matchesArray.Count; ++j) { Rule_filterHass.IMatch_filterHass match = matchesArray[j]; if (match.node_n.i < i) { matchesArray[j] = null; // setting to null is an efficient way to delete, better than List.RemoveAt } if (match.node_n.s != s) { match.node_n.s = s; } } matches.FromList(); }
void DoTNT() { graph = new LGSPGraph(new TNTGraphModel()); actions = new TNTActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // use graph rewrite sequence procEnv.ApplyGraphRewriteSequence("createTNT"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); // use old inexact interface IMatches matchesInexact = actions.GetAction("TNT").Match(procEnv, 0, null); Console.WriteLine(matchesInexact.Count + " matches found."); // use new 2.5 exact interface IMatchesExact<Rule_ToluolCore.IMatch_ToluolCore> matchesExact = actions.ToluolCore.Match(procEnv, 0); Console.WriteLine(matchesExact.Count + " matches found."); }
void DoAlt() { graph = new LGSPGraph(new AlternativesGraphModel()); actions = new AlternativesActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // use graph rewrite sequence procEnv.ApplyGraphRewriteSequence("createComplex"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); // use old inexact interface IMatches matches = actions.GetAction("Complex").Match(procEnv, 0, null); Console.WriteLine(matches.Count + " Complex matches found."); // use new 2.5 exact interface IMatchesExact<Rule_ComplexMax.IMatch_ComplexMax> matchesExact = actions.ComplexMax.Match(procEnv, 0); Console.WriteLine(matchesExact.Count + " ComplexMax matches found."); }
// Have a look at the .gm + .grg, the ExternalFiltersAndSequencesActionsExternalFunctions.cs, // and the ExternalFiltersAndSequencesActionsExternalFunctionsImpl.cs files. // They show how to declare external match filters and external sequences in the rules file, // and how to use them in the sequences in the rule file or the shell script file. // The generated XXXExternalFunctions.cs file contains the partial classes of the filters and sequences // and the manually coded XXXExternalFunctionsImpl.cs file exemplifies how to implement these external functions. void DoEFS() { graph = new ExternalFiltersAndSequencesGraph(); actions = new ExternalFiltersAndSequencesActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // use graph rewrite sequence procEnv.ApplyGraphRewriteSequence("(::n)=init"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); // use new 2.5 exact interface IMatchesExact<Rule_r.IMatch_r> matchesExact = actions.r.Match(procEnv, 0); Console.WriteLine(matchesExact.Count + " matches found."); actions.r.Modify(procEnv, matchesExact.FirstExact); procEnv.ApplyGraphRewriteSequence("(::x,::y,::z,::u,::v)=foo(42, 3.141, Enu::hurz, \"S21-heiteitei\", true)"); procEnv.ApplyGraphRewriteSequence("filterBase\\f1"); }
void DoAlt() { graph = new StdGraph(); actions = new RecursiveActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); IMatches matches; Object[] returns; Action_createChain createChain = Action_createChain.Instance; matches = createChain.Match(procEnv, 0); returns = createChain.Modify(procEnv, matches.First); Node[] param = new Node[2]; param[0] = (Node)returns[0]; param[1] = (Node)returns[1]; matches = actions.GetAction("chainFromToReverseToCommon").Match(procEnv, 0, param); Console.WriteLine(matches.Count + " matches found."); Action_createBlowball createBlowball = Action_createBlowball.Instance; matches = createBlowball.Match(procEnv, 0); returns = createBlowball.Modify(procEnv, matches.First); matches = actions.GetAction("blowball").Match(procEnv, 0, returns); Console.WriteLine(matches.Count + " matches found."); graph.Clear(); matches = createChain.Match(procEnv, 0); returns = createChain.Modify(procEnv, matches.First); param[0] = (Node)returns[0]; Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); IAction chainFromCompleteArbitraryBaseAlwaysFailesByGoingBackwards = actions.GetAction("chainFromCompleteArbitraryBaseAlwaysFailesByGoingBackwards"); matches = chainFromCompleteArbitraryBaseAlwaysFailesByGoingBackwards.Match(procEnv, 0, param); Console.WriteLine(matches.Count + " matches found."); }
public String _targetName; // for ToString only public LGSPUndoElemAdded(IGraphElement elem, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; if(procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); if(_elem is IEdge) { _sourceName = ((LGSPNamedGraph)procEnv.graph).GetElementName(((IEdge)_elem).Source); _targetName = ((LGSPNamedGraph)procEnv.graph).GetElementName(((IEdge)_elem).Target); } } else { _name = "?"; if(_elem is IEdge) { _sourceName = "?"; _targetName = "?"; } } }
public readonly String _targetName; // for ToString only public LGSPUndoElemAdded(IGraphElement elem, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; if (procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); if (_elem is IEdge) { _sourceName = ((LGSPNamedGraph)procEnv.graph).GetElementName(((IEdge)_elem).Source); _targetName = ((LGSPNamedGraph)procEnv.graph).GetElementName(((IEdge)_elem).Target); } } else { _name = "?"; if (_elem is IEdge) { _sourceName = "?"; _targetName = "?"; } } }
void DoEdge1() { graph = new StdGraph(); actions = new edge1Actions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // use graph rewrite sequence procEnv.ApplyGraphRewriteSequence("init3"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed."); procEnv.PerformanceInfo.Reset(); // use old inexact interface IMatches matches = actions.GetAction("findTripleCircle").Match(procEnv, 0, null); Console.WriteLine(matches.Count + " matches found."); // use new exact interface IMatchesExact<Rule_findTripleCircle.IMatch_findTripleCircle> matchesExact = actions.findTripleCircle.Match(procEnv, 0); Console.WriteLine(matchesExact.Count + " matches found."); actions.findTripleCircle.Modify(procEnv, matchesExact.FirstExact); // rewrite first match (largely nop, as findTripleCircle is a test) }
static void Main(string[] args) { LGSPNamedGraph graph; LGSPActions actions; new LGSPBackend().CreateNamedFromSpec("Mutex.grg", null, 0, out graph, out actions); LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions); NodeType processType = graph.GetNodeType("Process"); EdgeType nextType = graph.GetEdgeType("next"); INode p1 = graph.AddNode(processType); INode p2 = graph.AddNode(processType); graph.AddEdge(nextType, p1, p2); graph.AddEdge(nextType, p2, p1); procEnv.ApplyGraphRewriteSequence("newRule[3] && mountRule && requestRule[5] " + "&& (takeRule && releaseRule && giveRule)*"); using(VCGDumper dumper = new VCGDumper("HelloMutex.vcg")) GraphDumper.Dump(graph, dumper); }
public static bool ApplyXGRS_isnull(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, object var_v1) { return(var_v1 == null); }
public static IList <GRGEN_LIBGR.IMatch> Filter_extshf(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, IList <GRGEN_LIBGR.IMatch> matches, System.Int32 f) { return(matches); }
/// <summary> /// Executes the embedded sequence closure /// </summary> /// <param name="procEnv">the processing environment on which to apply the sequence, esp. containing the graph</param> /// <returns>the result of sequence execution</returns> public abstract bool exec(LGSPGraphProcessingEnvironment procEnv);
public readonly String _name; // for ToString only public LGSPUndoSettingVisited(IGraphElement elem, int visitorID, bool oldValue, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; _visitorID = visitorID; _oldValue = oldValue; if (procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); } else { _name = "?"; } }
public static void Filter_nomnomnom(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <Rule_filterBase.IMatch_filterBase> matches) { // eat away the single match of the empty rule matches.RemoveMatch(0); }
void DoBusyBeaver() { long startBytes = System.GC.GetTotalMemory(true); int startTime = Environment.TickCount; graph = new Turing3Graph(); actions = new Turing3Actions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // Initialize tape BandPosition bp = graph.CreateNodeBandPosition(); // Initialize states State sA = graph.CreateNodeState(); procEnv.SetVariableValue("sA", sA); State sB = graph.CreateNodeState(); procEnv.SetVariableValue("sB", sB); State sC = graph.CreateNodeState(); procEnv.SetVariableValue("sC", sC); State sD = graph.CreateNodeState(); procEnv.SetVariableValue("sD", sD); State sE = graph.CreateNodeState(); procEnv.SetVariableValue("sE", sE); State sH = graph.CreateNodeState(); procEnv.SetVariableValue("sH", sH); // Create state transitions GenStateTransition("sA", 0, "sB", 1, L); GenStateTransition("sA", 1, "sD", 1, L); GenStateTransition("sB", 0, "sC", 1, R); GenStateTransition("sB", 1, "sE", 0, R); GenStateTransition("sC", 0, "sA", 0, L); GenStateTransition("sC", 1, "sB", 0, R); GenStateTransition("sD", 0, "sE", 1, L); GenStateTransition("sD", 1, "sH", 1, L); GenStateTransition("sE", 0, "sC", 1, R); GenStateTransition("sE", 1, "sC", 1, L); // Initialize head procEnv.SetVariableValue("curState", sA); procEnv.SetVariableValue("curPos", bp); // A little warm up for the beaver // Using a graph rewrite sequence with the new and more expressive syntax procEnv.ApplyGraphRewriteSequence( @"( ((curValue:WriteValue)=readOneRule(curState, curPos) || (curValue)=readZeroRule(curState,curPos)) && (ensureMoveLeftValidRule(curValue, curPos) || ensureMoveRightValidRule(curValue, curPos) || true) && ((curState, curPos)=moveLeftRule(curValue, curPos) || (curState, curPos)=moveRightRule(curValue, curPos)) )[100]"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); // Reset counters of the PerformanceInfo object procEnv.PerformanceInfo.Reset(); // Calculate search plans to optimize performance graph.AnalyzeGraph(); actions.GenerateActions("readOneRule", "readZeroRule", "ensureMoveLeftValidRule", "ensureMoveRightValidRule", "moveLeftRule", "moveRightRule"); // Go, beaver, go! #if USE_SEQUENCE procEnv.ApplyGraphRewriteSequence( @"( ((curValue:WriteValue)=readOneRule(curState, curPos) || (curValue)=readZeroRule(curState,curPos)) && (ensureMoveLeftValidRule(curValue, curPos) || ensureMoveRightValidRule(curValue, curPos) || true) && ((curState, curPos)=moveLeftRule(curValue, curPos) || (curState, curPos)=moveRightRule(curValue, curPos)) )*"); #else // the graph rewrite sequence from above formulated in C# with the API of GrGen.NET 2.5 IState curState = (IState)procEnv.GetVariableValue("curState"); IBandPosition curPos = (IBandPosition)procEnv.GetVariableValue("curPos"); IWriteValue curValue = (IWriteValue)procEnv.GetVariableValue("curValue"); bool expressionToIterateSucceeded; do { expressionToIterateSucceeded = ( actions.readOneRule.Apply(procEnv, curState, curPos, ref curValue) || actions.readZeroRule.Apply(procEnv, curState, curPos, ref curValue) ) && ( actions.ensureMoveLeftValidRule.Apply(procEnv, curValue, curPos) || actions.ensureMoveRightValidRule.Apply(procEnv, curValue, curPos) || true ) && ( actions.moveLeftRule.Apply(procEnv, curValue, curPos, ref curState, ref curPos) || actions.moveRightRule.Apply(procEnv, curValue, curPos, ref curState, ref curPos) ); } while(expressionToIterateSucceeded); #endif int stopTime = Environment.TickCount; // Count "BandPosition" nodes with a "value" attribute being one int numOnes = 0; foreach(BandPosition bpNode in graph.GetExactNodes(BandPosition.TypeInstance)) if(bpNode.value == 1) numOnes++; int countTime = Environment.TickCount - stopTime; Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found." + "\nNumber of ones written: " + numOnes + "\nTime needed for counting ones: " + countTime + " ms"); long endBytes = System.GC.GetTotalMemory(true); Console.WriteLine("Time: " + (stopTime - startTime) + " ms" + "\nMemory usage: " + (endBytes - startBytes) + " bytes" + "\nNum nodes: " + graph.NumNodes + "\nNum edges: " + graph.NumEdges); }
public String _name; // for ToString only public LGSPUndoSettingVisited(IGraphElement elem, int visitorID, bool oldValue, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; _visitorID = visitorID; _oldValue = oldValue; if(procEnv.graph is LGSPNamedGraph) _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); else _name = "?"; }
public IGraph _graph; // for ToString only public LGSPUndoElemRedirecting(LGSPEdge edge, LGSPNode source, LGSPNode target, LGSPGraphProcessingEnvironment procEnv) { _edge = edge; _source = source; _target = target; if(procEnv.graph is LGSPNamedGraph) _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_edge); else _name = "?"; _graph = procEnv.graph; }
public String _name; // for ToString only public LGSPUndoElemRetyped(IGraphElement oldElem, IGraphElement newElem, LGSPGraphProcessingEnvironment procEnv) { _oldElem = oldElem; _newElem = newElem; if(procEnv.graph is LGSPNamedGraph) _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(newElem); else _name = "?"; }
public static void Filter_f1(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.IMatchesExact <Rule_filterBase.IMatch_filterBase> matches) { // just let pass }
public readonly IGraph _graph; // for ToString only public LGSPUndoAttributeChanged(IGraphElement elem, AttributeType attrType, AttributeChangeType changeType, Object newValue, Object keyValue, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; _attrType = attrType; if (procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); } else { _name = "?"; } _graph = procEnv.graph; if (_attrType.Kind == AttributeKind.SetAttr) { if (changeType == AttributeChangeType.PutElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(newValue)) { _undoOperation = UndoOperation.None; } else { _undoOperation = UndoOperation.RemoveElement; _value = newValue; } } else if (changeType == AttributeChangeType.RemoveElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(newValue)) { _undoOperation = UndoOperation.PutElement; _value = newValue; } else { _undoOperation = UndoOperation.None; } } else // Assign { Type keyType; Type valueType; IDictionary dict = ContainerHelper.GetDictionaryTypes( _elem.GetAttribute(_attrType.Name), out keyType, out valueType); IDictionary clonedDict = ContainerHelper.NewDictionary(keyType, valueType, dict); _undoOperation = UndoOperation.Assign; _value = clonedDict; } } else if (_attrType.Kind == AttributeKind.ArrayAttr) { if (changeType == AttributeChangeType.PutElement) { IList array = (IList)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.RemoveElement; _keyOfValue = keyValue; } else if (changeType == AttributeChangeType.RemoveElement) { IList array = (IList)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.PutElement; if (keyValue == null) { _value = array[array.Count - 1]; } else { _value = array[(int)keyValue]; _keyOfValue = keyValue; } } else if (changeType == AttributeChangeType.AssignElement) { IList array = (IList)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.AssignElement; _value = array[(int)keyValue]; _keyOfValue = keyValue; } else // Assign { Type valueType; IList array = ContainerHelper.GetListType( _elem.GetAttribute(_attrType.Name), out valueType); IList clonedArray = ContainerHelper.NewList(valueType, array); _undoOperation = UndoOperation.Assign; _value = clonedArray; } } else if (_attrType.Kind == AttributeKind.DequeAttr) { if (changeType == AttributeChangeType.PutElement) { IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.RemoveElement; _keyOfValue = keyValue; } else if (changeType == AttributeChangeType.RemoveElement) { IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.PutElement; if (keyValue == null) { _value = deque.Front; } else { _value = deque[(int)keyValue]; _keyOfValue = keyValue; } } else if (changeType == AttributeChangeType.AssignElement) { IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.AssignElement; _value = deque[(int)keyValue]; _keyOfValue = keyValue; } else // Assign { Type valueType; IDeque deque = ContainerHelper.GetDequeType( _elem.GetAttribute(_attrType.Name), out valueType); IDeque clonedDeque = ContainerHelper.NewDeque(valueType, deque); _undoOperation = UndoOperation.Assign; _value = clonedDeque; } } else if (_attrType.Kind == AttributeKind.MapAttr) { if (changeType == AttributeChangeType.PutElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(keyValue)) { if (dict[keyValue] == newValue) { _undoOperation = UndoOperation.None; } else { _undoOperation = UndoOperation.PutElement; _value = dict[keyValue]; _keyOfValue = keyValue; } } else { _undoOperation = UndoOperation.RemoveElement; _value = newValue; _keyOfValue = keyValue; } } else if (changeType == AttributeChangeType.RemoveElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(keyValue)) { _undoOperation = UndoOperation.PutElement; _value = dict[keyValue]; _keyOfValue = keyValue; } else { _undoOperation = UndoOperation.None; } } else if (changeType == AttributeChangeType.AssignElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict[keyValue] == newValue) { _undoOperation = UndoOperation.None; } else { _undoOperation = UndoOperation.AssignElement; _value = dict[keyValue]; _keyOfValue = keyValue; } } else // Assign { Type keyType, valueType; IDictionary dict = ContainerHelper.GetDictionaryTypes( _elem.GetAttribute(_attrType.Name), out keyType, out valueType); IDictionary clonedDict = ContainerHelper.NewDictionary(keyType, valueType, dict); _undoOperation = UndoOperation.Assign; _value = clonedDict; } } else // Primitve Type Assign { _undoOperation = UndoOperation.Assign; _value = _elem.GetAttribute(_attrType.Name); } }
public void DoUndo(IGraphProcessingEnvironment procEnv) { String attrName = _attrType.Name; LGSPGraphProcessingEnvironment procEnv_ = (LGSPGraphProcessingEnvironment)procEnv; if (_undoOperation == UndoOperation.PutElement) { if (_attrType.Kind == AttributeKind.SetAttr) { ChangingElementAttribute(procEnv_); IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); dict.Add(_value, null); } else if (_attrType.Kind == AttributeKind.MapAttr) { ChangingElementAttribute(procEnv_); IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); dict.Add(_keyOfValue, _value); } else if (_attrType.Kind == AttributeKind.ArrayAttr) { ChangingElementAttribute(procEnv_); IList array = (IList)_elem.GetAttribute(_attrType.Name); if (_keyOfValue == null) { array.Add(_value); } else { array.Insert((int)_keyOfValue, _value); } } else //if(_attrType.Kind == AttributeKind.DequeAttr) { ChangingElementAttribute(procEnv_); IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); if (_keyOfValue == null) { deque.EnqueueFront(_value); } else { deque.EnqueueAt((int)_keyOfValue, _value); } } } else if (_undoOperation == UndoOperation.RemoveElement) { if (_attrType.Kind == AttributeKind.SetAttr) { ChangingElementAttribute(procEnv_); IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); dict.Remove(_value); } else if (_attrType.Kind == AttributeKind.MapAttr) { ChangingElementAttribute(procEnv_); IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); dict.Remove(_keyOfValue); } else if (_attrType.Kind == AttributeKind.ArrayAttr) { ChangingElementAttribute(procEnv_); IList array = (IList)_elem.GetAttribute(_attrType.Name); if (_keyOfValue == null) { array.RemoveAt(array.Count - 1); } else { array.RemoveAt((int)_keyOfValue); } } else //if(_attrType.Kind == AttributeKind.DequeAttr) { ChangingElementAttribute(procEnv_); IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); if (_keyOfValue == null) { deque.DequeueBack(); } else { deque.DequeueAt((int)_keyOfValue); } } } else if (_undoOperation == UndoOperation.AssignElement) { if (_attrType.Kind == AttributeKind.ArrayAttr) { ChangingElementAttribute(procEnv_); IList array = (IList)_elem.GetAttribute(_attrType.Name); array[(int)_keyOfValue] = _value; } else if (_attrType.Kind == AttributeKind.DequeAttr) { ChangingElementAttribute(procEnv_); IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); deque[(int)_keyOfValue] = _value; } else //if(_attrType.Kind == AttributeKind.MapAttr) { ChangingElementAttribute(procEnv_); IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); dict[_keyOfValue] = _value; } } else if (_undoOperation == UndoOperation.Assign) { ChangingElementAttribute(procEnv_); _elem.SetAttribute(attrName, _value); } // otherwise UndoOperation.None }
public static bool ApplyXGRS_blo(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_LIBGR.INode var_v1, GRGEN_LIBGR.IEdge var_v2, ref GRGEN_LIBGR.INode var_r1, ref GRGEN_LIBGR.IEdge var_r2) { var_r1 = var_v1; var_r2 = var_v2; return(true); }
public static bool ApplyXGRS_bar(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, object var_v1, object var_v2, ref object var_r1) { var_r1 = var_v1 ?? var_v2; return(true); }
/// <summary> /// Executes the Mutex benchmark with a problem size of n. /// This variant uses IAction.Apply and IAction.MinMax to apply the rules /// (also available IAction.ApplyStar and IAction.ApplyPlus). /// These functions make it very easy to program complex rule applications, /// while providing the same speed as using IAction.Match and IAction.Modify /// (this example is not a complex scenario). /// </summary> /// <param name="n">The problem size, i.e. the number of Process nodes</param> static void AlternativeTwo(int n) { int startTime = Environment.TickCount; MutexGraph graph = new MutexGraph(); MutexPimpedActions actions = new MutexPimpedActions(graph); LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions); LGSPNode p1 = graph.CreateNodeProcess(); LGSPNode p2 = graph.CreateNodeProcess(); LGSPEdge n1 = graph.CreateEdgenext(p1, p2); LGSPEdge n2 = graph.CreateEdgenext(p2, p1); Action_newRule.Instance.ApplyMinMax(procEnv, n - 2, n - 2); Action_mountRule.Instance.Apply(procEnv); Action_requestRule.Instance.ApplyMinMax(procEnv, n, n); Action_takeRule takeRule = Action_takeRule.Instance; Action_releaseRule releaseRule = Action_releaseRule.Instance; Action_giveRule giveRule = Action_giveRule.Instance; for(int i = 0; i < n; i++) { takeRule.Apply(procEnv); releaseRule.Apply(procEnv); giveRule.Apply(procEnv); } int endTime = Environment.TickCount; PrintResults(endTime - startTime, graph); }
public readonly IGraph _graph; // for ToString only public LGSPUndoElemRedirecting(LGSPEdge edge, LGSPNode source, LGSPNode target, LGSPGraphProcessingEnvironment procEnv) { _edge = edge; _source = source; _target = target; if (procEnv.graph is LGSPNamedGraph) { _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_edge); } else { _name = "?"; } _graph = procEnv.graph; }
/// <summary> /// Executes the Mutex benchmark with a problem size of n. /// This variant uses BaseActions.ApplyGraphRewriteSequence. /// Although this provides the fastest way to program rule applications /// for simple scenarios, it needs aprox. 12% more running time than /// via Apply or Match/Modify. /// </summary> /// <param name="n">The problem size, i.e. the number of Process nodes</param> static void AlternativeThree(int n) { int startTime = Environment.TickCount; MutexGraph graph = new MutexGraph(); MutexPimpedActions actions = new MutexPimpedActions(graph); LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions); LGSPNode p1 = graph.CreateNodeProcess(); LGSPNode p2 = graph.CreateNodeProcess(); LGSPEdge n1 = graph.CreateEdgenext(p1, p2); LGSPEdge n2 = graph.CreateEdgenext(p2, p1); procEnv.ApplyGraphRewriteSequence("newRule[" + (n - 2) + "] && mountRule && requestRule[" + n + "] && (takeRule && releaseRule && giveRule)[" + n + "]"); int endTime = Environment.TickCount; PrintResults(endTime - startTime, graph); }
public static void Filter_shfext(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, IList <GRGEN_LIBGR.IMatch> matches, System.Int32 f) { }
/// <summary> /// Executes the Mutex benchmark with a problem size of n. /// This variant uses IAction.Match and IAction.Modify to apply the rules. /// This way you get access to the found matches and can select between them manually. /// </summary> /// <param name="n">The problem size, i.e. the number of Process nodes</param> static void AlternativeOne(int n) { int startTime = Environment.TickCount; MutexGraph graph = new MutexGraph(); MutexPimpedActions actions = new MutexPimpedActions(graph); LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions); LGSPNode p1 = graph.CreateNodeProcess(); LGSPNode p2 = graph.CreateNodeProcess(); LGSPEdge n1 = graph.CreateEdgenext(p1, p2); LGSPEdge n2 = graph.CreateEdgenext(p2, p1); IMatches matches; Action_newRule newRule = Action_newRule.Instance; for(int i = 0; i < n - 2; i++) { matches = newRule.Match(procEnv, 1); newRule.Modify(procEnv, matches.First); } matches = Action_mountRule.Instance.Match(procEnv, 1); Action_mountRule.Instance.Modify(procEnv, matches.First); Action_requestRule requestRule = Action_requestRule.Instance; for(int i = 0; i < n; i++) { matches = requestRule.Match(procEnv, 1); requestRule.Modify(procEnv, matches.First); } /** * The MutexPimped.grg file has been annotated with [prio] to generate very good static * searchplans, without the need of dynamically generating searchplans. * * Otherwise you would use the following code to get better matcher programs: * * graph.AnalyzeGraph(); * LGSPAction[] newActions = actions.GenerateSearchPlans("takeRule", "releaseRule", "giveRule"); * LGSPAction takeRule = newActions[0]; * LGSPAction releaseRule = newActions[1]; * LGSPAction giveRule = newActions[2]; * * Alternatively you could also write: * * graph.AnalyzeGraph(); * actions.GenerateSearchPlans("takeRule", "releaseRule", "giveRule"); * LGSPAction takeRule = actions.GetAction("takeRule"); * LGSPAction releaseRule = actions.GetAction("releaseRule"); * LGSPAction giveRule = actions.GetAction("giveRule"); */ Action_takeRule takeRule = Action_takeRule.Instance; Action_releaseRule releaseRule = Action_releaseRule.Instance; Action_giveRule giveRule = Action_giveRule.Instance; for(int i = 0; i < n; i++) { matches = takeRule.Match(procEnv, 1); takeRule.Modify(procEnv, matches.First); matches = releaseRule.Match(procEnv, 1); releaseRule.Modify(procEnv, matches.First); matches = giveRule.Match(procEnv, 1); giveRule.Modify(procEnv, matches.First); } int endTime = Environment.TickCount; PrintResults(endTime - startTime, graph); // example for reading annotations at API level Action_annotationTestRule annotationTestRule = Action_annotationTestRule.Instance; foreach(KeyValuePair<string, string> annotation in annotationTestRule.rulePattern.Annotations) { Console.WriteLine("The rule " + annotationTestRule.Name + " is decorated with an annotation " + annotation.Key + " -> " + annotation.Value); } foreach(IPatternNode node in annotationTestRule.RulePattern.PatternGraph.Nodes) { foreach(KeyValuePair<string, string> annotation in node.Annotations) { Console.WriteLine("The pattern node " + node.Name + " of rule " + annotationTestRule.Name + " is decorated with an annotation " + annotation.Key + " -> " + annotation.Value); } } IAnnotationTestNode testNode = graph.CreateNodeAnnotationTestNode(); foreach(KeyValuePair<string, string> annotation in testNode.Type.Annotations) { Console.WriteLine("The node type " + testNode.Type.Name + " is decorated with an annotation " + annotation.Key + " -> " + annotation.Value); } }
public static bool ApplyXGRS_bla(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv, GRGEN_MODEL.IN var_v1, GRGEN_MODEL.IE var_v2, ref GRGEN_MODEL.IN var_r1, ref GRGEN_MODEL.IE var_r2) { var_r1 = var_v1; var_r2 = var_v2; return(true); }
public IGraph _graph; // for ToString only public LGSPUndoElemRemoved(IGraphElement elem, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; _vars = procEnv.GetElementVariables(_elem); if(procEnv.graph is LGSPNamedGraph) _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); else _name = null; _graph = procEnv.graph; }
public void ExecuteDeferredSequencesThenExitRuleModify(LGSPGraphProcessingEnvironment procEnv) { while(toBeExecuted.Peek().Count > 0) toBeExecuted.Peek().Dequeue().exec(procEnv); toBeExecuted.Pop(); }
void DoIt() { // create the LibGr Search Plan backend we want to use LGSPBackend backend = new LGSPBackend(); // the graph model we'll use JavaProgramGraphsGraphModel model = new JavaProgramGraphsGraphModel(); // the actions object for the rules we'll to use IActions ba; // import the instance graph we created with gxl2grs, using the the .gm we created by hand // (can't use import gxl for the program graph, because the given .gxl is severly rotten) // we throw away the named graph cause we don't need names here and they require about the same amount of memory as the graph itself; INamedGraph importedNamedGraph = (INamedGraph)Porter.Import("InstanceGraph.grs", backend, model, out ba); LGSPGraph graph = new LGSPGraph((LGSPNamedGraph)importedNamedGraph, "unnamed"); importedNamedGraph = null; // get the actions object for the rules we want to use JavaProgramGraphsActions actions = ba!=null ? (JavaProgramGraphsActions)ba : new JavaProgramGraphsActions(graph); // the graph processing environment we'll use LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions); // the instance graph script uses variables to build up the graph, // we query some of them here, to get the elements to refactor // (instead of variables one could use the element names) Class src = (Class)procEnv.GetNodeVarValue("I176"); // class Node Class tgt = (Class)procEnv.GetNodeVarValue("I194"); // class Packet - use if parameter is used in moving method //Class tgt = (Class)graph.GetNodeVarValue("I617"); // class String - use if instance variable is used in moving method MethodBody mb = (MethodBody)procEnv.GetNodeVarValue("I409"); // method body of send // get operation for method body by: // get action, match action pattern with given parameters, apply rewrite filling given out parameters IMatchesExact<Rule_getOperation.IMatch_getOperation> matches = actions.getOperation.Match(procEnv, 1, mb); IOperation op; actions.getOperation.Modify(procEnv, matches.FirstExact, out op); // iterated application of action marking the body of the expression // (shows second way of getting action) int visitedFlagId = graph.AllocateVisitedFlag(); Debug.Assert(visitedFlagId==0); IGraphElement[] param = new LGSPNode[1]; param[0] = mb; IMatches matchesInexact; while((matchesInexact = actions.GetAction("markExpressionOfBody").Match(procEnv, 1, param)).Count == 1) { actions.GetAction("markExpressionOfBody").Modify(procEnv, matchesInexact.First); } // application of a graph rewrite sequence procEnv.SetVariableValue("src", src); procEnv.SetVariableValue("tgt", tgt); procEnv.SetVariableValue("mb", mb); procEnv.SetVariableValue("op", op); procEnv.ApplyGraphRewriteSequence( @"(p)=someParameterOfTargetType(mb,tgt) && !callToSuperExists && !isStatic(mb) && !methodNameExists(mb,tgt) && (!thisIsAccessed || thisIsAccessed && (srcparam)=addSourceParameter(op,src) && useSourceParameter(srcparam)*) && relinkOperationAndMethodBody(op,mb,src,tgt) && ( (call,pe)=getUnprocessedCallWithActualParameter(op,p) && ((def(srcparam) && addSourceToCall(call,srcparam)) || true) && (replaceAccess_Parameter_AccessWithoutLink(c,pe) || replaceAccess_Parameter_AccessWithLinkToExpression(c,pe)) )*"); Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found."); procEnv.PerformanceInfo.Reset(); // unmark the body of the expression by searching all occurences and modifying them actions.unmarkExpression.ApplyAll(0, procEnv); graph.FreeVisitedFlag(visitedFlagId); // export changed graph (alternatively you may export it as InstanceGraphAfter.gxl) // if we'd use a NamedGraph we'd get the graph exported with its persistent names; so we get it exported with some hash names List<String> exportParameters = new List<string>(); exportParameters.Add("InstanceGraphAfter.grs"); Porter.Export(graph, exportParameters); }
public IGraph _graph; // for ToString only public LGSPUndoAttributeChanged(IGraphElement elem, AttributeType attrType, AttributeChangeType changeType, Object newValue, Object keyValue, LGSPGraphProcessingEnvironment procEnv) { _elem = elem; _attrType = attrType; if(procEnv.graph is LGSPNamedGraph) _name = ((LGSPNamedGraph)procEnv.graph).GetElementName(_elem); else _name = "?"; _graph = procEnv.graph; if (_attrType.Kind == AttributeKind.SetAttr) { if (changeType == AttributeChangeType.PutElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(newValue)) { _undoOperation = UndoOperation.None; } else { _undoOperation = UndoOperation.RemoveElement; _value = newValue; } } else if (changeType == AttributeChangeType.RemoveElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(newValue)) { _undoOperation = UndoOperation.PutElement; _value = newValue; } else { _undoOperation = UndoOperation.None; } } else // Assign { Type keyType, valueType; IDictionary dict = ContainerHelper.GetDictionaryTypes( _elem.GetAttribute(_attrType.Name), out keyType, out valueType); IDictionary clonedDict = ContainerHelper.NewDictionary(keyType, valueType, dict); _undoOperation = UndoOperation.Assign; _value = clonedDict; } } else if (_attrType.Kind == AttributeKind.ArrayAttr) { if (changeType == AttributeChangeType.PutElement) { IList array = (IList)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.RemoveElement; _keyOfValue = keyValue; } else if (changeType == AttributeChangeType.RemoveElement) { IList array = (IList)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.PutElement; if(keyValue == null) { _value = array[array.Count-1]; } else { _value = array[(int)keyValue]; _keyOfValue = keyValue; } } else if(changeType == AttributeChangeType.AssignElement) { IList array = (IList)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.AssignElement; _value = array[(int)keyValue]; _keyOfValue = keyValue; } else // Assign { Type valueType; IList array = ContainerHelper.GetListType( _elem.GetAttribute(_attrType.Name), out valueType); IList clonedArray = ContainerHelper.NewList(valueType, array); _undoOperation = UndoOperation.Assign; _value = clonedArray; } } else if(_attrType.Kind == AttributeKind.DequeAttr) { if(changeType == AttributeChangeType.PutElement) { IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.RemoveElement; _keyOfValue = keyValue; } else if(changeType == AttributeChangeType.RemoveElement) { IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.PutElement; if(keyValue == null) { _value = deque.Front; } else { _value = deque[(int)keyValue]; _keyOfValue = keyValue; } } else if(changeType == AttributeChangeType.AssignElement) { IDeque deque = (IDeque)_elem.GetAttribute(_attrType.Name); _undoOperation = UndoOperation.AssignElement; _value = deque[(int)keyValue]; _keyOfValue = keyValue; } else // Assign { Type valueType; IDeque deque = ContainerHelper.GetDequeType( _elem.GetAttribute(_attrType.Name), out valueType); IDeque clonedDeque = ContainerHelper.NewDeque(valueType, deque); _undoOperation = UndoOperation.Assign; _value = clonedDeque; } } else if(_attrType.Kind == AttributeKind.MapAttr) { if (changeType == AttributeChangeType.PutElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(keyValue)) { if (dict[keyValue] == newValue) { _undoOperation = UndoOperation.None; } else { _undoOperation = UndoOperation.PutElement; _value = dict[keyValue]; _keyOfValue = keyValue; } } else { _undoOperation = UndoOperation.RemoveElement; _value = newValue; _keyOfValue = keyValue; } } else if (changeType == AttributeChangeType.RemoveElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if (dict.Contains(keyValue)) { _undoOperation = UndoOperation.PutElement; _value = dict[keyValue]; _keyOfValue = keyValue; } else { _undoOperation = UndoOperation.None; } } else if(changeType == AttributeChangeType.AssignElement) { IDictionary dict = (IDictionary)_elem.GetAttribute(_attrType.Name); if(dict[keyValue] == newValue) { _undoOperation = UndoOperation.None; } else { _undoOperation = UndoOperation.AssignElement; _value = dict[keyValue]; _keyOfValue = keyValue; } } else // Assign { Type keyType, valueType; IDictionary dict = ContainerHelper.GetDictionaryTypes( _elem.GetAttribute(_attrType.Name), out keyType, out valueType); IDictionary clonedDict = ContainerHelper.NewDictionary(keyType, valueType, dict); _undoOperation = UndoOperation.Assign; _value = clonedDict; } } else // Primitve Type Assign { _undoOperation = UndoOperation.Assign; _value = _elem.GetAttribute(_attrType.Name); } }
static void Main(string[] args) { if(args.Length < 2 || args.Length > 3) { Console.WriteLine("usage: MovieDatabaseBenchmarker <name of rule to apply> <name of grs file to import or number of creation iterations of synthetic graph> [\"sequence to execute\"]"); Console.WriteLine("example: MovieDatabaseBenchmarker findCouplesOpt imdb-0005000-50176.movies.xmi.grs"); Console.WriteLine("example: MovieDatabaseBenchmarker findCliquesOf3Opt imdb-0130000-712130.movies.xmi.grs \"[cliques3WithRating\\orderDescendingBy<avgRating>\\keepFirst(15)] ;> [cliques3WithRating\\orderDescendingBy<numMovies>\\keepFirst(15)]\""); return; } // the graph we'll work on LGSPGraph graph; // the actions we'll use MovieDatabaseActions actions; // the graph processing environment we'll use LGSPGraphProcessingEnvironment procEnv; int dummy; if(Int32.TryParse(args[1], out dummy)) { Console.WriteLine("Synthesizing test graph with iteration count " + args[1] + " ..."); graph = new MovieDatabaseModelGraph(); actions = new MovieDatabaseActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); int startTimeSynth = Environment.TickCount; procEnv.ApplyGraphRewriteSequence("createExample(" + args[1] + ")"); Console.WriteLine("...needed " + (Environment.TickCount - startTimeSynth) + "ms for synthesizing"); } else { Console.WriteLine("Importing " + args[1] + " ..."); // the libGr search plan backend we'll use LGSPBackend backend = new LGSPBackend(); // the graph model we'll use MovieDatabaseModelGraphModel model = new MovieDatabaseModelGraphModel(); // import the graph, result (of grs import) will be a named graph IActions ba; INamedGraph importedNamedGraph = (INamedGraph)Porter.Import(args[1], backend, model, out ba); // we throw away the named graph cause we don't need names here and they require a huge amount of memory graph = new LGSPGraph((LGSPNamedGraph)importedNamedGraph, "unnamed"); importedNamedGraph = null; GC.Collect(); actions = ba != null ? (MovieDatabaseActions)ba : new MovieDatabaseActions(graph); procEnv = new LGSPGraphProcessingEnvironment(graph, actions); } // calculate search plans to optimize performance (I'm not going to fiddle with loading saved analysis data here) graph.AnalyzeGraph(); actions.GenerateActions(args[0]); Console.WriteLine("Number of Movie: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Movie").TypeID]); Console.WriteLine("Number of Actor: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Actor").TypeID]); Console.WriteLine("Number of Actress: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Actress").TypeID]); Console.WriteLine("Number of personToMovie: " + graph.edgesByTypeCounts[graph.Model.EdgeModel.GetType("personToMovie").TypeID]); Console.WriteLine("Start matching " + args[0] + " ..."); int startTime = Environment.TickCount; // get action, search for all matches, apply rewrite IAction ruleToApply = actions.GetAction(args[0]); IMatches matches = ruleToApply.Match(procEnv, 0, new object[0]); Console.WriteLine("...needed " + (Environment.TickCount - startTime) + "ms for finding the matches"); Console.WriteLine("...continue with rewriting..."); ruleToApply.ModifyAll(procEnv, matches); Console.WriteLine("...needed " + (Environment.TickCount - startTime) + "ms for finding the matches and adding the couples/cliques"); Console.WriteLine("Number of Couple: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Couple").TypeID]); Console.WriteLine("Number of Clique: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Clique").TypeID]); Console.WriteLine("Number of commonMovies: " + graph.edgesByTypeCounts[graph.Model.EdgeModel.GetType("commonMovies").TypeID]); if(args.Length == 3) { procEnv.ApplyGraphRewriteSequence(args[2]); } }