/// <summary> /// Looks if a work-flow with a task is defined in testBench and if so, returns the ProgID defined /// in task. If the rules are not fulfilled an empty string is returned. /// </summary> /// <param name="testBench">Test-bench to look into.</param> /// <returns>ProgID for interpreter defined in task.</returns> public static List <CyPhy.TaskBase> GetTasksFromTestBench(CyPhy.TestBench testBench) { if (testBench.Children.WorkflowRefCollection.Count() == 1) { var workflowRef = testBench.Children.WorkflowRefCollection.FirstOrDefault(); if (workflowRef != null && workflowRef.Referred.Workflow != null) { var workflow = workflowRef.Referred.Workflow; var modelTasks = workflow.Children.TaskBaseCollection; List <CyPhy.TaskBase> orderedTasks = Enumerable.Repeat <CyPhy.TaskBase>(null, modelTasks.Count()).ToList(); Dictionary <CyPhy.TaskBase, int> tasks = new Dictionary <CyPhy.TaskBase, int>(); foreach (CyPhy.TaskBase task in modelTasks) { int index = GetTaskIndex(task, tasks); orderedTasks[index] = task; } if (orderedTasks[orderedTasks.Count - 1] == null) { throw new ApplicationException("Branching is not supported in Workflow " + workflow.Name); } return(orderedTasks); } } throw new ApplicationException(String.Format("TestBench {0} must have exactly one WorkflowRef", testBench.Name)); }
public static HashSet <CyPhyML.Component> getCyPhyMLComponentSet(CyPhyML.TestBench cyPhyMLTestBench) { HashSet <CyPhyML.Component> cyPhyMLComponentSet = new HashSet <CyPhyML.Component>(); foreach (CyPhyML.TopLevelSystemUnderTest cyPhyMLTopLevelSystemUnderTest in cyPhyMLTestBench.Children.TopLevelSystemUnderTestCollection) { CyPhyML.DesignEntity cyPhyMLDesignEntity = cyPhyMLTopLevelSystemUnderTest.Referred as CyPhyML.DesignEntity; if (cyPhyMLDesignEntity is CyPhyML.ComponentAssembly) { cyPhyMLComponentSet.UnionWith(getCyPhyMLComponentSet(cyPhyMLDesignEntity as CyPhyML.ComponentAssembly)); } } foreach (CyPhyML.ComponentAssembly cyPhyMLComponentAssembly in cyPhyMLTestBench.Children.ComponentAssemblyCollection) { if ((cyPhyMLComponentAssembly.Impl as MgaFCO).MetaRole.Name != "TopLevelSystemUnderTest") { continue; } cyPhyMLComponentSet.UnionWith(getCyPhyMLComponentSet(cyPhyMLComponentAssembly)); } return(cyPhyMLComponentSet); }
public string ExportToFile(CyPhy.TestBench tb, String s_outFolder) { // Elaborate first // CallElaborator(tb.Impl.Project, tb.Impl as MgaFCO, null, 128, true); var avmTestBench = CyPhy2TestBenchInterchange.CyPhy2TestBenchInterchange.Convert(tb); var s_outFilePath = String.Format("{0}\\{1}.atm", s_outFolder, Safeify(tb.Name)); OpenMETA.Interchange.AvmXmlSerializer.SaveToFile(Path.GetFullPath(Path.Combine(s_outFolder, Safeify(tb.Name) + ".atm")), avmTestBench); CheckForDuplicateIDs(avmTestBench); return(s_outFilePath); }
private static IEnumerable <RuleFeedbackBase> checkRulesWorkFlow(CyPhy.TestBench testBench) { var result = new List <RuleFeedbackBase>(); if (testBench.Children.WorkflowRefCollection.Count() != 1) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("Test-bench must have exactly one workflow {0}.", testBench.Name) }; feedback.InvolvedObjectsByRole.Add(testBench.Impl as IMgaFCO); result.Add(feedback); } else { var workflowRef = testBench.Children.WorkflowRefCollection.FirstOrDefault(); if (workflowRef != null && workflowRef.Referred.Workflow == null) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("Workflow reference is null: {0}.", workflowRef.Name) }; feedback.InvolvedObjectsByRole.Add(workflowRef.Impl as IMgaFCO); result.Add(feedback); } else { var workflow = workflowRef.Referred.Workflow; if (workflow.Children.TaskCollection.Count() < 1) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("Workflow must have at least one task: {0}.", workflow.Name) }; feedback.InvolvedObjectsByRole.Add(workflow.Impl as IMgaFCO); result.Add(feedback); } } } return(result); }
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(); } }
private void Visit(CyPhyInterfaces.TestBench testBench) { if (testBench.Children.ComponentAssemblyCollection.Count() == 0) { Logger.WriteError("No valid component assembly in testbench {0}", testBench.Name); return; } foreach (var componentAssembly in testBench.Children.ComponentAssemblyCollection) { Visit(componentAssembly); } foreach (var testComponent in testBench.Children.TestComponentCollection) { Visit(testComponent); } }
public void visit(CyPhy.TestBench testbench) { Logger.WriteDebug("visit(CyPhy.TestBench): {0}", testbench.Path); foreach (var tlsut in testbench.Children.TopLevelSystemUnderTestCollection) { if (tlsut is CyPhy.ComponentAssembly) { visit(tlsut as CyPhy.ComponentAssembly); } else { throw new NotSupportedException(String.Format("Top-Level System Under Test of kind {0} is not supported", tlsut.Impl.MetaBase.Name)); } } foreach (var ca in testbench.Children.ComponentAssemblyCollection) { visit(ca); } }
/// <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") { CyPhy.TestBench tb = ISIS.GME.Dsml.CyPhyML.Classes.TestBench.Cast(fco as MgaObject); AVM.DDP.MetaTBManifest manifest = new AVM.DDP.MetaTBManifest(); manifest.MakeManifest(tb, interpreterOutputDir); manifest.Serialize(interpreterOutputDir); } else if (fco.Meta.Name == "CADTestBench") { var tb = ISIS.GME.Dsml.CyPhyML.Classes.CADTestBench.Cast(fco as MgaObject); AVM.DDP.MetaTBManifest manifest = new AVM.DDP.MetaTBManifest(); manifest.MakeManifest(tb, interpreterOutputDir); manifest.Serialize(interpreterOutputDir); } }
public static TestBench Convert(ISIS.GME.Dsml.CyPhyML.Interfaces.TestBench tb) { if (tb == null) { throw new ArgumentNullException("tb"); } // TODO: Generate ID //var componentConnectorTargetMapping = new Dictionary<CyPhy.Connector, ComponentConnectorInstance>(); var componentConnectorTargetMapping = new Dictionary <CyPhy.Connector, object>(); //var componentValueflowTargetMapping = new Dictionary<CyPhy.ValueFlowTarget, ContainerPrimitivePropertyInstance>(); // Note: its is object because it contains: ContainerPrimitivePropertyInstance AND ComponentPrimitivePropertyInstance (TestComponent) var componentValueflowTargetMapping = new Dictionary <CyPhy.ValueFlowTarget, object>(); var vftIdCache = new Dictionary <CyPhy.ValueFlowTarget, String>(); var avmTestBench = new TestBench { Name = tb.Name }; #region Process ComponentAssembly | DesignContainer var systemUnderTest = tb.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); if (systemUnderTest != null && systemUnderTest.Referred != null) { var wrapper = new TestBenchPrimitiveWrapper(systemUnderTest.AllReferred); if (wrapper.Primitive != null) { var avmTopLevelSystemUnderTest = new TopLevelSystemUnderTest() { // Note: DesignContainers have no ConfigurationUniqueID DesignID = wrapper.ConfigurationUniqueID, // TODO: Check if null IDinSourceModel = wrapper.ID.ToString() }; SetLayoutData(avmTopLevelSystemUnderTest, systemUnderTest.Impl); #region Process TopLevelSystemUnderTest parameters foreach (var parameter in wrapper.ParameterCollection) { DataTypeEnum xDataType; if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType)) { continue; } /* * var avmPrimitivePropertyInstance = new ContainerPrimitivePropertyInstance() * { * IDinSourceModel = parameter.Attributes.ID.ToString(), * Value = new Value * { * DataType = xDataType, * DataTypeSpecified = true, * DimensionType = DimensionTypeEnum.Scalar, * DimensionTypeSpecified = true, * Dimensions = parameter.Attributes.Dimension, * ID = Guid.NewGuid().ToString("D"), * //parameter.Guid.ToString("D") * } * }; * * //SetLayoutData(avmPrimitivePropertyInstance, parameter.Impl); * * componentValueflowTargetMapping[parameter] = avmPrimitivePropertyInstance; * vftIdCache[parameter] = avmPrimitivePropertyInstance.Value.ID; * avmTopLevelSystemUnderTest.PropertyInstance.Add(avmPrimitivePropertyInstance); */ } #endregion #region Process TopLevelSystemUnderTest properties foreach (var property in wrapper.PropertyCollection) { DataTypeEnum xDataType; if (!ConvertCyPhyDataTypeEnum(property.Attributes.DataType, out xDataType)) { continue; } /* * var avmPrimitivePropertyInstance = new ContainerPrimitivePropertyInstance() * { * IDinSourceModel = property.Attributes.ID.ToString(), * Value = new Value * { * DataType = xDataType, * DataTypeSpecified = true, * DimensionType = DimensionTypeEnum.Scalar, * DimensionTypeSpecified = true, * Dimensions = property.Attributes.Dimension, * ID = Guid.NewGuid().ToString("D"), //property.Guid.ToString("D") * } * }; * * //SetLayoutData(avmPrimitivePropertyInstance, property.Impl); * * avmTopLevelSystemUnderTest.PropertyInstance.Add(avmPrimitivePropertyInstance); * componentValueflowTargetMapping[property] = avmPrimitivePropertyInstance; * vftIdCache[property] = avmPrimitivePropertyInstance.Value.ID; */ } #endregion #region Process TopLevelSystemUnderTest ModelicaConnector foreach (var mc in wrapper.ModelicaConnectorCollection) { /* * var avmPortInstance = new ContainerPortInstance * { * ID = string.IsNullOrEmpty(mc.Attributes.ID) ? GetOrSetID(mc) : mc.Attributes.ID, * NameInSourceModel = mc.Name, * }; * * modelicaConnectorCache[mc] = avmPortInstance; * avmTopLevelSystemUnderTest.PortInstance.Add(avmPortInstance); */ } #endregion // TODO: Temprary solution for Zsolt no difference between ModelicaConnector and Connector in the atm file. // => Impossible to import #region Process TopLevelSystemUnderTest Connectors foreach (var cc in wrapper.ConnectorCollection) { // Now it is ContainerPortInstance => Should be changed in the future. /* * var avmPortInstance = new ContainerPortInstance * { * ID = EnsureComponentIdAttribute(cc), * NameInSourceModel = cc.Name, * }; * * componentConnectorTargetMapping[cc] = avmPortInstance; * avmTopLevelSystemUnderTest.PortInstance.Add(avmPortInstance); */ } #endregion avmTestBench.TopLevelSystemUnderTest = avmTopLevelSystemUnderTest; } } #endregion #region Process TestComponents foreach (var testComponent in tb.Children.TestComponentCollection) { var avmComponentInstance = new avm.ComponentInstance() { Name = testComponent.Name, ID = EnsureComponentIdAttribute(testComponent).ToString(), ComponentID = testComponent.Guid.ToString("D") }; #region Component connectors foreach (var connector in testComponent.Children.ConnectorCollection) { var connectorId = EnsureComponentIdAttribute(connector); var avmComponentConnectorInstance = new avm.ComponentConnectorInstance { IDinComponentModel = connector.Attributes.ID, ID = avmComponentInstance.ID + '-' + connectorId, }; avmComponentInstance.ConnectorInstance.Add(avmComponentConnectorInstance); if (!componentConnectorTargetMapping.ContainsKey(connector)) { componentConnectorTargetMapping[connector] = avmComponentConnectorInstance; } } #endregion #region Process testComponent parameters foreach (var parameter in testComponent.Children.ParameterCollection) { DataTypeEnum xDataType; if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType)) { continue; } var avmPrimitivePropertyInstance = new ComponentPrimitivePropertyInstance() { IDinComponentModel = parameter.Attributes.ID.ToString(), Value = new Value { DataType = xDataType, DataTypeSpecified = true, DimensionType = DimensionTypeEnum.Scalar, DimensionTypeSpecified = true, Dimensions = parameter.Attributes.Dimension, ID = Guid.NewGuid().ToString("D"), //parameter.Guid.ToString("D") } }; //SetLayoutData(avmPrimitivePropertyInstance, parameter.Impl); componentValueflowTargetMapping[parameter] = avmPrimitivePropertyInstance; vftIdCache[parameter] = avmPrimitivePropertyInstance.Value.ID; avmComponentInstance.PrimitivePropertyInstance.Add(avmPrimitivePropertyInstance); } #endregion #region Process testComponent properties foreach (var property in testComponent.Children.PropertyCollection) { DataTypeEnum xDataType; if (!ConvertCyPhyDataTypeEnum(property.Attributes.DataType, out xDataType)) { continue; } var avmPrimitivePropertyInstance = new ComponentPrimitivePropertyInstance() { IDinComponentModel = property.Attributes.ID.ToString(), Value = new Value { DataType = xDataType, DataTypeSpecified = true, DimensionType = DimensionTypeEnum.Scalar, DimensionTypeSpecified = true, Dimensions = property.Attributes.Dimension, ID = Guid.NewGuid().ToString("D"), //property.Guid.ToString("D") } }; //SetLayoutData(avmPrimitivePropertyInstance, property.Impl); avmComponentInstance.PrimitivePropertyInstance.Add(avmPrimitivePropertyInstance); componentValueflowTargetMapping[property] = avmPrimitivePropertyInstance; vftIdCache[property] = avmPrimitivePropertyInstance.Value.ID; } #endregion SetLayoutData(avmComponentInstance, testComponent.Impl); avmTestBench.TestComponent.Add(avmComponentInstance); } // TODO: not use dynamic, it is just a walkaround while Adam is on vacation #region Process ConnectorCompositions foreach (var cc in tb.Children.ConnectorCompositionCollection) { var src = cc.SrcEnds.Connector; var dst = cc.DstEnds.Connector; if (src != null && dst != null) { dynamic avmSrc; dynamic avmDst; if (componentConnectorTargetMapping.ContainsKey(src) && componentConnectorTargetMapping.ContainsKey(dst)) { avmSrc = componentConnectorTargetMapping[src]; avmDst = componentConnectorTargetMapping[dst]; try { avmSrc.ConnectorComposition.Add(avmDst.ID); } catch (RuntimeBinderException e) { avmSrc.PortMap.Add(avmDst.ID); } } } } #endregion #endregion #region Process Testbench parameters foreach (var parameter in tb.Children.ParameterCollection) { DataTypeEnum xDataType; if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType)) { continue; } var avmParameter = new Parameter { ID = parameter.Attributes.ID, Name = parameter.Name, Notes = parameter.Attributes.Description, Value = new Value { DataType = xDataType, DataTypeSpecified = true, DimensionType = DimensionTypeEnum.Scalar, DimensionTypeSpecified = true, Dimensions = parameter.Attributes.Dimension, ID = Guid.NewGuid().ToString("D"), //parameter.Guid.ToString("D") } }; SetLayoutData(avmParameter, parameter.Impl); #region Set value expressions / Derived values if (parameter.SrcConnections.ValueFlowCollection.Any()) { var vft = parameter.SrcConnections.ValueFlowCollection.First().SrcEnds.ValueFlowTarget; String idVft = null; // ContainerPrimitivePropertyInstance cppi = null; dynamic cppi; if (componentValueflowTargetMapping.TryGetValue(vft, out cppi)) { idVft = cppi.Value.ID; } else { //idVft = GetOrSetID(vft); } avmParameter.Value.ValueExpression = new DerivedValue { ValueSource = idVft }; } else { // FixedValue or ParametricValue???? //var avmFixedValue = new FixedValue() { // Value = parameter.Attributes.Value //}; var rangeParts = (parameter.Attributes.Range == null || !parameter.Attributes.Range.Contains("..")) ? new[] { "", "" } : parameter.Attributes.Range.Split(new[] { ".." }, StringSplitOptions.RemoveEmptyEntries); if (rangeParts.Count() != 2) { rangeParts = new[] { "", "" } } ; var avmParametricValue = new ParametricValue { AssignedValue = new FixedValue { Value = parameter.Attributes.Value }, Default = new FixedValue { Value = parameter.Attributes.DefaultValue }, Maximum = new FixedValue { Value = rangeParts[1] }, Minimum = new FixedValue { Value = rangeParts[0] }, }; avmParameter.Value.ValueExpression = avmParametricValue; vftIdCache[parameter] = avmParameter.Value.ID; } #endregion avmTestBench.Parameter.Add(avmParameter); } #endregion #region Process Testbench metrics foreach (var metric in tb.Children.MetricCollection) { var avmMetric = new Metric { Name = metric.Name, Notes = metric.Attributes.Description }; SetLayoutData(avmMetric, metric.Impl); #region Derived values // Metric is derived only if (metric.SrcConnections.ValueFlowCollection.Any()) { var vft = metric.SrcConnections.ValueFlowCollection.First().SrcEnds.ValueFlowTarget; String idVft = null; // ContainerPrimitivePropertyInstance cppi = null; dynamic cppi; if (componentValueflowTargetMapping.TryGetValue(vft, out cppi)) { idVft = cppi.Value.ID; } else { //idVft = GetOrSetID(vft); } avmMetric.Value.ValueExpression = new DerivedValue { ValueSource = idVft }; } #endregion avmTestBench.Metric.Add(avmMetric); } #endregion #region Process Testbench Environments (modelica models) foreach (var env in tb.Children.EnvironmentCollection) { var avmModelicaModel = new avm.modelica.ModelicaModel { Name = env.Name, Author = env.Attributes.Author, Class = env.Attributes.Class, Notes = env.Attributes.Notes, UsesResource = env.Attributes.FilePathWithinResource, }; #region Process modelica connectors foreach (var mc in env.Children.ModelicaConnectorCollection) { var avmModelicaConnector = new avm.modelica.Connector { Name = mc.Name, Class = mc.Attributes.Class, Definition = mc.Attributes.Definition, Notes = mc.Attributes.DefinitionNotes, ID = string.IsNullOrEmpty(mc.Attributes.ID) ? GetOrSetID(mc) : mc.Attributes.ID, //= mc.Attributes.InstanceNotes, Locator = mc.Attributes.Locator, }; avmModelicaModel.Connector.Add(avmModelicaConnector); SetLayoutData(avmModelicaConnector, mc.Impl); } #endregion avmTestBench.TestStructure.Add(avmModelicaModel); SetLayoutData(avmModelicaModel, env.Impl); } #endregion #region Process Valueflows/set valueexpressions // Note: dynamic because of the Testcomponent Properties/Parameters foreach (var vf in tb.Children.ValueFlowCollection) { var srcValueFlow = vf.SrcEnds.ValueFlowTarget; var dstValueFlow = vf.DstEnds.ValueFlowTarget; if (componentValueflowTargetMapping.ContainsKey(dstValueFlow)) { dynamic dstPair = componentValueflowTargetMapping[dstValueFlow]; dstPair.Value.ValueExpression = new avm.DerivedValue { ValueSource = vftIdCache[srcValueFlow] }; } } #endregion #region Process PortCompositions foreach (var pc in tb.Children.PortCompositionCollection) { var src = pc.SrcEnds.ModelicaConnector; var dst = pc.DstEnds.ModelicaConnector; /* * if (src != null & dst != null) * { * ContainerPortInstance avmSrc; * ContainerPortInstance avmDst; * if (modelicaConnectorCache.ContainsKey(src)) * { * avmSrc = modelicaConnectorCache[src]; * avmSrc.PortMap.Add(dst.Attributes.ID); * } * else if (modelicaConnectorCache.ContainsKey(dst)) * { * avmDst = modelicaConnectorCache[dst]; * avmDst.PortMap.Add(src.Attributes.ID); * } * } */ } #endregion #region Process Workflows var workflowRef = tb.Children.WorkflowRefCollection.FirstOrDefault(); if (workflowRef != null) { var referred = workflowRef.Referred; if (referred != null && referred != null) { var workflow = referred.Workflow; var avmWorkflow = new Workflow { Name = workflow.Name, }; avmTestBench.Workflow = avmWorkflow; SetLayoutData(avmWorkflow, workflowRef.Impl); var allTasks = workflow.Children.TaskBaseCollection.ToList(); // Get the first task var currentTask = allTasks.FirstOrDefault(x => !x.SrcConnections.FlowCollection.Any()); if (currentTask != null) { do { // Create avm workflow tasks if (currentTask is CyPhy.Task) { var cyphyTask = (CyPhy.Task)currentTask; var avmTask = new InterpreterTask { Name = cyphyTask.Name, COMName = cyphyTask.Attributes.COMName, Parameters = cyphyTask.Attributes.Parameters }; avmWorkflow.Task.Add(avmTask); SetLayoutData(avmTask, cyphyTask.Impl); } else if (currentTask is CyPhy.ExecutionTask) { var cyphyTask = (CyPhy.ExecutionTask)currentTask; var avmTask = new ExecutionTask { Name = cyphyTask.Name, Description = cyphyTask.Attributes.Description, Invocation = cyphyTask.Attributes.Invocation, //TODO: Ask adam about these: // = cyphyTask.Attributes.Parameters // = cyphyTask.Attributes.PostProcess // = cyphyTask.Attributes.PreProcess }; SetLayoutData(avmTask, cyphyTask.Impl); avmWorkflow.Task.Add(avmTask); } else { // ToDo: Give a warning break; } // Next edge var nextFlow = currentTask.DstConnections.FlowCollection.FirstOrDefault(); // No more outgoing edge if (nextFlow == null) { break; } currentTask = nextFlow.DstEnds.TaskBase; // No element at the end of the edge // ToDo: Give a warning } while (currentTask != null); } } } #endregion #region Process Settings foreach (var settings in tb.Children.SolverSettingsCollection) { var intervalMethod = AvmModelicaIntervalMethodMapping.FirstOrDefault(x => x.Item1 == settings.Attributes.IntervalMethod); var jobManagerToolSelection = AvmModelicaJobManagerToolSelectionMapping.FirstOrDefault(x => x.Item1 == settings.Attributes.JobManagerToolSelection); var avmSettings = new avm.modelica.SolverSettings { IntervalLength = settings.Attributes.IntervalLength, IntervalLengthSpecified = true, // TODO: Give warning IntervalMethod = intervalMethod != null?intervalMethod.Item2:avm.modelica.IntervalMethod.IntervalLength, // TODO: Give warning JobManagerToolSelection = jobManagerToolSelection != null?jobManagerToolSelection.Item2:avm.modelica.JobManagerToolSelection.Dymola_latest, JobManagerToolSelectionSpecified = true, NumberOfIntervals = settings.Attributes.NumberOfIntervals, NumberOfIntervalsSpecified = true, Solver = settings.Attributes.Solver.ToString(), StartTime = settings.Attributes.StartTime, StartTimeSpecified = true, StopTime = settings.Attributes.StartTime, StopTimeSpecified = true, Tolerance = settings.Attributes.Tolerance, ToleranceSpecified = true, ToolSpecificAnnotations = settings.Attributes.ToolSpecificAnnotations }; avmTestBench.Settings.Add(avmSettings); } #endregion return(avmTestBench); }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { if (currentobj.Meta.Name == "TestBench") { CyPhy.TestBench tb = ISIS.GME.Common.Utils.CreateObject <CyPhyClasses.TestBench>(currentobj as MgaObject); //var sut = tb.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); //String s_sutName = sut.Name; CyPhy.ComponentAssembly sut = null; foreach (CyPhy.ComponentAssembly ca in tb.Children.ComponentAssemblyCollection) { if ((ca.Impl as MgaFCO).get_RegistryValue("ElaboratedModel") != "") { sut = ca; } } if (sut != null) { var dm = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(sut); //dm = MakeFakeModel(); //String json = dm.Serialize(); String json = XSD2CSharp.AvmXmlSerializer.Serialize(dm); int json_len = json.Length; dm.SaveToFile(Path.Combine(OutputDirectory, dm.Name + ".adm")); Complexity.Design cd = METADesignInterchange2ComplexityLib.METADesign2Complexity.Design2Complexity(dm); Dictionary <string, string> dCSV_output = cd.SerializeToCSVFormat(); foreach (KeyValuePair <string, string> kvp in dCSV_output) { String s_filePath = Path.Combine(OutputDirectory, kvp.Key); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s_filePath)) { sw.Write(kvp.Value); } } string mainPythonFilename = Path.Combine(OutputDirectory, "ComplexityMain.py"); string mainCmdFilename = Path.Combine(OutputDirectory, "RunComplexityEvaluator.cmd"); using (StreamWriter writer = new StreamWriter(mainPythonFilename)) { writer.WriteLine(CyPhyComplexity.Properties.Resources.ComplexityMain); } using (StreamWriter writer = new StreamWriter(mainCmdFilename)) { writer.WriteLine("call \"{0}\"", META_PATH_PYTHON_ACTIVATE); writer.WriteLine("python {0} Components.csv Connections.csv 1", mainPythonFilename); //writer.WriteLine(CyPhyComplexity.Properties.Resources.RunComplexityEvaluator); } if (dCSV_output.Count == 2) { result.RunCommand = "RunComplexityEvaluator.cmd"; } GMEConsole.Info.WriteLine( "Result files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>.", Path.GetFullPath(OutputDirectory)); } } }
private void CopyOverPostProcessingScripts(string outputDirectory, CyPhy.TestBench testBench) { string outputPostProcDir = Path.Combine(outputDirectory, "PostProcessing"); List <string> postProcFileNames = new List <string>(); foreach (var postProc in testBench.Children.PostProcessingCollection) { Directory.CreateDirectory(outputPostProcDir); var scriptFilePath = postProc.Attributes.ScriptPath; if (string.IsNullOrWhiteSpace(scriptFilePath)) { continue; } if (Path.IsPathRooted(scriptFilePath) == false) // if path starts with / it is rooted. Use ./ or nothing { scriptFilePath = Path.Combine(this.mainParameters.ProjectDirectory, scriptFilePath); } if (File.Exists(scriptFilePath)) { // Copy postScript file FileInfo postScript = new FileInfo(scriptFilePath); string destFile = Path.Combine(outputPostProcDir, postScript.Name); File.Copy(postScript.FullName, destFile, true); // META-3580 postProcFileNames.Add(Path.GetFileNameWithoutExtension(postScript.Name)); // If common folder exist copy entire folder. DirectoryInfo commonSrc = new DirectoryInfo(Path.Combine(postScript.DirectoryName, "common")); DirectoryInfo commonTarget = new DirectoryInfo(Path.Combine(outputPostProcDir, "common")); if (commonSrc.Exists && commonTarget.Exists == false) { commonTarget.Create(); CopyFilesRecursively(commonSrc, commonTarget); } } } // META-3580 if (postProcFileNames.Any()) { StringBuilder sb = new StringBuilder(); sb.AppendLine("# Generated file using the META tools"); sb.AppendLine("# Exposes all get_metrics functions for external usage"); sb.AppendLine(); // import all post processing files foreach (var postScriptFileName in postProcFileNames) { sb.AppendFormat("import {0}", postScriptFileName); sb.AppendLine(); } sb.AppendLine(); // expose get_metrics functions sb.AppendFormat("post_processing_modules = [{0}]", string.Join(", ", postProcFileNames)); sb.AppendLine(); sb.AppendLine(); File.WriteAllText(Path.Combine(outputPostProcDir, "__init__.py"), sb.ToString(), Encoding.UTF8); } }
private ModelConfig GenerateModelConfig( string outputDirectory, CyPhy.TestBench testBench, List <string> includeLibs) { Modelica.SolverSettings solver = new Modelica.SolverSettings(testBench.Children.SolverSettingsCollection.FirstOrDefault()); ModelConfig modelConfig = new ModelConfig() { model_name = "CyPhy.TestBenches." + testBench.Name, result_file = testBench.Name, model_file_name = "package.mo", verification_model_name = "CyPhy.TestBenches.verif_" + testBench.Name }; if (solver != null) { modelConfig.experiment.StartTime = solver.StartTime.ToString(); modelConfig.experiment.StopTime = solver.StopTime.ToString(); if (solver.Tolerance > 0) { modelConfig.experiment.Tolerance = solver.Tolerance.ToString(); } if (solver.UsesNumberOfIntervals) { modelConfig.experiment.IntervalMethod = "NumberOfIntervals"; if (solver.NumberOfIntervals > 0) { modelConfig.experiment.NumberOfIntervals = solver.NumberOfIntervals.ToString(); } } else { modelConfig.experiment.IntervalMethod = "Interval"; modelConfig.experiment.Interval = solver.IntervalLength.ToString(); } modelConfig.experiment.Algorithm.Dymola = solver.DymolaSolver; modelConfig.experiment.Algorithm.OpenModelica = solver.OpenModelicaSolver; modelConfig.experiment.Algorithm.JModelica = solver.JModelicaSolver; modelConfig.experiment.ToolSelection = solver.ToolSelection; } modelConfig.lib_package_paths.Add("../Libraries"); modelConfig.MSL_version = "3.2"; foreach (var libPath in includeLibs) { var library = ModelicaLibrary.GetLibraryFromPath(libPath); if (library.Name == "Modelica") { modelConfig.MSL_version = library.Version; } else { modelConfig.lib_package_names.Add(library.Name); } } var model_config_filename = Path.Combine(outputDirectory, "model_config.json"); using (StreamWriter writer = new StreamWriter(model_config_filename)) { var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject( modelConfig, Newtonsoft.Json.Formatting.Indented); writer.WriteLine(jsonString); } return(modelConfig); }
public override void TraverseTestBench(CyPhy.TestBenchType testBenchBase) { CyPhy.TestBench testBench = testBenchBase as CyPhy.TestBench; if (testBench == null) { testBench = CyPhyClasses.TestBench.Cast(testBenchBase.Impl); } base.TraverseTestBench(testBenchBase); //AnalysisID = testBench.ID; // R.O. added 11/15/2016, because the MSD_CAD.xme/TestBench_Valid was failing because the schema for CADAssmbly.xml requires // that ComponentID be set for Metrics/Metric attributes. For Mass, CenterOfGravity, BoundingBox, and Interference, // the metric applies to the entire assembly; therefore, we will use the top-level assembly as the ComponentID. var catlsut = testBench.Children.ComponentAssemblyCollection.FirstOrDefault(); // should be an instance b/c elaborate was called earlier if (catlsut == null) { // This check occurs earlier in ProcessCAD(), but will repeat here in case someone changes the code to not // test this earlier. throw new Exception("There is no elaborated system under test component assembly in the model!"); } // "|1" is set in other places in the code for the top-level assembly. Search on "|" to see those places. // If someone changes to another system ( different suffix than "|1") and does not change the following // line, then the CreateAssembly program will throw an exception. This will be caught by the build tests // (e.g. MSD_CAD.xme/TestBench_Valid). string topLevelAssemblyComponentInstanceID_temp = catlsut.Attributes.ConfigurationUniqueID + "|" + "1"; // CADComputations Metrics foreach (var conn in testBench.Children.CADComputation2MetricCollection) { CyPhy.CADComputationType cadcomputation = conn.SrcEnds.CADComputationType; TBComputation tbcomputation = new TBComputation(); tbcomputation.MetricID = conn.DstEnds.Metric.ID; if (cadcomputation is CyPhy.CenterOfGravity) { tbcomputation.ComponentID = topLevelAssemblyComponentInstanceID_temp; tbcomputation.RequestedValueType = (cadcomputation as CyPhy.CenterOfGravity).Attributes.CADComputationRequestedValue.ToString(); tbcomputation.ComputationType = TBComputation.Type.CENTEROFGRAVITY; } else if (cadcomputation is CyPhy.BoundingBox) { tbcomputation.ComponentID = topLevelAssemblyComponentInstanceID_temp; tbcomputation.RequestedValueType = (cadcomputation as CyPhy.BoundingBox).Attributes.CADComputationRequestedValue.ToString(); tbcomputation.ComputationType = TBComputation.Type.BOUNDINGBOX; } else if (cadcomputation is CyPhy.InterferenceCount) { tbcomputation.ComponentID = topLevelAssemblyComponentInstanceID_temp; tbcomputation.RequestedValueType = "Scalar"; tbcomputation.ComputationType = TBComputation.Type.INTERFERENCECOUNT; } else if (cadcomputation is CyPhy.Mass) { tbcomputation.ComponentID = topLevelAssemblyComponentInstanceID_temp; tbcomputation.RequestedValueType = "Scalar"; tbcomputation.ComputationType = TBComputation.Type.MASS; } this.StaticAnalysisMetrics.Add(tbcomputation); } // PointCoordinate Metrics foreach (var metric in testBench.Children.MetricCollection) { List <CyPhy.Point> points_list = new List <CyPhy.Point>(); foreach (var pt in metric.SrcConnections.PointCoordinates2MetricCollection) { points_list.Add(pt.SrcEnds.Point); } foreach (var pt in metric.DstConnections.PointCoordinates2MetricCollection) { points_list.Add(pt.DstEnds.Point); } if (points_list.Any()) { if (points_list.Count() > 1) { Logger.Instance.AddLogMessage("Metric should not be connected to multiple Point datums in a test bench.", Severity.Error); } CyPhy.Point point = points_list.First(); PointMetricTraversal traverser = new PointMetricTraversal(point); if (traverser.portsFound.Count() == 1) { TBComputation tbcomputation = new TBComputation(); tbcomputation.ComputationType = TBComputation.Type.POINTCOORDINATES; tbcomputation.MetricID = metric.ID; tbcomputation.RequestedValueType = "Vector"; tbcomputation.Details = (traverser.portsFound.First() as CyPhy.Point).Attributes.DatumName; tbcomputation.ComponentID = CyPhyClasses.Component.Cast(traverser.portsFound.First().ParentContainer.ParentContainer.Impl).Attributes.InstanceGUID; tbcomputation.MetricName = metric.Name; StaticAnalysisMetrics.Add(tbcomputation); } } } // Post Processing Blocks foreach (var postprocess in testBench.Children.PostProcessingCollection) { PostProcessScripts.Add(postprocess.Attributes.ScriptPath); } }
private string 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")); foreach (var wf_item in tb.Children.WorkflowRefCollection) { string TB_child_item_name = wf_item.Name; if (wf_item.Kind == "WorkflowRef") // not needed { var workflow_item = wf_item.ReferencedBy; // look for child task... foreach (var task_item in wf_item.Referred.Workflow.Children.TaskCollection) { string TaskName = task_item.Name; //wkflow_param = (task_item.Attributes.Parameters).ToLower(); //Grab parameter name -- which 'type' of test bench wkflow_param = task_item.Attributes.Parameters; } } } // End RB 7/17/13 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; 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(); } return(wkflow_param); }
/// <summary> /// Call this within a transaction. /// </summary> /// <param name="originalSubject"></param> /// <param name="singleFco"></param> /// <param name="OutputSubDir"></param> public void UpdateResultsJson( MgaFCO singleFco, string OutputSubDir) { string jsonFile = Path.Combine(Path.GetDirectoryName(this.m_filename), "results", "results.metaresults.json"); AVM.DDP.MetaResults results = null; bool createdNew; using (System.Threading.Mutex jsonFileMutex = new System.Threading.Mutex(false, "results_metaresults_mutex", out createdNew)) { jsonFileMutex.WaitOne(); try { if (File.Exists(jsonFile)) { string content = ""; using (StreamReader reader = new StreamReader(jsonFile)) { content = reader.ReadToEnd(); } results = JsonConvert.DeserializeObject <AVM.DDP.MetaResults>(content); // TODO: remove broken links } else { results = new AVM.DDP.MetaResults(); } AVM.DDP.MetaResults.Result thisResult = new AVM.DDP.MetaResults.Result(); thisResult.Summary = MakeRelativePath( Path.GetDirectoryName(jsonFile), Path.Combine(OutputSubDir, AVM.DDP.MetaTBManifest.TESTBENCH_FILENAME)).Replace('\\', '/'); thisResult.Time = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"); thisResult.TestBench = singleFco.RegistryValue["TestBenchUniqueName"] + ".testbench.json"; if (singleFco.Meta.Name == typeof(CyPhy.TestBench).Name || singleFco.Meta.Name == typeof(CyPhy.ParametricExploration).Name || singleFco.Meta.Name == typeof(CyPhy.TestBenchSuite).Name) { CyPhy.TestBench testBench = null; if (singleFco.Meta.Name == typeof(CyPhy.TestBench).Name) { testBench = ISIS.GME.Dsml.CyPhyML.Classes.TestBench.Cast(singleFco); } else if (singleFco.Meta.Name == typeof(CyPhy.ParametricExploration).Name) { var pet = ISIS.GME.Dsml.CyPhyML.Classes.ParametricExploration.Cast(singleFco); testBench = pet.Children.TestBenchRefCollection.FirstOrDefault().Referred.TestBench; } else if (singleFco.Meta.Name == typeof(CyPhy.TestBenchSuite).Name) { var pet = ISIS.GME.Dsml.CyPhyML.Classes.TestBenchSuite.Cast(singleFco); testBench = pet.Children.TestBenchRefCollection.FirstOrDefault().Referred.TestBench; } var tlsut = testBench.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); if (tlsut != null) { if (tlsut.Referred.ComponentAssembly != null) { var cfg = tlsut.Referred.ComponentAssembly; thisResult.Design = cfg.Name + ".metadesign.json"; var cid = cfg.Attributes.ConfigurationUniqueID; //this.ConfigurationUniqueID = cid; if (string.IsNullOrWhiteSpace(cid)) { cid = Guid.NewGuid().ToString("B"); cfg.Attributes.ConfigurationUniqueID = cid; } if (!string.IsNullOrEmpty(cid)) { try { Guid guid = new Guid(cid); thisResult.DesignID = guid.ToString("B"); } catch (System.FormatException ex) { Trace.TraceError("{0} is not a vaild GUID.", cid); Trace.TraceError(ex.ToString()); } } } } } results.Results.Add(thisResult); var dirname = Path.GetDirectoryName(jsonFile); if (Directory.Exists(dirname) == false) { Directory.CreateDirectory(dirname); } using (StreamWriter writer = new StreamWriter(jsonFile)) { writer.WriteLine(JsonConvert.SerializeObject(results, Newtonsoft.Json.Formatting.Indented)); } } finally { jsonFileMutex.ReleaseMutex(); jsonFileMutex.Dispose(); } } }