public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }, abort: true); } finally { if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // create a checker instance var ch = new Framework.Checker(currentobj, project, null); var checkerWindow = new RuleView(ch); checkerWindow.ShowDialog(); }
//[CheckerRule("Modelica TB 2", Description = "Description!")] //[Tags("Modelica", "Modelica 2")] //[ValidContext("Component")] public static IEnumerable<RuleFeedbackBase> CheckRule2(MgaFCO context) { return new List<RuleFeedbackBase> { new GenericRuleFeedback{FeedbackType = FeedbackTypes.Warning, Message = "Warning1"}, }; }
private void VisitConnector(CyPhy.Connector connector, MgaFCO parent) { if (!visitedPorts.Contains(connector.ID + "_" + parent.ID)) { visitedPorts.Add(connector.ID + "_" + parent.ID); bool parentIsComponent = (connector.ParentContainer is CyPhy.Component); bool isStart = (connector.ID == startNodeID); if (!isStart && parentIsComponent) { FoundConnectedNodes.Add(connector); } foreach (CyPhy.ConnectorComposition conn in connector.SrcConnections.ConnectorCompositionCollection) { if (topAssembly != null && !IsParent(conn, topAssembly)) continue; if (parent.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE || GetRefportOrParent((MgaConnection) conn.Impl, "src").ID == parent.ID) VisitConnector(conn.SrcEnds.Connector, parent); } foreach (CyPhy.ConnectorComposition conn in connector.DstConnections.ConnectorCompositionCollection) { if (topAssembly != null && !IsParent(conn, topAssembly)) continue; if (parent.ObjType != GME.MGA.Meta.objtype_enum.OBJTYPE_REFERENCE || GetRefportOrParent((MgaConnection)conn.Impl, "dst").ID == parent.ID) VisitConnector(conn.DstEnds.Connector, parent); } } }
private bool CallElaborator( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, bool expand = true) { bool result = false; try { this.Logger.WriteDebug("Elaborating model..."); var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter(); elaborator.Initialize(project); int verbosity = 128; result = elaborator.RunInTransaction(project, currentobj, selectedobjs, verbosity); this.Logger.WriteDebug("Elaboration is done."); } catch (Exception ex) { this.Logger.WriteError("Exception occurred in Elaborator : {0}", ex.ToString()); result = false; } return(result); }
private IMgaTraceability CallElaborator( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, bool expand = true) { bool result = false; try { // GMEConsole.Info.WriteLine("Elaborating model..."); var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter(); elaborator.Initialize(project); int verbosity = 128; //elaborator.UnrollConnectors = false; result = elaborator.RunInTransaction(project, currentobj, selectedobjs, verbosity); if (result == true) { return(elaborator.Traceability); } // GMEConsole.Info.WriteLine("Elaboration is done."); } catch (Exception ex) { GMEConsole.Error.WriteLine("Exception occurred in Elaborator : {0}", ex.ToString()); } throw new ApplicationException("Elaborator failed"); }
public void CAWithConnector() { MgaFCO currentobj = null; proj.PerformInTransaction(delegate { currentobj = (MgaFCO)proj.ObjectByPath["/@ComponentAssemblies/@Component Assembly"]; }); Utils.RunDSRefactorer(currentobj, new MgaFCO[] {}.ToList(), "DesignContainer"); proj.PerformInTransaction(delegate { var path = "/@NewDS__Component Assembly/@NewDC__Component Assembly"; var rootDC = (MgaModel)proj.ObjectByPath[path]; Assert.True(rootDC != null, String.Format("Could not find FCO with path '{0}'", path)); var fcos = rootDC.GetDescendantFCOs(proj.CreateFilter()).Cast <MgaFCO>().ToList(); Assert.Equal(6, fcos.Count); foreach (MgaFCO fco in fcos) { if (fco is MgaConnection) { MgaSimpleConnection conn = (MgaSimpleConnection)fco; Assert.NotNull(conn.Src); Assert.NotNull(conn.Dst); } } }); }
public void CopyMgaAndRunDesignImporter(string asmName) { //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + asmName + ".mga").Substring("MGA=".Length), true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx(proj.ProjectConnStr + asmName + ".mga", "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO componentAssembly = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + asmName); Assert.NotNull(componentAssembly); componentAssembly.DestroyObject(); var importer = new CyPhyDesignImporter.AVMDesignImporter(null, proj2); avm.Design design; using (StreamReader streamReader = new StreamReader(Path.Combine(AdmPath, asmName + ".adm"))) design = CyPhyDesignImporter.CyPhyDesignImporterInterpreter.DeserializeAvmDesignXml(streamReader); var ret = (ISIS.GME.Dsml.CyPhyML.Interfaces.DesignEntity)importer.ImportDesign(design, "ComponentAssemblies" == FolderName ? CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_CAS : CyPhyDesignImporter.AVMDesignImporter.DesignImportMode.CREATE_DS); } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { // TODO: Add your interpreter code gmeConsole.Out.WriteLine("Running Subtree Merge Utility ..."); string[] FileNames = null; DialogResult dr; using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.CheckFileExists = true; ofd.DefaultExt = "mga"; ofd.Multiselect = false; ofd.Filter = "mga files (*.mga)|*.mga|All files (*.*)|*.*"; dr = ofd.ShowDialog(); if (dr == DialogResult.OK) { FileNames = ofd.FileNames; } } if (dr == DialogResult.OK) { MgaGateway.PerformInTransaction(delegate { SubTreeMerge subTreeMerge = new SubTreeMerge(); subTreeMerge.gmeConsole = gmeConsole; subTreeMerge.merge(currentobj, FileNames[0]); }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false); return; } else { gmeConsole.Warning.WriteLine("Subtree Merge Utility cancelled"); return; } }
/// <summary> /// Call this function if a GME transaction is open. /// </summary> /// <param name="testBenchName"></param> /// <param name="interpreterOutputDir"></param> /// <param name="fco"></param> public void SaveSummaryReportJson(string interpreterOutputDir, MgaFCO fco) { // TODO: index result file! if (fco.Meta.Name == "TestBench" || fco.Meta.Name == "CFDTestBench" || fco.Meta.Name == "BallisticTestBench" || fco.Meta.Name == "BlastTestBench" || fco.Meta.Name == "CADTestBench") { CyPhy.TestBenchType tb = ISIS.GME.Dsml.CyPhyML.Classes.TestBenchType.Cast(fco as MgaObject); //AVM.DDP.MetaTBReport report = new AVM.DDP.MetaTBReport(); //string fullpathFileName = Path.Combine(interpreterOutputDir, "summary.testresults.json"); //if (File.Exists(fullpathFileName)) //{ // report = JsonConvert.DeserializeObject<AVM.DDP.MetaTBReport>(File.ReadAllText(fullpathFileName)); //} //report.GenerateSummary( // tb, // "summary.testresults.json", // interpreterOutputDir); // AVM.DDP.MetaTBManifest manifest = new AVM.DDP.MetaTBManifest(); // manifest.MakeManifest(tb, interpreterOutputDir); // manifest.Serialize(interpreterOutputDir); } }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } if (currentobj == null) { MessageBox.Show("Please select the subtree to be replaced (via merge) so that it is displayed in the main window."); return; } currentMgaProject = project; try { gmeConsole = new FlexConsole(FlexConsole.ConsoleType.GMECONSOLE, project); MgaGateway = new MgaGateway(project); Main(project, currentobj, selectedobjs, Convert(param)); } finally { MgaGateway = null; project = null; currentobj = null; selectedobjs = null; gmeConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
private void ElaborateModel(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { try { var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter(); elaborator.Logger = new GMELogger(project); //elaborator.Logger.AddWriter(Logger.Instance); var result = elaborator.RunInTransaction(project, currentobj, selectedobjs, param); if (result == false) { throw new ApplicationException("see elaborator log"); } if (this.result.Traceability == null) { this.result.Traceability = new META.MgaTraceability(); } if (elaborator.Traceability != null) { elaborator.Traceability.CopyTo(this.result.Traceability); } } catch (Exception e) { //Logger.Instance.AddLogMessage("Elaborator exception occurred: " + e.Message, Severity.Error); throw new Exception(e.Message); } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { GMEConsole = GMEConsole.CreateFromProject(project); GMEConsole.Out.WriteLine("Running the AddConnector interpreter..."); Boolean ownLogger = false; if (Logger == null) { ownLogger = true; Logger = new CyPhyGUIs.GMELogger(project, "AddConnector"); } GMEConsole.Out.WriteLine("\n======================================================================================================================================\n"); using (Logger) // Ensure Logger is disposed if there is an unexpected exception. MOT-84 { Logger.WriteInfo("Starting AddConnector."); AddConnector(currentobj, selectedobjs); Logger.WriteInfo("The AddConnector interpreter has finished."); } if (ownLogger) { Logger.Dispose(); Logger = null; } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { this.Logger.WriteInfo("Running Component Authoring interpreter."); // verify we are running in a component and that it is not an instance or library string return_msg; if (!CheckPreConditions(currentobj, out return_msg)) { this.Logger.WriteFailed(return_msg); return; } // assuming a component is open // stash off the project, currentobj and CurrentComponent parameters for use in the event handlers StashProject = project; StashCurrentObj = currentobj; StashCurrentComponent = CyPhyClasses.Component.Cast(currentobj); // use reflection to populate the dialog box objects PopulateDialogBox(); // To use the domain-specific API: // Create another project with the same name as the paradigm name // Copy the paradigm .mga file to the directory containing the new project // In the new project, install the GME DSMLGenerator NuGet package (search for DSMLGenerator) // Add a Reference in this project to the other project // Add "using [ParadigmName] = ISIS.GME.Dsml.[ParadigmName].Classes.Interfaces;" to the top of this file // if (currentobj.Meta.Name == "KindName") // [ParadigmName].[KindName] dsCurrentObj = ISIS.GME.Dsml.[ParadigmName].Classes.[KindName].Cast(currentobj); }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { MgaGateway = new MgaGateway(project); this.Logger = new CyPhyGUIs.GMELogger(project, this.GetType().Name); MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }, abort: false); } finally { if (Logger != null) { Logger.Dispose(); } MgaGateway = null; Logger = null; project = null; currentobj = null; selectedobjs = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public static void RunDSRefactorer(MgaFCO currentobj, List<MgaFCO> selected, String refactoredType) { // create interpreter type Type typeInterpreter = Type.GetTypeFromProgID("MGA.Interpreter.CyphyDesignSpaceRefactor"); IMgaComponentEx dsRefactorInterpreter = Activator.CreateInstance(typeInterpreter) as IMgaComponentEx; // empty selected object set Type typeMgaFCOs = Type.GetTypeFromProgID("Mga.MgaFCOs"); MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs; foreach (MgaFCO fco in selected) { selectedObjs.Append(fco); } // initialize interpreter dsRefactorInterpreter.Initialize(currentobj.Project); // automation means no UI element shall be shown by the interpreter dsRefactorInterpreter.ComponentParameter["automation"] = "true"; dsRefactorInterpreter.ComponentParameter["refactored_type_or_action"] = refactoredType; // do not write to the console dsRefactorInterpreter.ComponentParameter["console_messages"] = "off"; // do not expand nor collapse the model dsRefactorInterpreter.ComponentParameter["expanded"] = "true"; // call the formula evaluator and update all parameters starting from the current object dsRefactorInterpreter.InvokeEx(currentobj.Project, currentobj, selectedObjs, 16); }
public void RunFormulaEvaluator(MgaFCO currentobj, bool expanded = true) { // create formula evaluator type // FIXME: calling the elaborator is faster than calling the formula evaluator Type typeFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator"); IMgaComponentEx formulaEval = Activator.CreateInstance(typeFormulaEval) as IMgaComponentEx; // empty selected object set Type typeMgaFCOs = Type.GetTypeFromProgID("Mga.MgaFCOs"); MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs; // initialize formula evauator formulaEval.Initialize(Project); // automation means no UI element shall be shown by the interpreter formulaEval.ComponentParameter["automation"] = "true"; // do not write to the console formulaEval.ComponentParameter["console_messages"] = "off"; // do not expand nor collapse the model formulaEval.ComponentParameter["expanded"] = expanded ? "true" : "false"; // do not generate the post processing python scripts // FIXME: Why should we generate them ??? formulaEval.ComponentParameter["do_not_generate_post_processing"] = "true"; // call the formula evaluator and update all parameters starting from the current object formulaEval.InvokeEx(Project, currentobj, selectedObjs, 16); }
private void CheckParamValue(String nameDomainModel, String nameParameter, String valueExpected) { ModelOperation(delegate { var domainModel = compValueFlow.AllChildren .First(c => c.Name == nameDomainModel) .Impl as MgaModel; Assert.NotNull(domainModel); MgaFCO param = null; foreach (MgaFCO obj in domainModel.ChildFCOs) { if (obj.Name == nameParameter) { param = obj; break; } } Assert.NotNull(param); String attrValue = null; foreach (MgaAttribute attr in param.Attributes) { if (attr.Meta.Name == "Value") { attrValue = attr.StringValue; break; } } Assert.NotNull(attrValue); Assert.Equal(valueExpected, attrValue); }); }
public CyPhy.Parameter Create(MgaFCO parent) { if (typeof(CyPhy.CFDTestBench).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.CFDTestBench.Cast(parent)); } else if (typeof(CyPhy.TestBench).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.TestBench.Cast(parent)); } else if (typeof(CyPhy.CADTestBench).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.CADTestBench.Cast(parent)); } else if (typeof(CyPhy.BallisticTestBench).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.BallisticTestBench.Cast(parent)); } else if (typeof(CyPhy.BlastTestBench).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.BlastTestBench.Cast(parent)); } else if (typeof(CyPhy.ComponentAssembly).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.ComponentAssembly.Cast(parent)); } else if (typeof(CyPhy.Component).Name == parent.MetaBase.Name) { return Create(CyPhyClasses.Component.Cast(parent)); } else { throw new ArgumentException("Can't create parameter for " + parent.MetaBase.Name); } }
private MgaFCO ClonePort(MgaModel parent, MgaFCO oldPort) { Logger.WriteDebug("ClonePort: {0}", oldPort.AbsPath); GME.MGA.Meta.MgaMetaRole role = null; foreach (GME.MGA.Meta.MgaMetaRole roleItem in (parent.Meta as GME.MGA.Meta.MgaMetaModel).Roles) { if (roleItem.Kind.MetaRef == oldPort.MetaBase.MetaRef) { role = roleItem; break; } } var newPortFCO = parent.CopyFCODisp(oldPort, role); String lastGood = oldPort.ID; String iter = null; while (Traceability.TryGetMappedObject(lastGood, out iter) && lastGood != iter) { lastGood = iter; } Traceability.AddItem(newPortFCO.ID, lastGood); return(newPortFCO); }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { MgaGateway = new MgaGateway(project); MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }, abort: false); } finally { MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public bool CheckPreConditions(MgaFCO currentobj, out string message) { // check if the context is a Component if (currentobj == null || !(currentobj.Meta.Name == typeof(CyPhy.Component).Name || currentobj.Meta.Name == typeof(CyPhy.ComponentAssembly).Name)) { // this is a really bad situation we must return message = string.Format("Please open a Component or ComponentAssembly and run this tool from that context."); return(false); } else if (currentobj.IsInstance) { // there is no reason to run in an instance since it cannot be modified message = string.Format("This component cannot be modified because it is an instance."); return(false); } else if (currentobj.IsLibObject) { // there is no reason to run on a library object since it cannot be modified message = string.Format("This component cannot be modified because it is a library object."); return(false); } message = string.Format("Pre-Conditions met for running CAT"); return(true); }
public static IEnumerable<RuleFeedbackBase> CheckRule(MgaFCO context) { var result = new List<RuleFeedbackBase>(); CyPhyML.Component cyPhyMLComponent = ISIS.GME.Common.Utils.CreateObject<CyPhyMLClasses.Component>(context as MgaObject); Dictionary<string, List<CyPhyML.HasDescriptionAndGUID>> namePPMListMap = new Dictionary<string, List<CyPhyML.HasDescriptionAndGUID> >(); List<object> objectList = cyPhyMLComponent.AllChildren.ToList<object>(); foreach( CyPhyML.HasDescriptionAndGUID cyPhyMLHasDescriptionAndGUID in cyPhyMLComponent.AllChildren. Where(x => x.GetType().UnderlyingSystemType == typeof(CyPhyMLClasses.Parameter) || x.GetType().UnderlyingSystemType == typeof(CyPhyMLClasses.Property) || x.GetType().UnderlyingSystemType == typeof(CyPhyMLClasses.Metric)) ) { Type type = cyPhyMLHasDescriptionAndGUID.GetType(); string name = cyPhyMLHasDescriptionAndGUID.Name; if (!namePPMListMap.ContainsKey(name)) { namePPMListMap[name] = new List<CyPhyML.HasDescriptionAndGUID>(); } namePPMListMap[name].Add(cyPhyMLHasDescriptionAndGUID); } foreach (string name in namePPMListMap.Keys) { List<CyPhyML.HasDescriptionAndGUID> ppmList = namePPMListMap[name]; if (ppmList.Count > 1) { var genericRuleFeedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = "Name \"" + name + "\" not unique between Parameter, Property, and Metric children of Component \"" + cyPhyMLComponent.Name + "\"" }; result.Add(genericRuleFeedback); } } return result; }
public static IEnumerable <MgaSimpleConnection> GetRolesConnections(MgaFCO mgaFCO) { List <MgaFCO> baseClasses = GetBaseClasses(mgaFCO).ToList(); baseClasses.Add(mgaFCO); List <MgaFCO> baseClassesWProxies = new List <MgaFCO>(); baseClasses.ForEach(x => baseClassesWProxies.AddRange(x.ReferencedBy.Cast <MgaFCO>())); baseClassesWProxies.AddRange(baseClasses); //baseClasses.AddRange(GetBaseClasses(mgaFCO).Select(x => x.ReferencedBy).Cast<MgaFCO>()); foreach (MgaFCO item in baseClassesWProxies) { foreach (MgaConnPoint cp in item.PartOfConns) { MgaSimpleConnection simple = cp.Owner as MgaSimpleConnection; if (simple.MetaBase.Name == "Containment") { yield return(simple); } } } }
private void CallOldElaborator(MgaProject project, MgaFCO currentobj) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); this.Logger.WriteInfo("CyPhyElaborator 1.0 started"); try { Type typeElaborator = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyElaborate"); IMgaComponentEx oldElaborator = Activator.CreateInstance(typeElaborator) as IMgaComponentEx; Type typeMgaFCOs = Type.GetTypeFromProgID("Mga.MgaFCOs"); MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs; oldElaborator.Initialize(project); oldElaborator.ComponentParameter["automation"] = "true"; oldElaborator.ComponentParameter["console_messages"] = "off"; oldElaborator.ComponentParameter["expanded"] = "true"; sw.Start(); oldElaborator.InvokeEx(project, currentobj, selectedObjs, 128); this.Logger.WriteInfo("CyPhyElaborator 1.0 finished"); } catch (Exception ex) { this.Logger.WriteInfo("CyPhyElaborator 1.0 failed"); this.Logger.WriteDebug(ex.ToString()); } finally { sw.Stop(); this.Logger.WriteDebug("CyPhyElaborator 1.0 runtime: {0}", sw.Elapsed.ToString("c")); } }
public static IEnumerable<RuleFeedbackBase> OneAndOnlyOneDriver(MgaFCO context) { var result = new List<RuleFeedbackBase>(); var pet = CyPhyClasses.ParametricExploration.Cast(context); var cnt = pet.Children.ParameterStudyCollection.Count() + pet.Children.PCCDriverCollection.Count() + pet.Children.OptimizerCollection.Count(); if (cnt < 1) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("No driver defined, please add either a PCCDriver, Parameter Study or Optimizer.") }; result.Add(feedback); } else if (cnt > 1) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("The ParameterExploration-model has {0} drivers. There must only be one.", cnt) }; result.Add(feedback); } return result; }
public void InitializeEx( MgaProject project, MgaMetaPart meta, MgaFCO obj, IMgaCommonDecoratorEvents eventSink, ulong parentWnd) { try { Initialize(project, meta, obj); if (name != null) { IntPtr parentHwnd; unchecked { parentHwnd = (IntPtr)(int)parentWnd; } using (Graphics g = Graphics.FromHwnd(parentHwnd)) { Font font = new Font("Arial", 12f, GraphicsUnit.Pixel); LabelSize = g.MeasureString(name, font); } } } catch (Exception ex) { // sometimes the mgafco is inaccessible Trace.TraceWarning(ex.ToString().Replace('\n', '\t')); } }
/// <summary> /// Adds selected ports or pins to the selected connector. /// </summary> /// <param name="currentobj">Component that holds the ports/pins to be wrapped.</param> /// <param name="portList">List of all the selected ports to be moved into the selected connector.</param> /// <param name="conn">Connector where the selected pins are to be moved.</param> private void HandleOneConnectorSelected(MgaFCO currentobj, List <MgaFCO> portList, CyPhy.Connector conn) { int popCount = 0; int startY = GetGreatestCurrentConnectorY(conn); // Get the component var component = ISIS.GME.Dsml.CyPhyML.Classes.Component.Cast(currentobj); foreach (MgaFCO portOrPin in portList) { // Get the name of the selected port or pin string popName = portOrPin.Name; int pinX = 100; int pinY = startY + (125 * ++popCount); // Copy fields into a cloned port or pin MgaFCO clonedPortOrPin = ClonePort(conn.Impl as MgaModel, portOrPin); // Name it clonedPortOrPin.Name = popName; // Set coordinates SetFCOPosition(clonedPortOrPin, pinX, pinY); // Copy connections CopyPinConnections(component, portOrPin, clonedPortOrPin); // Delete the original port or pin portOrPin.DestroyObject(); } }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); Main(project, currentobj, selectedobjs, Convert(param)); } finally { MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public void BaseAssembly() { MgaFCO fcoAsm = null; fixture.proj.PerformInTransaction(delegate { var path = "/@ComponentAssemblies/@BaseAssembly"; fcoAsm = (MgaFCO)fixture.proj.get_ObjectByPath(path); Assert.True(fcoAsm != null, String.Format("Could not find {0} in {1}", path, fixture.proj.ProjectConnStr)); }); RunFormulaEvaluator(fcoAsm, "false"); fixture.proj.PerformInTransaction(delegate { var asm = CyPhyClasses.ComponentAssembly.Cast(fcoAsm); var outMetric = asm.Children.MetricCollection.Single(p => p.Name == "OutMetric"); Assert.Equal("100", outMetric.Attributes.Value); var outParamater = asm.Children.ParameterCollection.Single(p => p.Name == "OutParameter"); Assert.Equal("100", outParamater.Attributes.Value); Assert.Equal(1, asm.Children.ComponentRefCollection.Count()); Assert.Equal(0, asm.Children.ComponentCollection.Count()); }); }
public string[] RunFormulaEvaluator(MgaFCO currentobj, string automation = "true") { // create formula evaluator type Type typeFormulaEval = Type.GetTypeFromProgID("MGA.Interpreter.CyPhyFormulaEvaluator"); IMgaComponentEx formulaEval = Activator.CreateInstance(typeFormulaEval) as IMgaComponentEx; // empty selected object set Type typeMgaFCOs = Type.GetTypeFromProgID("Mga.MgaFCOs"); MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs; // initialize formula evaluator formulaEval.Initialize(fixture.proj); // automation means no UI element shall be shown by the interpreter formulaEval.ComponentParameter["automation"] = automation; // do not write to the console formulaEval.ComponentParameter["console_messages"] = "off"; // do not generate the post processing python scripts // FIXME: Why should we generate them ??? formulaEval.ComponentParameter["do_not_generate_post_processing"] = "true"; // call the formula evaluator and update all parameters starting from the current object formulaEval.InvokeEx(fixture.proj, currentobj, selectedObjs, 16); string[] numericLeafNodes = (string[])formulaEval.ComponentParameter["numericLeafNodes"]; return(numericLeafNodes); }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); MgaGateway.PerformInTransaction(delegate { Main(project, currentobj, selectedobjs, Convert(param)); }); } finally { if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
private void CallCAD( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { Type tCAD = Type.GetTypeFromProgID("MGA.Interpreter.CyPhy2CAD_CSharp"); if (tCAD == null) { GMEConsole.Info.WriteLine("CyPhy2CAD is not installed on your machine."); return; } ComComponent cyPhy2CAD = new ComComponent("MGA.Interpreter.CyPhy2CAD_CSharp"); //cyPhy2CAD.WorkflowParameters["prepIFab"] = "true"; cyPhy2CAD.Initialize(project); cyPhy2CAD.InterpreterConfig = cadSettings; // TODO cyPhy2CAD.MainParameters.config.prepIFab = true; //cyPhy2CAD.MainParameters.ConsoleMessages = ; cyPhy2CAD.MainParameters.Project = project; cyPhy2CAD.MainParameters.CurrentFCO = currentobj; cyPhy2CAD.MainParameters.SelectedFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); cyPhy2CAD.MainParameters.StartModeParam = param; cyPhy2CAD.MainParameters.OutputDirectory = this.OutputDirectory; cyPhy2CAD.MainParameters.ProjectDirectory = this.ProjectRootDirectory; cyPhy2CAD.Main(); this.componentParameters["results_zip_py"] = cyPhy2CAD.result.ZippyServerSideHook; }
public static void RunUdmInterpreter(MgaFCO currentobj, String ProgID) { // create interpreter type Type typeUdmInterpreter = Type.GetTypeFromProgID(ProgID); IMgaComponentEx udmInterpreter = Activator.CreateInstance(typeUdmInterpreter) as IMgaComponentEx; // empty selected object set Type typeMgaFCOs = Type.GetTypeFromProgID("Mga.MgaFCOs"); MgaFCOs selectedObjs = Activator.CreateInstance(typeMgaFCOs) as MgaFCOs; // initialize interpreter udmInterpreter.Initialize(currentobj.Project); // automation means no UI element shall be shown by the interpreter udmInterpreter.ComponentParameter["automation"] = "true"; // do not write to the console udmInterpreter.ComponentParameter["console_messages"] = "off"; // do not expand nor collapse the model udmInterpreter.ComponentParameter["expanded"] = "true"; // call the formula evaluator and update all parameters starting from the current object udmInterpreter.InvokeEx(currentobj.Project, currentobj, selectedObjs, 16); }
public void CallCyPhy2CADWithTransaction(MgaProject project, MgaFCO toplevelAssembly, int param) { if (GMEConsole == null) { GMEConsole = GMEConsole.CreateFromProject(project); } Dictionary <MgaFCO, MgaFCO> objectMap = new Dictionary <MgaFCO, MgaFCO>(); try { project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); handleEvents = false; GenerateCADAssemblyXml(project, toplevelAssembly, param); try { HighlightInTree(toplevelAssembly, 1); } catch (Exception e) { GMEConsole.Error.Write("Error during processing the model: " + e.Message); // Don't do anything, there won't be highlight } } finally { project.AbortTransaction(); handleEvents = true; } }
private void AddReferenceCoordinateSystemForAssemblyRoot(avm.Design ad_import, CyPhy.DesignEntity cyphy_container) { foreach (var root in ad_import.DomainFeature.OfType <avm.cad.AssemblyRoot>()) { CyPhyML.ComponentRef componentRef; if (idToComponentInstanceMap.TryGetValue(root.AssemblyRootComponentInstance, out componentRef)) { MgaFCO rcs = CreateChild((ISIS.GME.Common.Interfaces.Model)componentRef.ParentContainer, typeof(CyPhyML.ReferenceCoordinateSystem)); rcs.Name = "AssemblyRoot"; CyPhyML.ReferenceCoordinateSystem componentRcs = componentRef.Referred.Component.Children.ReferenceCoordinateSystemCollection.FirstOrDefault(); if (componentRcs == null) { componentRcs = CyPhyClasses.ReferenceCoordinateSystem.Create(componentRef.Referred.Component); } ((MgaModel)componentRef.ParentContainer.Impl).CreateSimpleConnDisp(((MgaMetaModel)componentRef.ParentContainer.Impl.MetaBase).RoleByName[typeof(CyPhyML.RefCoordSystem2RefCoordSystem).Name], rcs, (MgaFCO)componentRcs.Impl, null, (MgaFCO)componentRef.Impl); while (rcs.ParentModel.ID != cyphy_container.ID) { var oldrcs = rcs; rcs = CreateChild(rcs.ParentModel.ParentModel, typeof(CyPhyML.ReferenceCoordinateSystem)); rcs.Name = "AssemblyRoot"; ((MgaModel)rcs.ParentModel).CreateSimplerConnDisp(((MgaMetaModel)rcs.ParentModel.Meta).RoleByName[typeof(CyPhyML.RefCoordSystem2RefCoordSystem).Name], rcs, oldrcs); } } } }
public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (!enabled) { return; } try { MgaGateway = new MgaGateway(project); MgaGateway.BeginTransaction(transactiontype_enum.TRANSACTION_NON_NESTED); try { Main(project, currentobj, selectedobjs, Convert(param)); } finally { MgaGateway.AbortTransaction(); } } finally { MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public void FormulaTest() { var xmePath = Path.Combine(_exportModelDirectory, "FormulaTest", "InputModel.xme"); string mgaFilename = unpackXme(xmePath); IMgaProject project = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); project.OpenEx("MGA=" + mgaFilename, "CyPhyML", null); try { project.BeginTransactionInNewTerr(); try { MgaFCO fco = (MgaFCO)project.RootFolder.ObjectByPath["/@Imported_Components/@FormulaComp"]; Exception e = Assert.Throws(typeof(ApplicationException), () => CyPhyComponentExporter.CyPhyComponentExporterInterpreter.ExportComponentPackage(ISIS.GME.Dsml.CyPhyML.Classes.Component.Cast(fco))); Assert.True(e.Message.Contains("Value assignments for Component Parameters must come from outside the Component itself.")); fco = (MgaFCO)project.RootFolder.ObjectByPath["/@ComponentAssemblies/@ComponentAssembly/@Component"]; CyPhyComponentExporter.CyPhyComponentExporterInterpreter.ExportComponentPackage(ISIS.GME.Dsml.CyPhyML.Classes.Component.Cast(fco)); } finally { project.AbortTransaction(); } } finally { project.Close(true); } }
public CyPhy.Parameter Create(MgaFCO parent) { if (typeof(CyPhy.CFDTestBench).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.CFDTestBench.Cast(parent))); } else if (typeof(CyPhy.TestBench).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.TestBench.Cast(parent))); } else if (typeof(CyPhy.CADTestBench).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.CADTestBench.Cast(parent))); } else if (typeof(CyPhy.BallisticTestBench).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.BallisticTestBench.Cast(parent))); } else if (typeof(CyPhy.BlastTestBench).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.BlastTestBench.Cast(parent))); } else if (typeof(CyPhy.ComponentAssembly).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.ComponentAssembly.Cast(parent))); } else if (typeof(CyPhy.Component).Name == parent.MetaBase.Name) { return(Create(CyPhyClasses.Component.Cast(parent))); } else { throw new ArgumentException("Can't create parameter for " + parent.MetaBase.Name); } }
public void CopyMgaAndRunImporter(string tbName) { //proj.Save(proj.ProjectConnStr + asmName + ".mga", true); File.Copy(proj.ProjectConnStr.Substring("MGA=".Length), (proj.ProjectConnStr + tbName + ".mga").Substring("MGA=".Length), true); MgaProject proj2 = (MgaProject)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaProject")); proj2.OpenEx(proj.ProjectConnStr + tbName + ".mga", "CyPhyML", null); proj2.BeginTransactionInNewTerr(); try { MgaFCO oldTestBench = (MgaFCO)proj2.RootFolder.GetObjectByPathDisp("/@" + FolderName + "/@" + tbName + "|kind=TestBench"); Assert.NotNull(oldTestBench); oldTestBench.DestroyObject(); CyPhyML.TestBenchType testBench; using (StreamReader streamReader = new StreamReader(Path.Combine(AtmPath, tbName + ".atm"))) { avm.TestBench avmTestBench = OpenMETA.Interchange.AvmXmlSerializer.Deserialize <avm.TestBench>(streamReader); testBench = CyPhy2TestBenchInterchange.TestBenchInterchange2CyPhy.Convert(avmTestBench, proj2); } } finally { proj2.CommitTransaction(); if (Debugger.IsAttached) { proj2.Save(null, true); } proj2.Close(true); } }
//[CheckerRule("Modelica TB", Description = "Description is not mandatory.")] //[Tags("Modelica","Modelica 2")] //[ValidContext("AggregatePort")] public static IEnumerable<RuleFeedbackBase> CheckRule1(MgaFCO context) { return new List<RuleFeedbackBase> { new GenericRuleFeedback{FeedbackType = FeedbackTypes.Error, Message = "Error1"}, new GenericRuleFeedback{FeedbackType = FeedbackTypes.Error, Message = "Error2"}, new GenericRuleFeedback{FeedbackType = FeedbackTypes.Error, Message = "Error3"}, }; }
public static IEnumerable<RuleFeedbackBase> CheckTLSUT(MgaFCO context) { var result = new List<RuleFeedbackBase>(); var tsults = context.ChildObjects.OfType<MgaReference>().Where(x => x.Meta.Name == "TopLevelSystemUnderTest"); var count = tsults.Count(); if (count == 0) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = "There is no top level system under test object." }; result.Add(feedback); } else if (count == 1) { var referred = tsults.FirstOrDefault().Referred; if (referred == null) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = "Top level system under test reference cannot be null." }; result.Add(feedback); } else if (referred.Meta.Name != "DesignContainer") { var feedback = new GenericRuleFeedback { FeedbackType = FeedbackTypes.Warning, Message = "Top level system under test reference MUST point to a Design Container." }; result.Add(feedback); } } else { var feedback = new GenericRuleFeedback { FeedbackType = FeedbackTypes.Error, Message = "There is more than one top level system under test object." }; result.Add(feedback); } return result; }
public static IEnumerable<RuleFeedbackBase> SoTObjectsValid(MgaFCO context) { try { var result = new List<RuleFeedbackBase>(); // check for unsupported object types var unsupportedKinds = new List<string>(); unsupportedKinds.AddRange(new string[] { typeof(CyPhy.TopLevelSystemUnderTest).Name }); var fcos = (context as MgaModel) .ChildObjects .Cast<MgaFCO>() .Where(x => unsupportedKinds.Contains(x.Meta.Name)); foreach (var item in fcos) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("Context: {0} - {1}[{2}] is not supported", context.Name, item.Name, item.Meta.Name) }; feedback.InvolvedObjectsByRole.Add(context as IMgaFCO); result.Add(feedback); } return result; } catch (Exception ex) { var result = new List<RuleFeedbackBase>(); var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("Context: {0} - Exception: {1} {2}", context.Name, ex.Message, ex.StackTrace) }; feedback.InvolvedObjectsByRole.Add(context); result.Add(feedback); return result; } }
public void InvokeEx2(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { string projectPath = Path.GetDirectoryName(project.ProjectConnStr.Substring(4)); // skip mga= string projectName = Path.GetFileNameWithoutExtension(project.ProjectConnStr.Substring(4)); string cyphyFilename = project.ProjectConnStr.Substring(4); baseOutputDir = Path.Combine(projectPath, projectName + "_PRISMATIC"); GME.CSharp.GMEConsole console = GME.CSharp.GMEConsole.CreateFromProject(project); console.Out.WriteLine("Output directory is " + baseOutputDir); META_PATH = GetMetaPathValue(); if (!Directory.Exists(META_PATH)) { throw new ApplicationException("META_PATH='" + META_PATH + "' doesn't exist. Please install the META toolchain and restart GME."); } string metaPath = Path.Combine( META_PATH, "meta" ); if (!Directory.Exists(metaPath)) { throw new ApplicationException(metaPath + " doesn't exist"); } ensureDir(baseOutputDir); string CyPhyML_udm_xml_path = Path.Combine(metaPath, "CyPhyML_udm.xml"); if (!File.Exists(CyPhyML_udm_xml_path)) { CyPhyML_udm_xml_path = Path.Combine(metaPath, @"..\generated\CyPhyML\models\CyPhyML_udm.xml"); } string CyPhyML_xsd_path = Path.Combine(metaPath, "CyPhyML.xsd"); if (!File.Exists(CyPhyML_xsd_path)) { CyPhyML_xsd_path = Path.Combine(metaPath, @"..\generated\CyPhyML.xsd"); } console.Out.WriteLine("Extracting XML model..."); runProgram( Path.Combine(metaPath, @"..\bin\UdmCopy.exe"), new string[] { "-f", cyphyFilename, Path.Combine( baseOutputDir, projectName + ".xml" ), CyPhyML_udm_xml_path, CyPhyML_xsd_path } ); console.Out.WriteLine("Generating Prismatic files..."); runProgram( "C:\\Python26\\python.exe", new string[] { META_PATH + "\\bin\\Prismatic\\" + "cmc.py", Path.Combine( baseOutputDir, projectName + ".xml" ), baseOutputDir } ); console.Out.WriteLine("Running Prismatic..."); runProgram( "C:\\Python27\\python.exe", new string[] { baseOutputDir + "\\prismatic.py" }); console.Out.WriteLine("Prismatic work done."); }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { string[] fileNames = null; DialogResult dr; using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.CheckFileExists = true; ofd.DefaultExt = "design.adm"; ofd.Multiselect = true; ofd.Filter = "AVM design files (*.adm)|*.adm|All files (*.*)|*.*"; ofd.RestoreDirectory = true; if (project.ProjectConnStr.StartsWith("MGA=", true, System.Globalization.CultureInfo.InvariantCulture)) { ofd.InitialDirectory = Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)); } dr = ofd.ShowDialog(); if (dr == DialogResult.OK) { fileNames = ofd.FileNames; } } if (dr == DialogResult.OK) { Model[] result = null; MgaGateway.PerformInTransaction(delegate { var importer = new AVMDesignImporter(GMEConsole, project); result = importer.ImportFiles(fileNames, mode: AVMDesignImporter.DesignImportMode.CREATE_CA_IF_NO_DS_CONCEPTS); }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false); if (result.Length > 0 && GMEConsole.gme != null) { GMEConsole.gme.ShowFCO((MgaFCO)result[0].Impl); } return; } else { GMEConsole.Warning.WriteLine("Design Importer canceled"); return; } }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { string[] fileNames = null; DialogResult dr; using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.CheckFileExists = true; ofd.DefaultExt = "testbench.atm"; ofd.Multiselect = true; ofd.Filter = "AVM testbench files (*.atm)|*.atm|All files (*.*)|*.*"; dr = ofd.ShowDialog(); if (dr == DialogResult.OK) { fileNames = ofd.FileNames; } } if (dr == DialogResult.OK) { MgaGateway.PerformInTransaction(delegate { foreach (var fileName in fileNames) { using (var streamReader = new StreamReader(fileName)) { var avmTestBench = XSD2CSharp.AvmXmlSerializer.Deserialize<avm.TestBench>(streamReader); CyPhy2TestBenchInterchange.TestBenchInterchange2CyPhy.Convert(avmTestBench, project); } } }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: false); //if (result.Any() && GMEConsole.gme != null) //{ // GMEConsole.gme.ShowFCO((MgaFCO)result.First().Impl); //} return; } else { GMEConsole.Warning.WriteLine("TestBench Importer canceled"); return; } }
private void ManufacturingGeneration(MgaFCO currentobj) { if (currentobj.MetaBase.Name == "TestBench") { // DDP Generation CyPhy.TestBench tb = CyPhyClasses.TestBench.Cast(currentobj); var catlsut = tb.Children.ComponentAssemblyCollection.FirstOrDefault(); // should be an instance b/c elaborate was called earlier if (catlsut == null) { throw new Exception("There is no elaborated system under test component assembly in the model!"); } var design = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(catlsut); this.TestBenchName = tb.Name; this.AssemblyName = design.Name; design.SaveToFile(Path.Combine(this.OutputDirectory, this.TestBenchName + ".adm")); if (catlsut.Attributes.ConfigurationUniqueID.Contains("{")) this.ManufacturingManifestData.DesignID = catlsut.Attributes.ConfigurationUniqueID; else this.ManufacturingManifestData.DesignID = "{" + catlsut.Attributes.ConfigurationUniqueID + "}"; this.ManufacturingManifestData.Name = catlsut.Name; PartManufacturingGeneration(catlsut); } else if (currentobj.MetaBase.Name == "ComponentAssembly") { // DDP Generation CyPhy.ComponentAssembly assembly = CyPhyClasses.ComponentAssembly.Cast(currentobj); var design = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(assembly); this.AssemblyName = design.Name; this.TestBenchName = design.Name; design.SaveToFile(Path.Combine(this.OutputDirectory, this.TestBenchName + ".adm")); this.ManufacturingManifestData.DesignID = "{" + assembly.Attributes.ConfigurationUniqueID + "}"; this.ManufacturingManifestData.Name = assembly.Name; PartManufacturingGeneration(assembly); } else throw new NotImplementedException(); }
public static bool Run(string outputdirname, MgaProject project, MgaFCO testObj, bool copycomponents) { bool status = true; try { if (copycomponents) { CopyDirectory(Path.Combine(GetProjectDir(project),"components"), Path.Combine(outputdirname, "components")); } var interpreter = new CyPhy2CAD_CSharp.CyPhy2CAD_CSharpInterpreter(); interpreter.Initialize(project); var mainParameters = new CyPhyGUIs.InterpreterMainParameters(); var cadSettings = new CyPhy2CAD_CSharp.CyPhy2CADSettings(); cadSettings.OutputDirectory = outputdirname; cadSettings.AuxiliaryDirectory = ""; mainParameters.config = cadSettings; mainParameters.Project = project; mainParameters.CurrentFCO = testObj; mainParameters.SelectedFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); mainParameters.StartModeParam = 128; mainParameters.ConsoleMessages = false; mainParameters.ProjectDirectory = Path.GetDirectoryName(GetProjectDir(project)); mainParameters.OutputDirectory = outputdirname; interpreter.Main(mainParameters); } catch (Exception) { status = false; } finally { project.Close(); } return status; }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { string OutputBaseDir = (string)componentParameters["output_dir"]; SotConfig sotConfig = new SotConfig(); sotConfig.MultiJobRun = true; sotConfig.OriginalProjectFileName = project.ProjectConnStr.Substring("MGA=".Length); sotConfig.ProjectFileName = Path.Combine(OutputBaseDir, Path.GetFileName(sotConfig.OriginalProjectFileName)); // can't be in a tx and save the project project.AbortTransaction(); project.Save("MGA=" + sotConfig.ProjectFileName, true); project.BeginTransactionInNewTerr(transactiontype_enum.TRANSACTION_NON_NESTED); MgaGateway.PerformInTransaction(delegate { sotConfig.SoTID = currentobj.ID; }, transactiontype_enum.TRANSACTION_READ_ONLY); using (StreamWriter writer = new StreamWriter(Path.Combine(OutputBaseDir, "manifest.sot.json"))) { writer.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(sotConfig, Newtonsoft.Json.Formatting.Indented)); } string configsDir = Path.Combine(Path.GetDirectoryName((string)componentParameters["original_project_file"]), "config"); if (Directory.Exists(configsDir)) { var configs = Directory.EnumerateFiles(configsDir, "*xml").ToList(); string sotConfigDir = Path.Combine(OutputBaseDir, "config"); Directory.CreateDirectory(sotConfigDir); foreach (var config in configs) { File.Copy(config, Path.Combine(sotConfigDir, Path.GetFileName(config))); } } //componentParameters["labels"] = ""; //componentParameters["runCommand"] = ; //componentParameters["results_zip_py"] as string; // result.LogFileDirectory = Path.Combine(MainParameters.ProjectDirectory, "log"); // componentParameters["build_query"] as string; }
public Checker(MgaFCO model, MgaProject project, IMgaTraceability traceability = null, CyPhyGUIs.GMELogger logger = null) { Model = model; Project = project; if (logger != null) { this.Logger = logger; } else { GMEConsole = GMEConsole.CreateFromProject(project); } registeredRules = new ConcurrentDictionary<string, List<RuleDescriptor>>(); if (traceability == null) { this.Traceability = new META.MgaTraceability(); } else { this.Traceability = traceability; } }
/// <summary> /// Opens the project and find the CurrentObject /// Note: You must call SaveAndCloseProject(), which releases the taken semaphore. /// </summary> private void OpenProject() { criticalSection[this.ProjectConnStr].WaitOne(); // Always creating a new instance of MgaProject Type type = Type.GetTypeFromProgID("Mga.MgaProject"); this.Project = Activator.CreateInstance(type) as MgaProject; bool ro_mode; Trace.TraceInformation("Opening project {0}", this.ProjectConnStr); // Do NOT rely on ro_mode! this.Project.Open(this.ProjectConnStr, out ro_mode); try { var terr = this.Project.BeginTransactionInNewTerr(); // ALWAYS find object this.CurrentObj = this.Project.GetFCOByID(sotConfig.SoTID); currentObjectName = this.CurrentObj.Name; sotName = this.CurrentObj.RegistryValue["SoTUniqueName"]; if (string.IsNullOrEmpty(sotName)) { sotName = currentObjectName; } this.Project.AbortTransaction(); // FIXME: do we need this? //terr.Destroy(); } catch (COMException ex) { // FCO was not found Trace.TraceError(ex.ToString()); return; } }
private List<CyPhySoT.TestBench> GetMultiJobRunTestBenches(MgaFCO CurrentObj, string OutputDirectory) { var TestBenches = new List<CyPhySoT.TestBench>(); var testbench1 = new CyPhySoT.TestBench(); var workflowRef = CurrentObj .ChildObjects .OfType<MgaReference>() .FirstOrDefault(x => x.Meta.Name == "WorkflowRef"); string parameters = "{}"; MgaAtom task; if (workflowRef != null) { task = workflowRef .Referred .ChildObjects .OfType<MgaAtom>() .FirstOrDefault(x => x.Meta.Name == "Task"); parameters = task.StrAttrByName["Parameters"]; testbench1.ProgId = task.StrAttrByName["COMName"]; } else { testbench1.ProgId = "MGA.Interpreter.CyPhy2CAD_CSharp"; } testbench1.WorkflowParametersDict = new Dictionary<string, string>(); if (string.IsNullOrWhiteSpace(parameters) == false) { try { testbench1.WorkflowParametersDict = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(parameters); } catch (Exception ex) { Console.WriteLine(ex); Trace.TraceWarning(ex.ToString()); } } testbench1.OutputDirectory = OutputDirectory; if (Directory.Exists(testbench1.OutputDirectory) == false) { Directory.CreateDirectory(testbench1.OutputDirectory); } testbench1.Project = CurrentObj.Project; testbench1.CurrentObj = CurrentObj; testbench1.ParamInvoke = 0; testbench1.Name = CurrentObj.Name; TestBenches.Add(testbench1); var testbench2 = testbench1.MemberwiseClone(); testbench2.UpstreamTestBenches = new List<CyPhySoT.TestBench>(); testbench2.DownstreamTestBenches = new List<CyPhySoT.TestBench>(); testbench2.UpstreamTestBenches.Add(testbench1); testbench1.DownstreamTestBenches.Add(testbench2); TestBenches.Add(testbench2); testbench2.ProgId = "MGA.Interpreter.CyPhyPython"; var metaToPyScript = new Dictionary<string, string>() { {"CFDTestBench", "runOpenFoam.py"}, {"BlastTestBench", "runLSDyna.py"}, {"BallisticTestBench", "runCTH.py"}, }; testbench2.WorkflowParametersDict = new Dictionary<string, string>() { {"script_file", metaToPyScript[CurrentObj.Meta.Name]} }; return TestBenches; }
public void InvokeEx( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (project == null) { throw new ArgumentNullException("project"); } if (selectedobjs == null) { throw new ArgumentNullException("selectedobjs"); } this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE; try { GMEConsole = GMEConsole.CreateFromProject(project); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); this.GMEConsole.Clear(); System.Windows.Forms.Application.DoEvents(); this.InteractiveMode = this.Convert(param) != ComponentStartMode.GME_SILENT_MODE; this.Logger = new CyPhyGUIs.GMELogger(project, this.GetType().Name); this.Logger.GMEConsoleLoggingLevel = Properties.Settings.Default.bVerboseLogging ? CyPhyGUIs.SmartLogger.MessageType_enum.Debug : CyPhyGUIs.SmartLogger.MessageType_enum.Info; //this.Logger.WriteDebug("Hello debug"); //this.Logger.WriteError("Hello error {0} {1} {2}", 1, "string", true); //this.Logger.WriteInfo("Hello info"); //this.Logger.WriteWarning("Hello WriteWarning"); //this.Logger.WriteFailed("Hello WriteFailed"); //this.Logger.WriteSuccess("Hello WriteSuccess"); //this.Logger.WriteCheckFailed("Hello WriteCheckFailed"); //this.Logger.WriteCheckPassed("Hello WriteCheckPassed"); this.Logger.WriteInfo("Master Interpreter 2.0"); System.Windows.Forms.Application.DoEvents(); this.Logger.MakeVersionInfoHeader(); // control was held this.Process(currentobj); foreach (var filename in this.Logger.LogFilenames) { this.Logger.WriteInfo("Log file was generated here: <a href=\"file:///{0}\" target=\"_blank\">{1}</a>", Path.GetDirectoryName(filename), filename); } this.Logger.WriteInfo("Master Interpreter 2.0 finished"); } finally { this.Logger.Dispose(); System.Windows.Forms.Application.DoEvents(); if (MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GMEConsole = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
private void Process(MgaFCO currentobj) { if (currentobj == null) { this.Logger.WriteError("Context is invalid. This component can be executed only if a valid context is open in the main editor (e.g.: Test Bench, Component Assembly)."); return; } MgaGateway.PerformInTransaction(() => { this.Logger.WriteInfo("Processing {0} [{1}] model", currentobj.Name, currentobj.MetaBase.Name); }); using (var masterInterpreter = new CyPhyMasterInterpreterAPI(currentobj.Project, this.Logger)) { masterInterpreter.IsInteractive = this.InteractiveMode; this.Logger.WriteDebug("Interactive mode: {0}", masterInterpreter.IsInteractive); Rules.ContextCheckerResult[] contextCheckerResults = null; // check context var checkerSuccess = false; try { checkerSuccess = masterInterpreter.TryCheckContext(currentobj as MgaModel, out contextCheckerResults); } catch (ArgumentOutOfRangeException ex) { this.Logger.WriteDebug(ex.ToString()); this.Logger.WriteError(ex.Message); return; } List<Rules.ContextCheckerResult> sortedResults = contextCheckerResults.ToList(); // sort results Passed, Failed, then alphabetically based on message. sortedResults.Sort((x, y) => { return x.Success == y.Success ? x.Message.CompareTo(y.Message) : y.Success.CompareTo(x.Success); }); // Print Checker results MgaGateway.PerformInTransaction(() => { foreach (var result in sortedResults) { if (result.Success) { this.Logger.WriteCheckPassed(" <i><a href=\"mga:{0}\">{1}</a></i> {2}", result.Subject.ID, result.Subject.Name, result.Message); } else { this.Logger.WriteCheckFailed(" <i><a href=\"mga:{0}\">{1}</a></i> {2}", result.Subject.ID, result.Subject.Name, result.Message); } } }); if (sortedResults.Any(x => x.Success == false)) { this.Logger.WriteError("Context is invalid see messeges above. Please fix the problems."); bool controlWasHeld = false; int VK_CONTROL = 0x11; // if user held the control ignore the checker results ... for debugging purposes ONLY! if ((bool)((GetKeyState(VK_CONTROL) & 0x8000) == 0x8000)) { controlWasHeld = true; } if (controlWasHeld == false) { return; } else { this.Logger.WriteWarning("Bypassing checker results. This mode is strictly for debugging purposes."); } } if (checkerSuccess == false) { return; } // context is valid // show GUI for the user ConfigurationSelection selection = null; try { selection = masterInterpreter.ShowConfigurationSelectionForm(currentobj as MgaModel); MgaGateway.PerformInTransaction(() => { this.Logger.WriteDebug("MasterExe command: CyPhyMasterExe.exe \"{0}\" \"{1}\" \"{2}\"", currentobj.Project.ProjectConnStr, GMELightObject.ShortenAbsPath(currentobj.AbsPath), String.Join("\" \"", selection.SelectedConfigurations.Cast<IMgaFCO>().Select(f => GMELightObject.ShortenAbsPath(f.AbsPath)).ToArray())); }); } catch (ExecutionCanceledByUserException ex) { this.Logger.WriteWarning("Operation was canceled by user. {0}", ex.Message); return; } MasterInterpreterResult[] miResults = null; // Get a progress dialog using (var progressDialog = new ProgressDialog(masterInterpreter)) { masterInterpreter.MultipleConfigurationProgress += progressDialog.MultipleConfigurationProgressHandler; masterInterpreter.SingleConfigurationProgress += progressDialog.SingleConfigurationProgressHandler; if (masterInterpreter.IsInteractive) { progressDialog.ShowWithDisabledMainWindow(); } try { miResults = masterInterpreter.RunInTransactionWithConfig(selection); } catch (AnalysisModelInterpreterConfigurationFailedException ex) { this.Logger.WriteWarning("Operation was canceled by user. {0}", ex.Message); } catch (ExecutionCanceledByUserException ex) { this.Logger.WriteWarning("Operation was canceled by user. {0}", ex.Message); } } if (selection.OpenDashboard) { masterInterpreter.OpenDashboardWithChrome(); } masterInterpreter.WriteSummary(miResults); } }
private MgaFCOs ResolveConfiguration(MgaFCO configuration) { MgaFCOs results = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); this.ExecuteInTransaction(configuration, () => { if (configuration.MetaBase.Name == typeof(ISIS.GME.Dsml.CyPhyML.Interfaces.Configurations).Name) { MgaFilter filter = configuration.Project.CreateFilter(); filter.Kind = typeof(ISIS.GME.Dsml.CyPhyML.Interfaces.CWC).Name; foreach (MgaFCO cwc in (configuration as MgaModel).GetDescendantFCOs(filter)) { MgaFCO found = null; foreach (MgaSimpleConnection conn in cwc.PartOfConns) { if (conn.MetaBase.Name == typeof(ISIS.GME.Dsml.CyPhyML.Interfaces.Config2CA).Name) { if ((conn.Dst as MgaReference).Referred != null) { // pick the first non null exported configuration found = conn.Dst; break; } } } if (found != null) { results.Append(found); } else { results.Append(cwc); } }; } else if (configuration.MetaBase.Name == typeof(ISIS.GME.Dsml.CyPhyML.Interfaces.CWC).Name) { MgaFCO found = null; foreach (MgaSimpleConnection conn in configuration.PartOfConns) { if (conn.MetaBase.Name == typeof(ISIS.GME.Dsml.CyPhyML.Interfaces.Config2CA).Name) { if ((conn.Dst as MgaReference).Referred != null) { // pick the first non null exported configuration found = conn.Dst; break; } } } if (found != null) { results.Append(found); } else { results.Append(configuration); } } else if (configuration.MetaBase.Name == typeof(ISIS.GME.Dsml.CyPhyML.Interfaces.ComponentAssembly).Name) { results.Append(configuration); } else { this.Logger.WriteWarning("Not supported configuration type {0} [{1}]", configuration.Name, configuration.MetaBase.Name); } StringBuilder sbResolvedConfigs = new StringBuilder(); foreach (MgaFCO config in results) { sbResolvedConfigs.AppendFormat(" {0} [{1}]", config.Name, config.MetaBase.Name); } this.Logger.WriteDebug("Configuration {0} [{1}] was resolved to: {2}", configuration.Name, configuration.MetaBase.Name, sbResolvedConfigs); }); return results; }
public void Initialize( MgaProject project, MgaMetaPart meta, MgaFCO obj) { // only store temporarily, they might be unavailable later myobj = obj; mymetaobj = null; LastMetaKind = myobj.Meta.Name; // obtain the metaobject GetMetaFCO(meta, out mymetaobj); if (obj != null) { // concrete object name = myobj.Name; if (myobj.Meta.Name == "Task") { // task // get progid check whether it is already in the cache TaskProgId = myobj.StrAttrByName["COMName"]; if (interpreters.Keys.Contains(TaskProgId) == false) { // create an instance ComComponent task = new ComComponent(TaskProgId); interpreters.Add(TaskProgId, task); } // save parameters Parameters = myobj.StrAttrByName["Parameters"]; h = IconHeight; w = IconWidth; } else if (myobj.Meta.Name == "WorkflowRef") { // Workflow reference get the tasks // TODO: get those in the right order workflow.Clear(); MgaReference wfRef = myobj as MgaReference; Queue<string> items = new Queue<string>(); List<MgaAtom> tasks = new List<MgaAtom>(); List<MgaFCO> processed = new List<MgaFCO>(); if (wfRef.Referred != null) { tasks.AddRange(wfRef.Referred.ChildObjects.OfType<MgaAtom>()); MgaAtom StartTask = null; StartTask = tasks. Where(x => x.ExSrcFcos().Count() == 0). FirstOrDefault(); if (StartTask != null) { this.EnqueueTask(StartTask as MgaFCO); processed.Add(StartTask as MgaFCO); MgaFCO NextTask = StartTask.ExDstFcos().FirstOrDefault(); // avoid loops while (NextTask != null && processed.Contains(NextTask) == false) { processed.Add(NextTask as MgaFCO); this.EnqueueTask(NextTask); NextTask = NextTask.ExDstFcos().FirstOrDefault(); } } } h = IconHeight; if (workflow.Count > 0) { w = IconWidth * workflow.Count + TaskPadding * (workflow.Count - 1); } else { w = IconWidth; } } } else { // not a concreter object (maybe in part browser?) name = mymetaobj.DisplayedName; } // to handle color and labelColor settings in GME if (!GetColorPreference(out color, "color")) { color = Color.Black; } if (!GetColorPreference(out labelColor, "nameColor")) { labelColor = Color.Black; } // null them for sure // myobj = null; mymetaobj = null; }
protected void InitializeIconPaths(MgaFCO task) { string allIconPaths = new MgaRegistrar().get_IconPath(regaccessmode_enum.REGACCESS_BOTH); string projectDir = GetDirectoryFromConnStr(task.Project.ProjectConnStr); string paradigmDir = GetDirectoryFromConnStr(task.Project.ParadigmConnStr); if (!string.IsNullOrWhiteSpace(allIconPaths) && !string.IsNullOrWhiteSpace(projectDir) && !string.IsNullOrWhiteSpace(paradigmDir)) { allIconPaths = allIconPaths.Replace("$PROJECTDIR", projectDir); allIconPaths = allIconPaths.Replace("$PARADIGMDIR", paradigmDir); this.iconPaths = allIconPaths.Split(';').ToList(); } }
public void EnqueueTask(MgaFCO task) { if (this.iconPaths.Count == 0) { InitializeIconPaths(task); } string metaName = task.MetaBase.Name; if (metaName == "ExecutionTask") { TaskInfo taskInfo = new TaskInfo(metaName); SetTaskIconPath(taskInfo, EXECUTIONTASK_ICON_NAME); workflow.Enqueue(taskInfo); } else { workflow.Enqueue(new TaskInfo(task.StrAttrByName["COMName"], metaName)); } }
public void InitializeEx( MgaProject project, MgaMetaPart meta, MgaFCO obj, IMgaCommonDecoratorEvents eventSink, ulong parentWnd) { try { Initialize(project, meta, obj); if (name != null) { IntPtr parentHwnd; unchecked { parentHwnd = (IntPtr)(int)parentWnd; } using (Graphics g = Graphics.FromHwnd(parentHwnd)) { LabelSize = g.MeasureString(name, SystemFonts.DefaultFont); } } } catch (Exception ex) { // sometimes the mgafco is inaccessible Trace.TraceWarning(ex.ToString().Replace('\n','\t')); } }