public static void WritePromela(KPsystem kp, Experiment kpx, PromelaTranslationParams tp, TextWriter writer) { var model = new KpTranslator(kp, kpx, tp).Translate(); var promelaWriter = new PromelaWriter(writer); promelaWriter.Write(model); }
public static void Translate(KpCore.KpModel kpModel, Experiment kpx, string outFileName) { KPsystem kpSystem = kpModel.KPsystem; KpMetaModel kpMetaModel = new KpMetaModel(kpSystem); try { //Translate KP model to SMV model SMVModel nuSMV = BNuSMV.buildModel(kpSystem); //SMVModels are loaded, in first run write variable to XML files, in 2nd run these values can be read. foreach (var module in nuSMV.Modules) { BVariables.writeBounds2XML(module); } //Generate SMV file if (nuSMV != null) { PrintNuSMV(nuSMV, kpMetaModel, kpx, outFileName); } else { throw new Exception("NuSMV translation failed."); } } catch (Exception ex) { Console.WriteLine("Exception occurred during NuSMV translation."); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); throw ex; } }
public void Write(KPsystem kp) { if (kp != null) { Write(new KpTranslator(kp).Translate()); } }
/// <summary> /// Get list of all connected instances to @param kpInstance as the list of SMV instances. /// </summary> /// <param name="nuSMV"></param> /// <param name="kPsystem"></param> /// <param name="kpInstance"></param> /// <returns></returns> public static List <Instance> getInstanceConnections(SMVModel nuSMV, KPsystem kPsystem, MInstance kpInstance) { List <Instance> smvInstances = new List <Instance>(); foreach (var connected in kpInstance.Connections) { MType targetType = findTargetTypeOfInstance(kPsystem, connected); Module targetModule = nuSMV.getModule(targetType, connected); Instance smvInstance = targetModule.Instance; if (smvInstance != null) { // if connection is not exist then add it if (!smvInstances.Exists(item => item.Name == smvInstance.Name)) { smvInstances.Add(smvInstance); } } else { throw new Exception("Corresponding SMV instance of " + connected.Name + " not found!"); } } return(smvInstances); }
private static void setBoundIntType(KPsystem kpSystem, MType type, Module module, Variable variable) { bool setByXML = false; if (manageBoundsByUser) { if (isBoundXMLFileExist(module.Type)) { setByXML = readBounds(variable as Variable); } } if (!(manageBoundsByUser && setByXML)) { if (variable.Type == null) { BoundInt boundInt = new BoundInt(); int lowerBound = 0; int upperBound = setMax(kpSystem, type, module, variable); variable.Type = new BoundInt(lowerBound, upperBound); } else { int upperBound = setMax(kpSystem, type, module, variable); if (upperBound > (variable.Type as BoundInt).UpperBound) { (variable.Type as BoundInt).UpperBound = upperBound; } } } }
/*****************************************************************************/ #region generate custom variables //variables required for NuSMV model public static void generateCustomVariables(KPsystem kpSystem, MType kpType, Module module) { if (module.HasDivisionRule || module.HasDissolutionRule) { Variable status = generateStatusVariable(module, kpType); if (status != null) { module.Status = status; } } Variable turn = generateTurnVariable(module, kpType); if (turn != null) { module.Turn = turn; } if (module.HasConnection) { List <NoNextVar> connections = generateConnectionVariable(kpSystem, kpType, module); if (connections != null) { module.Connections = connections; } } }
private void writeInitialConfig(KPsystem kp) { owt.WriteLine("Initial Configuration"); owt.WriteLine("-------------------------------------------------"); writeKPsystem(kp); owt.WriteLine("-------------------------------------------------"); }
private static void buildDissolutionVariables(KPsystem kpSystem, KpCore.MType type, NuSMV.Module module, int strategyIndex, KpCore.Rule rule) { //Preserve variable value and update status value. DissolutionRule dissolutionRule = (DissolutionRule)rule; foreach (var leftHRule in dissolutionRule.Lhs) { Variable variable = new Variable(leftHRule.Key); if (!module.Variables.Contains(variable)) { variable.Type = new BoundInt(0, setMax(kpSystem, type, module, variable)); variable.Behaviour = VariableBehaviour.REWRITING; variable.Init = setOrUpdateInit(module, variable); module.Variables.Add(variable); } else { //if variable exists then update the upperbound value. variable = (Variable)module.Variables.First(item => item.Name.Equals(leftHRule.Key)); } //add result of rule to caseline BRulesStandardVar.addCaseLineToStandardVariable(variable, rule, module, strategyIndex); } // add rule to status variable BRulesCustomVar.addRuleToStatusVariable(rule, module, strategyIndex); }
public KPsystemXMLWriter(KPsystem kp) { kPsystem = kp; model = new Model(); agentsInitial = new AgentsInitialConfiguration(); objectsId = new ObjectsId(); typeId = new Dictionary <string, int>(); membraneId = new MembraneId(); membranes = new Membranes(objectsId); FlameRulesGenerator flameRulesGenerator = new FlameRulesGenerator(objectsId, membraneId); FlameCodeRulesGenerator flameCodeRulesGenerator = new FlameCodeRulesGenerator(objectsId, membraneId); foreach (MType mType in kPsystem.Types) { typeId.Add(mType.Name, typeId.Count); membranes.AddMembraneType(mType); model.AddAgent(new Agent(mType, typeId[mType.Name], flameCodeRulesGenerator)); Console.WriteLine(mType.Name); } foreach (MType mType in kPsystem.Types) { AgentMembrane agentMembrane = new AgentMembrane(); agentMembrane.Name = mType.Name; agentMembrane.Id = membraneId[mType.Name].ToString(); List <int> list = flameCodeRulesGenerator.Rules(mType.ExecutionStrategy); foreach (MInstance mInstance in mType.Instances) { agentMembrane.AddInstance(flameRulesGenerator.Multiset(mInstance.Multiset), mInstance, membranes, membraneId); } agentsInitial.AddMembrane(agentMembrane); } }
private static void buildReWritingVariables(KPsystem kpSystem, KpCore.MType kpType, NuSMV.Module module, int strategyIndex, KpCore.Rule kpRule) { RewritingRule rwr = (RewritingRule)kpRule; string varName = ""; VariableOrigin origin = VariableOrigin.Original; bool isLeft = true; foreach (var leftHRule in rwr.Lhs) { varName = leftHRule.Key; origin = VariableOrigin.Original; isLeft = true; buildReWritingVariable(kpSystem, kpType, module, strategyIndex, kpRule, varName, origin, isLeft); } foreach (var rigthHRule in rwr.Rhs) { varName = rigthHRule.Key; origin = VariableOrigin.Original; isLeft = false; //first generate original one, then its copy if (!module.isVariableExist(varName)) { buildReWritingVariable(kpSystem, kpType, module, strategyIndex, kpRule, varName, origin, isLeft); } string copyVarName = varName + SMVPreFix.COPY; origin = VariableOrigin.Copy; buildReWritingVariable(kpSystem, kpType, module, strategyIndex, kpRule, copyVarName, origin, isLeft); } }
/// <summary> /// Sets an ID to each rule. Generate name for unnamed instances. /// </summary> /// <param name="kpSystem"></param> private static void prepareKpSystem(KPsystem kpSystem) { foreach (var kpType in kpSystem.Types) { ExecutionStrategy kpES = kpType.ExecutionStrategy; while (kpES != null) { int id = 1; foreach (var kpRule in kpES.Rules) { kpRule.Id = id; id++; } kpES = kpES.Next; } //produce a name for unnamed instances int count = 0; foreach (var kpInstance in kpType.Instances) { if (String.IsNullOrWhiteSpace(kpInstance.Name)) { kpInstance.Name = "_" + kpType.Name.ToLower() + count; count++; } } } }
private static void extractVarFromBasicGuards(KPsystem kpSystem, MType kpType, Module module, BasicGuard basicGuard) { Multiset ms = basicGuard.Multiset; NuSMV.RelationalOperator oper = SMVUtil.getRelationalOperator(basicGuard.Operator); Variable variable = null; foreach (var varName in ms.Objects) { if (!module.isVariableExist(varName)) { variable = new Variable(varName); int upperBound = ms[varName]; //if the guard requires a number greater, or greaterEqual, then it upperbound should be at least one number greater then, //the condition if (oper.Operator == NuSMV.RelationalOperator.GEQ || oper.Operator == NuSMV.RelationalOperator.GT) { upperBound = upperBound + 1; } variable.Type = new BoundInt(0, upperBound); setBoundIntType(kpSystem, kpType, module, variable); variable.Behaviour = VariableBehaviour.REWRITING; variable.Init = setOrUpdateInit(module, variable); module.Variables.Add(variable); } } }
public KPsystem Run(KPsystem kps) { if (kps != kp) { Reset(kps); } return(Run()); }
public ActiveInstance(IndexedMType itype, MInstance instance, KPsystem kp) : base(itype.Type, instance) { Buffer = new Multiset(); applicableRules = new List <Rule>(); this.kp = kp; IndexedMType = itype; }
private void simulationStarted(KPsystem kp) { owt.WriteLine("Simulation started."); if (!MuteConfiguration) { writeInitialConfig(kp); } }
public void WriteFormatted(KPsystem kp) { TextWriter tw = owt; owt = new StringWriter(); Write(kp); tw.Write(JsonFormatter.Format(owt.ToString())); tw.Flush(); }
public static void WriteJSON(KPsystem kp, TextWriter writer, bool formatted = false) { if (formatted) { new JsonWriter(writer).WriteFormatted(kp); } else { new JsonWriter(writer).Write(kp); } }
public void Write(KPsystem kp) { if (!String.IsNullOrEmpty(kp.Name)) { owt.WriteLine("#Name: {0}", kp.Name); owt.WriteLine("#Description: {0}", kp.Description); owt.WriteLine(); } foreach (MType mtype in kp.Types) { owt.WriteLine("@" + mtype.Name + ":"); } }
private static void buildDivisionVariables(NuSMV.Module module, KPsystem kpSystem, KpCore.MType type, int strategyIndex, KpCore.Rule rule) { DivisionRule divisionRule = (DivisionRule)rule; foreach (var leftHRule in divisionRule.Lhs) { Variable variable = new Variable(leftHRule.Key); if (!module.Variables.Contains(variable)) { variable.Type = new BoundInt(0, setMax(kpSystem, type, module, variable)); variable.Behaviour = VariableBehaviour.REWRITING; variable.Init = setOrUpdateInit(module, variable); module.Variables.Add(variable); } else { //if variable exists then update the upperbound value. variable = (Variable)module.Variables.First(item => item.Name.Equals(leftHRule.Key)); } //add result of rule to caseline BRulesStandardVar.addCaseLineToStandardVariable(variable, rule, module, strategyIndex); } foreach (InstanceBlueprint compartment in divisionRule.Rhs) { MType compType = compartment.Type; if (type.Name.Equals(compType.Name)) { Multiset ms = compartment.Multiset; foreach (var obj in ms.Objects) { Variable variable = new Variable(obj); if (!module.Variables.Contains(variable)) { variable.Type = new BoundInt(0, setMax(kpSystem, compType, module, variable)); variable.Behaviour = VariableBehaviour.DIVISION; variable.Init = setOrUpdateInit(module, variable); module.Variables.Add(variable); } else { variable = (Variable)module.Variables.First(item => item.Name.Equals(obj)); variable.Behaviour = VariableBehaviour.DIVISION; } } } } // add rule to status variable BRulesCustomVar.addRuleToStatusVariable(rule, module, strategyIndex); }
private static void buildReWritingVariable(KPsystem kpSystem, KpCore.MType kpType, NuSMV.Module module, int strategyIndex, KpCore.Rule kpRule, string newVarName, VariableOrigin origin, bool isLeft) { Variable newVar = null; //if variable does not exist then create it, if (!module.isVariableExist(newVarName)) { if (origin == VariableOrigin.Original) { newVar = new Variable(newVarName); setBoundIntType(kpSystem, kpType, module, newVar); newVar.Behaviour = VariableBehaviour.REWRITING; newVar.Init = setOrUpdateInit(module, newVar); newVar.Origin = VariableOrigin.Original; if (isLeft) { //if it is on left then add it, but do not add rules to first not-copy variable on right. BRulesStandardVar.addCaseLineToStandardVariable(newVar, kpRule, module, strategyIndex); } } else if (origin == VariableOrigin.Copy) { newVar = new Variable(newVarName); Variable orginalVariable = (Variable)module.getVariable(newVarName.Replace(SMVPreFix.COPY, "")); newVar.Type = orginalVariable.Type; newVar.Behaviour = VariableBehaviour.REWRITING; newVar.Init = "0"; newVar.Origin = VariableOrigin.Copy; //add result of rule to caseline BRulesStandardVar.addCaseLineToStandardVariable(newVar, kpRule, module, strategyIndex); } if (newVar != null) { module.Variables.Add(newVar); } else { throw new Exception("Cannot create variable : " + newVarName); } } else { //bring variable to add new rules. newVar = (Variable)module.Variables.First(item => item.Name.Equals(newVarName)); BRulesStandardVar.addCaseLineToStandardVariable(newVar, kpRule, module, strategyIndex); } }
/// <summary> /// Finds corresponding KP type of provided KP instance. /// </summary> /// <param name="kPsystem"></param> /// <param name="mInstance"></param> /// <returns></returns> private static MType findTargetTypeOfInstance(KPsystem kPsystem, MInstance mInstance) { MType targetType = null; foreach (var type in kPsystem.Types) { foreach (var instance in type.Instances) { if (mInstance == instance) { targetType = type; return(targetType); } } } return(targetType); }
public KpMetaModel(KPsystem kp, bool build) { KPsystem = kp; tm = new Dictionary <int, MTypeMeta>(); typeMeta = new Dictionary <MType, MTypeMeta>(); instanceRegistry = new Dictionary <MInstance, MInstanceMeta>(); ruleRegistry = new Dictionary <Rule, RuleMeta>(); alphabet = new Dictionary <int, Symbol>(); symbols = new Dictionary <string, Symbol>(); symbolCount = 0; AreLinksNecessary = false; if (build) { Build(); } }
public void Reset(KPsystem newModel) { Reset(); kp = newModel; allInstances.Clear(); allOperationalInstances.Clear(); indexedTypes.Clear(); int i = 0; foreach (MType mtype in kp.Types) { IndexedMType imt = new IndexedMType(mtype, i++); indexedTypes.Add(imt); indexedTypesByName.Add(mtype.Name, imt); ExecutionStrategy ex = mtype.ExecutionStrategy; while (ex != null && ex.Rules.Count == 0) { ex = ex.Next; } foreach (MInstance instance in mtype.Instances) { ActiveInstance activeInstance = new ActiveInstance(imt, instance, kp); allInstances.Add(activeInstance); aiMapping.Add(instance, activeInstance); if (ex != null) { allOperationalInstances.Add(activeInstance); activeInstance.CurrentStrategySegment = ex; } } } foreach (ActiveInstance ai in allInstances) { ai.GenerateConnections(aiMapping); //set execution strategy to begining ai.ResetCurrentStrategySegment(); } }
private static void extractVarsFromGuards(KPsystem kpSystem, MType kpType, Module module, IGuard guard) { if (guard is BasicGuard) { BasicGuard basicGuard = (BasicGuard)guard; extractVarFromBasicGuards(kpSystem, kpType, module, basicGuard); } else if (guard is NegatedGuard) { NegatedGuard negatedGuard = (NegatedGuard)guard; Console.Error.WriteLine("This part has not implemented yet."); // ICondition negatedBooleanExpression = getNegatedGuard(negatedGuard); } else if (guard is CompoundGuard) { CompoundGuard compoundGuard = (CompoundGuard)guard; extractVarsFromGuards(kpSystem, kpType, module, compoundGuard.Lhs); extractVarsFromGuards(kpSystem, kpType, module, compoundGuard.Rhs); } }
private static List <NoNextVar> generateConnectionVariable(KPsystem kpSystem, MType kpType, Module module) { List <NoNextVar> connections = new List <NoNextVar>(); foreach (MType mType in kpSystem.Types) { NoNextVar connection = new NoNextVar(SMVPreFix.getConnectionVar(mType)); connection.Behaviour = VariableBehaviour.CUSTOM; SEnum connEnums = new SEnum(); HashSet <Instance> connectedTo = new HashSet <Instance>(); foreach (var connectedInstance in module.Instance.ConnectedTo) { // if it has connection if (connectedInstance.Module.Type == mType.Name) { bool communicationRuleToTargetExist = communicationRuleIncludesTargetType(kpType, mType); if (communicationRuleToTargetExist) { connectedTo.Add(connectedInstance); } } } //if there is more than one connection of same type compartments exists, then add it to connections if (connectedTo.Count > 1) { //sort them IEnumerable <Instance> orderedConns = connectedTo.OrderBy(instance => instance.Name); foreach (var connectedInstance in orderedConns) { connEnums.Values.Add(SMVPreFix.getConnectedTo(connectedInstance)); } connection.Type = connEnums; // connection.Init = setOrUpdateInit(module, connection); Commented out, since no need to get from parameter. connections.Add(connection); } } return(connections); }
public IEnumerable <MInstance> ResolveInstances(KPsystem kp, IInstanceIdentifier identifier) { List <MInstance> instances = new List <MInstance>(); if (identifier is InstanceIdentifier) { InstanceIdentifier ident = identifier as InstanceIdentifier; if (ident.Indicator == InstanceIndicator.TYPE) { foreach (MType type in kp.Types) { if (type.Name == ident.Value) { instances.AddRange(type.Instances); } } } } //solve if instance identifier is complex (i.e. includes more than one basic identifier) return(instances); }
public void Write(KPsystem kp) { owt.Write("{"); if (writePItem(kp)) { owt.Write(", "); } owt.Write("\"types\":["); int i = 1; foreach (MType type in kp.Types) { writeType(type); if (i++ < kp.Types.Count) { owt.Write(", "); } } owt.Write("]"); owt.Write("}"); owt.Flush(); }
public static SMVModel buildModel(KPsystem param_kpSystem) { kpSystem = param_kpSystem; if (kpSystem != null) { //set an id to each rules prepareKpSystem(kpSystem); nuSMV = new SMVModel(); try { //If there are division rules, generate child instances as kPInstance foreach (var kpType in kpSystem.Types) { if (kpTypeHasDivisionRule(kpType)) { List <KPChildInstance> kpChildInstances = BDivisionInstances.generateKPChildInstances(kpType); if (kpChildInstances != null) { kpType.Instances.AddRange(kpChildInstances); } } } //Generate a module for each kPInstance, including child instances(if division rule exist) foreach (var kpType in kpSystem.Types) { foreach (MInstance kpInstance in kpType.Instances) { Module module = new Module(); prepareSMVModule(module, kpType, kpInstance); nuSMV.Modules.Add(module); } } foreach (var kpType in kpSystem.Types) { foreach (MInstance kpInstance in kpType.Instances) { buildInstanceConnections(kpType, kpInstance); } } foreach (var kpType in kpSystem.Types) { foreach (MInstance kpInstance in kpType.Instances) { Module module = nuSMV.getModule(kpType, kpInstance); BVariables.generateCustomVariables(kpSystem, kpType, module); } } foreach (var kpType in kpSystem.Types) { foreach (MInstance kpInstance in kpType.Instances) { buildModule(kpType, kpInstance); } } if (nuSMV != null) { foreach (var kpType in kpSystem.Types) { foreach (MInstance kpInstance in kpType.Instances) { Module module = nuSMV.getModule(kpType, kpInstance); if (module.HasDivisionRule) { BDivisionInstances.generateDivisionRules(kpType, kpInstance, module); } } } } //assign cases for synch variable of main module. buildMain(nuSMV); //finalize model, add caseLast caselines, do modifications, sorting etc. assignLastCasesToNext(nuSMV); } catch (Exception ex) { throw ex; } } return(nuSMV); }
/// <summary> /// A KpMeta object assumes the KPsystem it wraps around is immutable /// </summary> /// <param name="kps"></param> public KpMeta(KPsystem kps) { //the assignment automatically triggers the building process KPsystem = kps; }
private void writeKPsystem(KPsystem kp) { foreach (MType type in kp.Types) { owt.WriteLine("TYPE {0}", type.Name); foreach (MInstance instance in type.Instances) { owt.Write("#{0}", instance.Id); if (instance.HasName()) { owt.Write(" {0}", instance.Name); } string status = null; if (instance.IsCreated) { status = "Created"; } if (instance.IsDissolved) { status = status == null ? "Dissolved" : status + ", Dissolved"; } else if (instance.IsDivided) { status = status == null ? "Divided" : status + ", Divided"; } else { status = status == null ? "Active" : status + ", Active"; } owt.Write(" [{0}]", status); owt.Write(" {"); int i = 1, count = instance.Multiset.Count; foreach (KeyValuePair <string, int> ms in instance.Multiset) { if (ms.Value > 0) { if (ms.Value == 1) { owt.Write(ms.Key); } else { owt.Write("{0}{1}", ms.Value, ms.Key); } if (i++ < count) { owt.Write(", "); } } } owt.Write("}"); owt.Write(" Links to #: "); i = 1; count = instance.Connections.Count; if (count == 0) { owt.Write("none"); } else { foreach (MInstance connection in instance.Connections) { owt.Write("{0}", connection.Id); if (i++ < count) { owt.Write(", "); } } } owt.WriteLine(); } } }