private string ExportToFile(CyPhy.TestBenchType testBench, string outputDirectory) { var topLevelSystem = testBench.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); if (topLevelSystem != null) { var design = topLevelSystem.Referred.DesignEntity; if (design != null) { return(ExportToFile(design, outputDirectory)); } } else { var tlsut = (CyPhy.DesignEntity)testBench.AllChildren .Where(x => ((IMgaFCO)x.Impl).MetaRole.Name == "TopLevelSystemUnderTest" || ((IMgaFCO)x.Impl).MetaRole.Name == x.Impl.MetaBase.Name + "TopLevelSystemUnderTest") .FirstOrDefault(); if (tlsut != null) { return(ExportToFile(tlsut, outputDirectory)); } } throw new NotSupportedException("No TopLevelSystemUnderTest found"); }
/// <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 TestBenchTypeProcessor(CyPhy.TestBenchType testBenchType) { this.testBenchType = testBenchType; this.OriginalSystemUnderTest = testBenchType.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); // HACK: used by PET, SoT and CyPhy2Modelica_v2 [old code] this.GetInvokedObject().RegistryValue["TestBenchUniqueName"] = this.testBenchType.Name; }
public override void Expand(CyPhy.ComponentAssembly configuration) { this.Configuration = configuration; if (this.OriginalSystemUnderTest.Referred.DesignEntity.ID == configuration.ID) { this.expandedTestBenchType = this.testBenchType; } else { // create temp folder for test bench CyPhy.Testing testing = CyPhyClasses.Testing.Cast(this.testBenchType.ParentContainer.Impl); var tempFolderName = AnalysisModelProcessor.GetTemporaryFolderName(this.testBenchType.Impl); CyPhy.Testing tempFolder = testing.Children.TestingCollection.FirstOrDefault(x => x.Name == tempFolderName); if (tempFolder == null) { tempFolder = CyPhyClasses.Testing.Create(testing); tempFolder.Name = tempFolderName; this.AddToTraceabilityAndTemporary(tempFolder.Impl, testing.Impl, recursive: false); } // copy test bench var tempCopy = (tempFolder.Impl as MgaFolder).CopyFCODisp(this.testBenchType.Impl as MgaFCO); // fix name tempCopy.Name = AnalysisModelProcessor.GetTemporaryObjectName(this.testBenchType.Impl, configuration.Impl); this.AddToTraceabilityAndTemporary(tempCopy, this.testBenchType.Impl); // set expanded property to the expanded element this.expandedTestBenchType = CyPhyClasses.TestBenchType.Cast(tempCopy); var tlsut = this.expandedTestBenchType.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); // switch references try { // redirect SUT var switcher = new ReferenceSwitcher.ReferenceSwitcherInterpreter(); switcher.SwitchReference(configuration.Impl as MgaFCO, tlsut.Impl as IMgaReference); } catch (Exception ex) { // handle failures for this (use case we can lose ports/connections/ // what if something is an instance/subtype/readonly etc... throw new AnalysisModelExpandFailedException("ReferenceSwitcher failed.", ex); } // redirect TIPs this.SwitchAllTipReferences(); } }
public string GetParameterValue(CyPhy.TestBenchType testBench, string paramname) { //var param = testBench.Children.ParameterCollection.Where(p => p.Name == paramname); // R. Owens, 5/11/2017 Make case insentive var param = testBench.Children.ParameterCollection.Where(p => p.Name.Equals(paramname, StringComparison.CurrentCultureIgnoreCase)); if (param.Any()) { return(param.First().Attributes.Value); } return(null); }
public bool SaveTestBench(CyPhy.TestBenchType testBenchType) { string testBenchFileFullPath = this.UpdateTestBenchJson(testBenchType.Impl as MgaFCO); string testBenchFile = Path.Combine(".", Path.GetFileName(Path.GetDirectoryName(testBenchFileFullPath)), Path.GetFileName(testBenchFileFullPath)).Replace('\\', '/'); if (this.Project.TestBenches.Contains(testBenchFile) == false) { this.Project.TestBenches.Add(testBenchFile); } return(true); }
public void SaveTestBenchManifest(string designName, string configurationName, CyPhy.TestBenchType expandedTestBenchType, string outputDir, CyPhy.TestBenchType originalTestBenchType, DateTime analysisStartTime) { if (expandedTestBenchType == null) { throw new ArgumentNullException("expandedTestBenchType"); } if (originalTestBenchType == null) { expandedTestBenchType = originalTestBenchType; } SaveTestBenchManifest(designName, configurationName, originalTestBenchType.Name, expandedTestBenchType, outputDir, analysisStartTime); }
public void SaveTestBenchManifest(string outputDirectory, CyPhy.TestBenchType testBenchType) { if (testBenchType == null) { throw new ArgumentNullException(); } if (outputDirectory == null) { throw new ArgumentNullException(); } AVM.DDP.MetaTBManifest manifest = new AVM.DDP.MetaTBManifest(); manifest.MakeManifest(testBenchType, outputDirectory); manifest.Serialize(outputDirectory); }
// RB 8/16/13 public void TraverseTestBenchForComponentExport(MgaFCO currentobj, string OutputDirectory, string ProjectDirectory) { string type = currentobj.MetaBase.Name; if (type != "TestBench" && type != "BallisticTestBench" && type != "BlastTestBench") { GMEConsole.Info.WriteLine("ERROR: " + type + " != TestBench or BlastTestBench or BallisticTestBench"); return; } //CyPhy.TestBench tb = CyPhyClasses.TestBench.Cast(currentobj); // DY: META-1971 CyPhy.TestBenchType tb = CyPhyClasses.TestBenchType.Cast(currentobj); var catlsut = tb.Children.ComponentAssemblyCollection.FirstOrDefault(); if (catlsut == null) { throw new Exception("There is no elaborated system under test component assembly in the model!"); } ComponentIndex compindex = new ComponentIndex(); //create index TraverseComponentAssemblyForComponentExport(compindex, catlsut, OutputDirectory, ProjectDirectory); }
// META-2987 private void GenerateCADParameterMapping(CyPhy.TestBenchType testBench, string outputDir, List <object> cadParamList) { foreach (var parameter in testBench.Children.ParameterCollection) { List <CyPhy.CADParameter> vftFound = new List <CyPhy.CADParameter>(); List <CyPhy.ValueFlowTarget> vftVisited = new List <CyPhy.ValueFlowTarget>(); FindValueFlowTargets(parameter, vftFound, vftVisited); foreach (var cadParam in vftFound) { CyPhy2CAD_CSharp.TestBenchModel.TBCadParameterMapping cadParameterMapping = new TestBenchModel.TBCadParameterMapping(cadParam, parameter.Name); if (!String.IsNullOrEmpty(cadParameterMapping.ComponentInstanceGUID)) { cadParamList.Add(cadParameterMapping); } } } if (cadParamList.Any()) { string mappingFileContent = Newtonsoft.Json.JsonConvert.SerializeObject(cadParamList); File.WriteAllText(Path.Combine(outputDir, "CADParamTestBenchMapping.json"), mappingFileContent, new UTF8Encoding(false)); } // generate testbench_manifest.json if it does not exist if (true /*!File.Exists(Path.Combine(outputDir, "testbench_manifest.json"))*/) { AVM.DDP.MetaTBManifest tbManifest = new AVM.DDP.MetaTBManifest(); tbManifest.MakeManifest(testBench, outputDir); tbManifest.Serialize(outputDir); } }
public PET(CyPhyGUIs.IInterpreterMainParameters parameters, CyPhyGUIs.GMELogger logger) { this.Logger = logger; this.pet = CyPhyClasses.ParametricExploration.Cast(parameters.CurrentFCO); this.outputDirectory = parameters.OutputDirectory; this.testBench = pet.Children.TestBenchRefCollection.FirstOrDefault().Referred.TestBenchType; this.PCCPropertyInputDistributions = new Dictionary<string, string>(); // Determine type of driver of the Parametric Exploration if (this.pet.Children.PCCDriverCollection.Count() == 1) { this.theDriver = DriverType.PCC; this.driverName = "PCCDriver"; } else if (this.pet.Children.OptimizerCollection.Count() == 1) { this.theDriver = DriverType.Optimizer; this.driverName = "Optimizer"; } else if (this.pet.Children.ParameterStudyCollection.Count() == 1) { this.theDriver = DriverType.ParameterStudy; this.driverName = "ParameterStudy"; } }
public void AddAllTasks( CyPhy.TestBenchType testBenchType, IEnumerable <global::META.ComComponent> interpreters, string relativePathToProjectDir) { Contract.Requires(testBenchType != null); Contract.Requires(interpreters != null); var workflowRef = testBenchType.Children .WorkflowRefCollection .ToList(); if (workflowRef.Count == 1 && workflowRef[0].AllReferred != null) { var workflow = workflowRef[0].Referred.Workflow; var allTasks = workflow.Children.TaskBaseCollection; var startTask = allTasks .Where(x => x.AllSrcConnections.Count() == 0) .FirstOrDefault(); CyPhy.TaskBase nextTask = startTask; int regularTaskIndex = 0; int regularTaskCount = interpreters.Count(); var processed = new List <CyPhy.TaskBase>(); while (nextTask != null && processed.Contains(nextTask) == false) { processed.Add(nextTask); if (nextTask.Impl.MetaBase.Name == (typeof(CyPhy.Task).Name)) { if (regularTaskIndex < regularTaskCount) { var currTask = interpreters.ElementAt(regularTaskIndex++); if (currTask.result != null && currTask.result.RunCommand != null) { var step = new Step(); step.Invocation = currTask.result.RunCommand; this.Steps.Add(step); } } } else if (nextTask.Impl.MetaBase.Name == (typeof(CyPhy.ExecutionTask).Name)) { CyPhy.ExecutionTask executionTask = ISIS.GME.Dsml.CyPhyML.Classes.ExecutionTask.Cast(nextTask.Impl); var step = new Step(); step.Description = executionTask.Attributes.Description; // %project_dir% is relative path to MgaExtensions.MgaExtensions.GetProjectDirectoryPath(testBenchType.Impl.Project) step.Invocation = Regex.Replace(executionTask.Attributes.Invocation, "%project_dir%", relativePathToProjectDir, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); step.PreProcess = executionTask.Attributes.PreProcess; step.PostProcess = executionTask.Attributes.PostProcess; var splitStrings = new string[] { Environment.NewLine, "\n" }; foreach (var parameterValue in executionTask.Attributes.Parameters.Split(splitStrings, StringSplitOptions.RemoveEmptyEntries)) { Parameter parameter = new Parameter(); parameter.Name = parameterValue; step.Parameters.Add(parameter); } this.Steps.Add(step); } var flow = nextTask.DstConnections.FlowCollection.FirstOrDefault(); if (flow == null) { nextTask = null; } else { nextTask = flow.DstEnds.TaskBase; } } } }
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); } }
public void GenerateCode(CyPhy.TestBenchRef testBenchRef, string testBenchOutputDir) { this.testBench = testBenchRef.Referred.TestBenchType; this.testBenchOutputDir = testBenchOutputDir; var config = new PETConfig.Component() { parameters = new Dictionary<string, PETConfig.Parameter>(), unknowns = new Dictionary<string, PETConfig.Parameter>(), details = new Dictionary<string, string>() }; config.details["directory"] = testBenchOutputDir; this.config.components.Add(testBenchRef.Name, config); foreach (var parameter in testBench.Children.ParameterCollection) { var sourcePath = GetSourcePath((MgaReference)testBenchRef.Impl, (MgaFCO)parameter.Impl); if (sourcePath != null) { config.parameters.Add(parameter.Name, new PETConfig.Parameter() { source = sourcePath }); } } foreach (var metric in testBench.Children.MetricCollection) { config.unknowns.Add(metric.Name, new PETConfig.Parameter() { }); } if (this.testBench is CyPhy.TestBench) { var interpreterProgID = Rules.Global.GetInterpreterProgIDFromTestBench(this.testBench as CyPhy.TestBench); if (interpreterProgID == "MGA.Interpreter.CyPhyFormulaEvaluator") { // FIXME: does this still work this.SimpleCalculation(); } } }
public override void TraverseTestBench(CyPhy.TestBenchType testBenchBase) { CyPhy.BlastTestBench testBench = testBenchBase as CyPhy.BlastTestBench; if (testBench == null) { testBench = CyPhyClasses.BlastTestBench.Cast(testBenchBase.Impl); } base.TraverseTestBench(testBenchBase); foreach (var item in testBench.Children.BlastComputation2MetricCollection) { CyPhy.BlastComputationType cadcomputation = item.SrcEnds.BlastComputationType; TBComputation tbcomputation = new TBComputation(); tbcomputation.MetricID = item.DstEnds.Metric.ID; if (cadcomputation is CyPhy.MaxHorizonalVelocity) { tbcomputation.ComputationType = TBComputation.Type.MAXHORIZONALVELOCITY; } else if (cadcomputation is CyPhy.MaxVerticalJump) { tbcomputation.ComputationType = TBComputation.Type.MAXVERTICALJUMP; } else if (cadcomputation is CyPhy.MaxVerticalVelocity) { tbcomputation.ComputationType = TBComputation.Type.MAXVERTICALVELOCITY; } tbcomputation.RequestedValueType = ""; Computations.Add(tbcomputation); } int predefinedCnt = testBench.Children.PredefinedBlastSuiteCollection.Count(); int customCnt = testBench.Children.BlastModelCollection.Count(); if (predefinedCnt > 0) { if (predefinedCnt > 1) { Logger.Instance.AddLogMessage("Blast testbench can only have at most 1 predefined blast suite.", Severity.Error); return; } if (customCnt > 0) { Logger.Instance.AddLogMessage("Blast testbench can not have both predefined and custom blast suite.", Severity.Error); return; } } // reference plane if (testBench.Children.ReferencePlaneCollection.Any()) { if (testBench.Children.ReferencePlaneCollection.First().Attributes.ReferencePlaneType == 0) { referencePlaneType = Survivability.ReferencePlaneTypeEnum.Ground; } else { referencePlaneType = Survivability.ReferencePlaneTypeEnum.Waterline; } } Survivability.BlastConfig.Analysis blastAnalysis = new Survivability.BlastConfig.Analysis(); blastAnalysis.ID = AnalysisID; //blastAnalysis.ID = testBench.ID; blastAnalysis.numDisplayTimeSteps = testBench.Attributes.DisplayTimeSteps; blastAnalysis.duration_seconds = testBench.Attributes.Duration; if (predefinedCnt > 0) { blastAnalysis.suiteName = testBench.Children.PredefinedBlastSuiteCollection.First().Attributes.BlastSuiteName; } if (customCnt > 0) { blastAnalysis.suiteName = testBench.Children.BlastModelCollection.First().Attributes.BlastSuiteName; } blastAnalysis.tier = (int)testBench.Attributes.BlastTier + 1; // starts at 0 blastConfig.analysis = blastAnalysis; string stepFormat; if (blastAnalysis.tier > 1) { stepFormat = "AP203_E2_Separate_Part_Files"; } else { stepFormat = "AP203_E2_Single_File"; } if (!STEP_DataExchangeFormats.Contains(stepFormat, StringComparer.CurrentCultureIgnoreCase)) { STEP_DataExchangeFormats.Add(stepFormat); } // blast threat if (customCnt > 0) { CyPhy.BlastModel blastSuite = testBench.Children.BlastModelCollection.First(); if (!blastSuite.Children.BlastThreatCollection.Any()) { Logger.Instance.AddLogMessage("Custom blast testbench must contain a blast threat within a blast suite.", Severity.Error); return; } if (!blastSuite.Children.ChargeLocationCollection.Any()) { Logger.Instance.AddLogMessage("Custom blast testbench must contain a charge location within a blast suite.", Severity.Error); return; } CyPhy.BlastThreat threat = blastSuite.Children.BlastThreatCollection.First(); Survivability.BlastConfig.BlastThreat configThreat = new Survivability.BlastConfig.BlastThreat(); configThreat.burialDepth_meters = threat.Attributes.ThreatBurialDepth; configThreat.chargeSize_kgOfTNT = threat.Attributes.TNTChargeSize; int tTypeint = (int)threat.Attributes.ThreatType; configThreat.type = (Survivability.BlastConfig.BlastThreatTypeEnum)tTypeint; Survivability.BlastConfig.Shape shape = new Survivability.BlastConfig.Shape(); shape.height_meters = threat.Attributes.ThreatShapeHeight; shape.radius_meters = threat.Attributes.ThreatShapeRadius; int sTypeint = (int)threat.Attributes.ThreatShapeType; shape.type = (Survivability.BlastConfig.Shape.ShapeTypeEnum)sTypeint; configThreat.shape = shape; CyPhy.ChargeLocation loc = blastSuite.Children.ChargeLocationCollection.First(); Survivability.BlastConfig.ChargeLocation configChargeLoc = new Survivability.BlastConfig.ChargeLocation(); configChargeLoc.x_meters = loc.Attributes.X; configChargeLoc.y_meters = loc.Attributes.Y; configChargeLoc.z_meters = loc.Attributes.Z; configThreat.chargeLocation = configChargeLoc; blastConfig.blastThreat = configThreat; } }
public virtual void TraverseTestBench(CyPhy.TestBenchType testBench) { AnalysisID = testBench.ID; MakeRep = GetParameterValue(testBench, "MAKE_REP"); DefaultRep = GetParameterValue(testBench, "DEFAULT_REP"); BuyRep = GetParameterValue(testBench, "BUY_REP"); string exportParameterName; string exportFormat; exportParameterName = "EXPORT_STEP_AP203_SINGLE_FILE"; exportFormat = "AP203_Single_File"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!STEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { STEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_STEP_AP203_E2_SINGLE_FILE"; exportFormat = "AP203_E2_Single_File"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!STEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { STEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_STEP_AP203_E2_SEPARATE_PART_FILES"; exportFormat = "AP203_E2_Separate_Part_Files"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!STEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { STEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_STEP_AP214_SINGLE_FILE"; exportFormat = "AP214_Single_File"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!STEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { STEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_STEP_AP214_SEPARATE_PART_FILES"; exportFormat = "AP214_Separate_Part_Files"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!STEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { STEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_STEREOLITHOGRAPHY_ASCII"; exportFormat = "Stereolithography_ASCII"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!NonSTEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { NonSTEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_STEREOLITHOGRAPHY_BINARY"; exportFormat = "Stereolithography_Binary"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!NonSTEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { NonSTEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_INVENTOR"; exportFormat = "Inventor"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!NonSTEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { NonSTEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_PARASOLID"; exportFormat = "Parasolid"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!NonSTEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { NonSTEP_DataExchangeFormats.Add(exportFormat); } } exportParameterName = "EXPORT_DXF_2013"; exportFormat = "DXF_2013"; if (GetParameterValue(testBench, exportParameterName) != null) { if (!NonSTEP_DataExchangeFormats.Contains(exportFormat, StringComparer.CurrentCultureIgnoreCase)) { NonSTEP_DataExchangeFormats.Add(exportFormat); } } foreach (var param in testBench.Children.ParameterCollection.Where(p => p.Name == "PROCESSINGINSTRUCTION")) { string[] paramarr = param.Attributes.Value.Split(','); ProcessingInstructions.Add(new KeyValuePair <string, string>(paramarr[0], paramarr.Length > 1 ? paramarr[1] : "")); } ExportComponentPoints = testBench.Children.ParameterCollection .Where(p => p.Name == "Export_All_Component_Points") .Any(); // R.O. 1/26/2015, InterferenceCheck deprecated. Now interference check is specified by adding a InterferenceCount to // a CADComputationComponent //var interference = testBench.Children.ParameterCollection.Where(p => p.Name == "INTERFERENCE_CHECK"); //if (interference.Any()) //{ // if (interference.First().Attributes.Value == "1") // { // InterferenceCheck = true; // } //} // [email protected]: Collect additional CAD executable parameters from the assembly if (testBench.Children.TopLevelSystemUnderTestCollection.Any()) { if (testBench.Children.TopLevelSystemUnderTestCollection.First().AllReferred is CyPhy.ComponentAssembly) { var assembly = testBench.Children.TopLevelSystemUnderTestCollection.First().AllReferred as CyPhy.ComponentAssembly; var param = assembly.Children.ParameterCollection.Where(p => p.Name.ToUpper() == "CADEXEPARAMS"); if (param.Any()) { this.CADOptions = param.First().Attributes.Value; } } } else if (testBench.Children.ComponentAssemblyCollection.Any()) { var assembly = testBench.Children.ComponentAssemblyCollection.First(); var param = assembly.Children.ParameterCollection.Where(p => p.Name.ToUpper() == "CADEXEPARAMS"); if (param.Any()) { this.CADOptions = param.First().Attributes.Value; } } }
public void AddAllTasks( CyPhy.TestBenchType testBenchType, IEnumerable <global::META.ComComponent> interpreters, string relativePathToProjectDir) { Contract.Requires(testBenchType != null); Contract.Requires(interpreters != null); var workflowRef = testBenchType.Children .WorkflowRefCollection .ToList(); if (workflowRef.Count == 1 && workflowRef[0].AllReferred != null) { var workflow = workflowRef[0].Referred.Workflow; var allTasks = workflow.Children.TaskBaseCollection; var startTask = allTasks .Where(x => x.AllSrcConnections.Count() == 0) .FirstOrDefault(); CyPhy.TaskBase nextTask = startTask; int regularTaskIndex = 0; int regularTaskCount = interpreters.Count(); var processed = new List <CyPhy.TaskBase>(); while (nextTask != null && processed.Contains(nextTask) == false) { processed.Add(nextTask); if (nextTask.Impl.MetaBase.Name == (typeof(CyPhy.Task).Name)) { if (regularTaskIndex < regularTaskCount) { var currTask = interpreters.ElementAt(regularTaskIndex++); if (currTask.result != null && currTask.result.RunCommand != null) { var step = new Step(); step.Invocation = currTask.result.RunCommand; this.Steps.Add(step); } } } else if (nextTask.Impl.MetaBase.Name == (typeof(CyPhy.ExecutionTask).Name)) { CyPhy.ExecutionTask executionTask = ISIS.GME.Dsml.CyPhyML.Classes.ExecutionTask.Cast(nextTask.Impl); Step step = CreateManifestStepForExecutionTask(relativePathToProjectDir, executionTask); this.Steps.Add(step); } var flow = nextTask.DstConnections.FlowCollection.FirstOrDefault(); if (flow == null) { nextTask = null; } else { nextTask = flow.DstEnds.TaskBase; } } } else if (testBenchType.Impl.MetaBase.Name == typeof(CyPhy.CADTestBench).Name) { // CADTestBench aka Structural FEA Test Bench is assumed to run with only CyPhy2CAD var step = new Step(); step.Invocation = interpreters.Single().result.RunCommand; this.Steps.Add(step); } }
public override void TraverseTestBench(CyPhy.TestBenchType testBenchBase) { string stepFormat = "AP203_E2_Single_File"; if (!STEP_DataExchangeFormats.Contains(stepFormat, StringComparer.OrdinalIgnoreCase)) { STEP_DataExchangeFormats.Add(stepFormat); } CyPhy.BallisticTestBench testBench = testBenchBase as CyPhy.BallisticTestBench; if (testBench == null) { testBench = CyPhyClasses.BallisticTestBench.Cast(testBenchBase.Impl); } base.TraverseTestBench(testBenchBase); //AnalysisID = testBench.ID; foreach (var item in testBench.Children.BallisticComputation2MetricCollection) { TBComputation tbcomputation = new TBComputation(); if (item.SrcEnds.TotalIntersections != null) { tbcomputation.ComputationType = TBComputation.Type.TOTALINTERSECTIONS; } else if (item.SrcEnds.TotalKills != null) { tbcomputation.ComputationType = TBComputation.Type.TOTALKILLS; } else if (item.SrcEnds.TotalPerforations != null) { tbcomputation.ComputationType = TBComputation.Type.TOTALPERFORATIONS; } else if (item.SrcEnds.TotalShots != null) { tbcomputation.ComputationType = TBComputation.Type.TOTALSHOTS; } else { Logger.Instance.AddLogMessage("Unknown Ballistic calculation: " + item.SrcEnd.Impl.Name, Severity.Error); } tbcomputation.MetricID = item.DstEnds.Metric.ID; tbcomputation.MetricName = item.Name; tbcomputation.RequestedValueType = ""; Computations.Add(tbcomputation); } int predefinedCnt = testBench.Children.PredefinedBallisticSuiteCollection.Count(); int customCnt = testBench.Children.ShotlineModelCollection.Count(); if (predefinedCnt > 0) { if (predefinedCnt > 1) { Logger.Instance.AddLogMessage("Ballistic testbench can only have at most 1 predefined shotline suite.", Severity.Error); return; } if (customCnt > 0) { Logger.Instance.AddLogMessage("Ballistic testbench can not have both predefined and custom shotline suites.", Severity.Error); return; } } // reference plane if (testBench.Children.ReferencePlaneCollection.Any()) { if (testBench.Children.ReferencePlaneCollection.First().Attributes.ReferencePlaneType == 0) { referencePlaneType = Survivability.ReferencePlaneTypeEnum.Ground; } else { referencePlaneType = Survivability.ReferencePlaneTypeEnum.Waterline; } } // analysis Survivability.BallisticConfig.Analysis ballisticAnalysis = new Survivability.BallisticConfig.Analysis(); ballisticAnalysis.ID = AnalysisID; if (predefinedCnt > 0) { ballisticAnalysis.suiteName = testBench.Children.PredefinedBallisticSuiteCollection.First().Attributes.Name; } else { ballisticAnalysis.suiteName = testBench.Name; } if (ballisticAnalysis.suiteName.Length == 0) { Logger.Instance.AddLogMessage("Ballistic analysis suite has no name specified.", Severity.Warning); } ballisticAnalysis.tier = (int)testBench.Attributes.Tier + 1; // starts at 0 ballisticConfig.analysis = ballisticAnalysis; // ballistic threat foreach (var item in testBench.Children.BallisticThreatCollection) { VerifyBallisticThreat(item); Survivability.BallisticConfig.BallisticThreat threat = new Survivability.BallisticConfig.BallisticThreat(); threat.diameter_meters = item.Attributes.Diameter; threat.length_meters = item.Attributes.Length; threat.materialRef = item.Attributes.Material; threat.speed_metersPerSec = item.Attributes.Speed; if (item.Kind == "ProjectileBallisticThreat") { threat.type = Survivability.BallisticConfig.BallisticThreat.BallisticThreatTypeEnum.Ballistic; } else if (item.Kind == "ShapedChargeJetBallisticThreat") { threat.type = Survivability.BallisticConfig.BallisticThreat.BallisticThreatTypeEnum.ShapedChargeJet; threat.standoff_meters = (item as CyPhy.ShapedChargeJetBallisticThreat).Attributes.Standoff; int chargeq = (int)(item as CyPhy.ShapedChargeJetBallisticThreat).Attributes.ChargeQuality; threat.chargeQuality = (Survivability.BallisticConfig.BallisticThreat.ChargeQualityEnum)(chargeq); } threat.name = item.ID; ballisticConfig.ballisticThreats.Add(threat); } // critical components foreach (var item in testBench.Children.CriticalComponentCollection) { int type = (int)item.Attributes.Type; CyPhy.TIPRefBase refbase = item.Referred.TIPRefBase; if (refbase != null) { if (refbase.Kind != "Component") { Logger.Instance.AddLogMessage(String.Format("Critical component must refer to a component: {0}", refbase.Name), Severity.Error); } else { Survivability.BallisticConfig.CriticalComponent criticalcomponent = new Survivability.BallisticConfig.CriticalComponent(); criticalcomponent.componentID = (refbase as CyPhy.Component).Attributes.InstanceGUID; criticalcomponent.type = (Survivability.BallisticConfig.CriticalComponent.CriticalityTypeEnum)(type); ballisticConfig.criticalComponents.Add(criticalcomponent); } } } // file location // see GenerateCADXmlOutput(); // custom shotline foreach (var item in testBench.Children.ShotlineModelCollection) { if (VerifyShotLineModel(item)) { continue; } string componentid = ""; string datumname = ""; CyPhy.ShotlineTarget target = item.DstConnections.ShotlineTargetCollection.First(); CyPhy.Point ap = target.DstEnds.Point; PointMetricTraversal traverser = new PointMetricTraversal(ap); if (!traverser.portsFound.Any()) { Logger.Instance.AddLogMessage("Shotline Model is connected to an AnalysisPoint which does not end in a PointGeometry [" + item.Path + "]", Severity.Error); continue; } datumname = (traverser.portsFound.First() as CyPhy.Point).Attributes.DatumName; CyPhy.Component targetComponent = CyPhyClasses.Component.Cast(traverser.portsFound.First().ParentContainer.ParentContainer.Impl); componentid = targetComponent.Attributes.InstanceGUID; foreach (var conn in item.SrcConnections.Threat2ShotlineSuiteCollection) { CyPhy.BallisticThreat threat = conn.SrcEnds.BallisticThreat; CustomShotline customshotline = new CustomShotline(); customshotline.Azimuth = item.Children.AzimuthAngleCollection.First().Attributes.Value; customshotline.Elevation = item.Children.ElevationAngleCollection.First().Attributes.Value; customshotline.BallisticThreatRef = threat.ID; customshotline.ComponentID = componentid; customshotline.DatumPoint = datumname; customshotline.ShotlineName = item.Attributes.Name; customShotlineList.Add(customshotline); } } }
public static IEnumerable <RuleFeedbackBase> TestBenchRefsWorkflowsAreValid(MgaFCO context) { try { var result = new List <RuleFeedbackBase>(); // no TB null ref var tbRefs = (context as MgaModel) .ChildObjects .OfType <MgaReference>() .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name); List <string> tbRefNames = new List <string>(); List <string> tbIDs = new List <string>(); MgaFCO referredSUT = null; foreach (var tbRef in tbRefs) { // Unique names if (tbRefNames.Contains(tbRef.Name)) { var feedbackName = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBenchRef name must be unique: {0} (within {1})", tbRef.Name, context.Name) }; feedbackName.InvolvedObjectsByRole.Add(tbRef as IMgaFCO); result.Add(feedbackName); } else { tbRefNames.Add(tbRef.Name); } // Referred TB is not null if (tbRef.Referred == null) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBenchRef cannot be null: {0} (within {1})", tbRef.Name, context.Name) }; feedback.InvolvedObjectsByRole.Add(context as IMgaFCO); result.Add(feedback); } else { // Can only use each TB once in an SoT if (tbIDs.Contains(tbRef.Referred.ID)) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("Multiple TestBenchRefs cannot refer to the same TestBench: {0} (within {1})", tbRef.Name, context.Name) }; feedback.InvolvedObjectsByRole.Add(context as IMgaFCO); result.Add(feedback); } else { tbIDs.Add(tbRef.Referred.ID); } CyPhy.TestBenchType referredTB = CyPhyClasses.TestBenchType.Cast(tbRef.Referred); if (referredTB.Children.TopLevelSystemUnderTestCollection.Count() != 0) { var tlsut = referredTB.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); if ((tlsut.AllReferred.Impl as MgaFCO) != null) { if (referredSUT == null) { referredSUT = tlsut.AllReferred.Impl as MgaFCO; } else if ((tlsut.AllReferred.Impl as MgaFCO).ID != referredSUT.ID) { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("All TestBenches in {0} must use to the same SystemUnderTest", context.Name) }; feedback.InvolvedObjectsByRole.Add(context as IMgaFCO); result.Add(feedback); } } } else { var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBench {0} does not have a SystemUnderTest", tbRef.Name) }; feedback.InvolvedObjectsByRole.Add(tbRef as IMgaFCO); result.Add(feedback); } if (referredTB.Children.WorkflowRefCollection.Any()) { if (referredTB.Children.WorkflowRefCollection.Count() == 1) { // one workflow var workflowRef = referredTB.Children.WorkflowRefCollection.FirstOrDefault(); if (workflowRef.Referred.Workflow != null) { var workflow = workflowRef.Referred.Workflow; if (workflow.Children.TaskCollection.Any()) { // OK? } else { // no tasks var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBench {0} has a workflow with no tasks", tbRef.Name) }; feedback.InvolvedObjectsByRole.Add(tbRef as IMgaFCO); feedback.InvolvedObjectsByRole.Add(workflow.Impl as IMgaFCO); result.Add(feedback); } } else { // workflow ref is null var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBench {0} has a workflow which is a null reference", tbRef.Name) }; feedback.InvolvedObjectsByRole.Add(tbRef as IMgaFCO); feedback.InvolvedObjectsByRole.Add(workflowRef.Impl as IMgaFCO); result.Add(feedback); } } else { // more than one workflow var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBench {0} has more than one workflow element", tbRef.Name) }; feedback.InvolvedObjectsByRole.Add(tbRef as IMgaFCO); result.Add(feedback); } } else { // no workflow var feedback = new GenericRuleFeedback() { FeedbackType = FeedbackTypes.Error, Message = string.Format("TestBench {0} has no workflow element", tbRef.Name) }; feedback.InvolvedObjectsByRole.Add(tbRef 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 as IMgaFCO); result.Add(feedback); return(result); } }
public MultiJobRunProcessor(CyPhy.TestBenchType testBenchType) : base(testBenchType) { }
/// <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, DateTime time) { string jsonFile = Path.GetFullPath(Path.Combine(this.GetResultsFolder(), "results.metaresults.json")); AVM.DDP.MetaResults results = null; using (new MutexWrapper(jsonFile)) { if (File.Exists(jsonFile)) { string content = ""; using (StreamReader reader = new StreamReader(jsonFile)) { content = reader.ReadToEnd(); } try { results = JsonConvert.DeserializeObject <AVM.DDP.MetaResults>(content); } catch (Newtonsoft.Json.JsonReaderException ex) { // Will this cause problems if we run it from the job manager??? Should we only log it istead? throw new Exception(string.Format("{0} file is probably malformed. Not a valid json. {1}{2}", Path.GetFullPath(jsonFile), Environment.NewLine, ex.Message)); } // 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 = time.ToString("yyyy-MM-dd HH-mm-ss"); if (string.IsNullOrWhiteSpace(singleFco.RegistryValue["TestBenchUniqueName"]) == false) { thisResult.TestBench = singleFco.RegistryValue["TestBenchUniqueName"] + ".testbench.json"; } Func <MgaFCO, CyPhy.TestBenchType> cast; if (TestbenchAndCompositeTypes.TryGetValue(singleFco.Meta.Name, out cast) && cast(singleFco) != null) { CyPhy.TestBenchType testBench = cast(singleFco); var tlsut = testBench.Children.TopLevelSystemUnderTestCollection.FirstOrDefault(); if (tlsut != null) { if (tlsut.AllReferred is CyPhy.ComponentAssembly) { 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)); } } }
public override void TraverseTestBench(CyPhy.TestBenchType testBenchBase) { CyPhy.KinematicTestBench testBench = testBenchBase as CyPhy.KinematicTestBench; if (testBench == null) { testBench = CyPhyClasses.KinematicTestBench.Cast(testBenchBase.Impl); } base.TraverseTestBench(testBenchBase); //NonSTEP_DataExchangeFormats.Add("Parasolid"); Name = testBench.Name; SimulationStep = testBench.Attributes.SimulationResolution; SimulationTime = testBench.Attributes.Duration; if (testBench.Children.GravityLoadCollection.Any()) { CyPhy.GravityLoad load = testBench.Children.GravityLoadCollection.First(); double x = 0; double y = 0; double z = 0; GetGravityLoadParam(load, "X", out x); GetGravityLoadParam(load, "Y", out y); GetGravityLoadParam(load, "Z", out z); Gravity = new KinematicGravity(x, y, z, load.Attributes.Active); } var terrain = testBench.Children.ComponentRefCollection.Where(c => ((MgaFCO)c.Impl).MetaRole.Name == "Terrain"); if (terrain.Any()) { CyPhy.Component terraincomp = terrain.First().AllReferred as CyPhy.Component; if (terraincomp == null) { Logger.Instance.AddLogMessage("Terrain component reference must refer to a cyphy component.", Severity.Error); return; } if (!terraincomp.Children.CADModelCollection.Any()) { Logger.Instance.AddLogMessage("Terrain component must contain a CAD model.", Severity.Error); return; } TerrainFileName = terraincomp.Children.ResourceCollection.First().Attributes.Path; try { File.Copy(Path.Combine(terraincomp.GetDirectoryPath(), TerrainFileName), Path.Combine(OutputDirectory, Path.GetFileName(TerrainFileName))); } catch (Exception e) { Logger.Instance.AddLogMessage("Unable to copy terrain file: " + e.Message, Severity.Warning); } TerrainFileName = Path.GetFileNameWithoutExtension(TerrainFileName); } else { if (testBench.Children.AnchorCollection.Any()) { CyPhy.Anchor anchor = testBench.Children.AnchorCollection.First(); var pointList = anchor .DstConnections .SetAnchorCollection .Select(x => x.DstEnds.Point) .Concat(anchor .SrcConnections .SetAnchorCollection .Select(x => x.SrcEnds.Point)); if (!pointList.Any()) { Logger.Instance.AddLogMessage("Anchor is not connected to a point. Anchor should be connected to a datum point on one of the components.", Severity.Error); return; } var point = pointList.First(); PointMetricTraversal traverser = new PointMetricTraversal(point); foreach (var pointFound in traverser.portsFound) { string name = (pointFound as CyPhy.Point).Attributes.DatumName; string componentID = CyPhyClasses.Component.Cast((pointFound as CyPhy.Point).ParentContainer.ParentContainer.Impl).Attributes.InstanceGUID; StaticAnalysisMetrics.Add(new TBComputation() { ComponentID = componentID, Details = name, MetricID = "Anchor", ComputationType = TBComputation.Type.POINTCOORDINATES, RequestedValueType = "Vector" }); //Computations.Add(new TBComputation() { ComponentID = componentID, FeatureDatumName = name, MetricID = "Anchor", ComputationType = TBComputation.Type.POINTCOORDINATES, RequestedValueType = "Vector" }); GroundCyphyID = componentID; } } else { Logger.Instance.AddLogMessage("Anchor not found. There should be exactly one anchor in the testbench, to specify which body is fixed to the ground in the kinematic simnulation.", Severity.Error); return; } } foreach (var motion in testBench.Children.MotionLoadCollection) { var connectorList = motion .SrcConnections .ApplyMotionToJointCollection .Select(x => x.SrcEnds.Connector) .Concat(motion .DstConnections .ApplyMotionToJointCollection .Select(x => x.DstEnds.Connector) ); var toplevelSUT = testBench.Children.ComponentAssemblyCollection.FirstOrDefault(); foreach (var connector in connectorList) { OriginatingConnectorTraversal traverser = new OriginatingConnectorTraversal(connector); if (traverser.result != null) { CyPhy.KinematicJoint joint = GetJoint(traverser.result); if (joint != null) { Multibody.ModelLoadsMotion mbdMotion = new Multibody.ModelLoadsMotion(); mbdMotion.Active = (motion.Attributes.Active) ? Multibody.ModelLoadsMotionActive.on : Multibody.ModelLoadsMotionActive.off; mbdMotion.FreedomType = (Multibody.ModelLoadsMotionFreedomType)((int)motion.Attributes.JointFreedomType); mbdMotion.Function = motion.Attributes.CustomFunction; mbdMotion.JointID = cadDataContainer.GetJointIDFromGMEID(joint.ID); mbdMotion.MotionID = motion.Name; mbdMotion.TimeDerivative = (Multibody.ModelLoadsMotionTimeDerivative)((int)motion.Attributes.TimeDerivative); mbdMotion.Type = "JointMotion"; MotionList.Add(mbdMotion); } else { Logger.Instance.AddLogMessage("Kinematic motion is connected to a connector without joint information: " + connector.ToHyperLink(), Severity.Error); } } } } if (testBench.Children.AdamsScriptCollection.Any()) { Scripts = new List <Multibody.ModelScript>(); foreach (var script in testBench.Children.AdamsScriptCollection) { Scripts.Add(new Multibody.ModelScript() { Path = script.Attributes.Path }); } } ProcessContacts(testBench); }
private void ProcessCAD(MgaFCO currentobj) { string outputdir = this.mainParameters.OutputDirectory; if (!Directory.Exists(outputdir)) { Directory.CreateDirectory(outputdir); } string debuglogdir = Path.Combine(outputdir, "log"); if (!Directory.Exists(debuglogdir)) { Directory.CreateDirectory(debuglogdir); } string projectdir = this.mainParameters.ProjectDirectory; CyPhy2CADSettings cadSetting = (CyPhy2CADSettings)this.mainParameters.config; string cadauxdir = cadSetting.AuxiliaryDirectory; CyPhy.ComponentAssembly curassembly; string curObjMetaBase = currentobj.MetaBase.Name; if (curObjMetaBase == "TestBench" || curObjMetaBase == "BallisticTestBench" || curObjMetaBase == "CFDTestBench" || curObjMetaBase == "BlastTestBench" || curObjMetaBase == "KinematicTestBench") { CyPhy.TestBenchType tb = CyPhyClasses.TestBenchType.Cast(currentobj); if (result != null && curObjMetaBase == "BlastTestBench") { result.Labels = JobManager.Job.DefaultLabels + "&&SwRI_Blast"; } if (result != null && curObjMetaBase == "KinematicTestBench") { result.Labels = JobManager.Job.DefaultLabels + "&&Adams"; } var catlsut = tb.Children.ComponentAssemblyCollection.FirstOrDefault(); // should be an instance b/c elaborate was called earlier if (catlsut == null) { result.Success = false; throw new Exception("There is no elaborated system under test component assembly in the model!"); } curassembly = catlsut; if (curassembly == null) { result.Success = false; throw new Exception("No Valid Component Assembly."); } // META-1971: ADM + ACM file export for blast + ballistics if (curObjMetaBase == "BallisticTestBench" || curObjMetaBase == "BlastTestBench") { // ADM: Export DDP 2.x version (XML) { var design = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(catlsut, this.result.Traceability); string TestBenchName = tb.Name; string admDir = Path.Combine(cadSetting.OutputDirectory, "DesignADM"); if (!Directory.Exists(admDir)) { Directory.CreateDirectory(admDir); } OpenMETA.Interchange.AvmXmlSerializer.SaveToFile(Path.Combine(admDir, TestBenchName + ".adm"), design); } } // end META-1971 // META-2987 GenerateCADParameterMapping(tb, outputdir, new List <object>()); CADFlatDataCreator datacreator = new CADFlatDataCreator(debuglogdir, this.mainParameters.ProjectDirectory, CadFormat); datacreator.Traceability = this.result.Traceability; datacreator.CreateFlatData(curassembly); DataRep.CADContainer cadcontainer = datacreator.CreateCADDataContainer(curassembly.Attributes.ConfigurationUniqueID, UtilityHelpers.CleanString2(curassembly.Name)); using (StreamWriter writer = new StreamWriter(Path.Combine(outputdir, "log", "CyPhy2CAD_Graphviz_Representation.gv"))) { writer.WriteLine(cadcontainer.ToGraphviz(true)); } if (!cadcontainer.IsAnalyzable() && curObjMetaBase != "TestBench") { result.Success = false; //Logger.Instance.AddLogMessage("Test Bench can not proceed because the test bench contains islands and/or orphans! Please see graphviz file in /log directory for details.", Severity.Error); throw new META.InterpreterException("Test Bench can not proceed because the test bench contains islands and/or orphans, see graphviz file in /log/CyPhy2CAD_Graphviz_Representation.gv for details. Please remove islands/orphans and try again."); } TestBenchModel.TestBenchBase testBenchRep = TestBenchModelFactory.CreateTestBenchModel(curObjMetaBase, cadSetting, outputdir, projectdir, Automation); testBenchRep.cadDataContainer = cadcontainer; testBenchRep.CopySTL = this.CopySTL; if (curObjMetaBase != "ComponentAssembly") { testBenchRep.TraverseTestBench(tb); } testBenchRep.CollectDirectories(); result.Success = testBenchRep.GenerateOutputFiles(); } else if (curObjMetaBase == "CADTestBench") { CyPhy.CADTestBench tb = CyPhyClasses.CADTestBench.Cast(currentobj); // META-1701: label for Abaqus if (result != null) { Dictionary <CyPhyClasses.CADTestBench.AttributesClass.SolverType_enum, string> labelMap = new Dictionary <CyPhyClasses.CADTestBench.AttributesClass.SolverType_enum, string>() { { CyPhyClasses.CADTestBench.AttributesClass.SolverType_enum.ABAQUS_Deck_Based, "Abaqus" }, { CyPhyClasses.CADTestBench.AttributesClass.SolverType_enum.ABAQUS_Model_Based, "Abaqus" }, { CyPhyClasses.CADTestBench.AttributesClass.SolverType_enum.NASTRAN, "Nastran" }, }; string label = "Abaqus"; labelMap.TryGetValue(tb.Attributes.SolverType, out label); result.Labels += "&&" + label; } var toplevelSUT = tb.Children.ComponentAssemblyCollection.FirstOrDefault(); // should be an instance b/c elaborate was called earlier if (toplevelSUT == null) { result.Success = false; throw new Exception("There is no elaborated system under test component assembly in the model!"); } CADFlatDataCreator datacreator = new CADFlatDataCreator(debuglogdir, this.mainParameters.ProjectDirectory, CadFormat); datacreator.Traceability = this.result.Traceability; datacreator.CreateFlatData(tb, toplevelSUT.Path); DataRep.CADContainer cadcontainer = datacreator.CreateCADDataContainer(tb.Guid.ToString(), UtilityHelpers.CleanString2(tb.Name)); using (StreamWriter writer = new StreamWriter(Path.Combine(outputdir, "log", "CyPhy2CAD_Graphviz_Representation.gv"))) { writer.WriteLine(cadcontainer.ToGraphviz(true)); } result.Success = false; if (!cadcontainer.IsAnalyzable()) { //Logger.Instance.AddLogMessage("FEA Test Bench can not proceed because the test bench contains islands and/or orphans! Please see graphviz file in /log directory for details.", Severity.Error); throw new META.InterpreterException("FEA Test Bench can not proceed because the test bench contains islands and/or orphans, see graphviz file in /log/CyPhy2CAD_Graphviz_Representation.gv for details. Please remove islands/orphans and try again."); } TestBenchModel.TestBenchBase testBenchRep = TestBenchModelFactory.CreateTestBenchModel(curObjMetaBase, cadSetting, outputdir, projectdir, Automation); testBenchRep.cadDataContainer = cadcontainer; testBenchRep.CopySTL = this.CopySTL; testBenchRep.TraverseTestBench(tb); testBenchRep.CollectDirectories(); result.Success = testBenchRep.GenerateOutputFiles(); List <object> mappings = new List <object>(); if (testBenchRep is TestBenchModel.FEATestBench) { var feaRep = (TestBenchModel.FEATestBench)testBenchRep; mappings = feaRep.TestBenchParameterMappings; } // META-2987 GenerateCADParameterMapping(tb, outputdir, mappings); } else if (curObjMetaBase == "ComponentAssembly") { curassembly = CyPhyClasses.ComponentAssembly.Cast(currentobj); CADFlatDataCreator datacreator = new CADFlatDataCreator(debuglogdir, this.mainParameters.ProjectDirectory, CadFormat); datacreator.Traceability = this.result.Traceability; datacreator.CreateFlatData(curassembly); DataRep.CADContainer cadcontainer = datacreator.CreateCADDataContainer(curassembly.Guid.ToString(), UtilityHelpers.CleanString2(curassembly.Name)); TestBenchModel.TestBenchBase testbenchbase = new TestBenchModel.TestBenchBase(cadSetting, outputdir, projectdir); testbenchbase.cadDataContainer = cadcontainer; testbenchbase.CopySTL = this.CopySTL; testbenchbase.CollectDirectories(); } else { result.Success = false; throw new NotImplementedException(String.Format("Running Cyphy2CAD on {0} is not implemented.", curObjMetaBase)); } }
public override void TraverseTestBench(CyPhy.TestBenchType testBenchBase) { // META-3195 - CFD needs Inventor format now instead of STL - Stereolithography_ASCII NonSTEP_DataExchangeFormats.Add("Inventor"); CyPhy.CFDTestBench testBench = testBenchBase as CyPhy.CFDTestBench; if (testBench == null) { testBench = CyPhyClasses.CFDTestBench.Cast(testBenchBase.Impl); } base.TraverseTestBench(testBenchBase); //AnalysisID = testBench.ID; foreach (var conn in testBench.Children.CFDComputation2MetricCollection) { TBComputation tbcomputation = new TBComputation(); tbcomputation.MetricID = conn.DstEnds.Metric.ID; tbcomputation.ComputationType = TBComputation.Type.COEFFICIENTOFDRAG; tbcomputation.RequestedValueType = "SCALAR"; Computations.Add(tbcomputation); } int calmSolverCnt = testBench.Children.CalmWaterSolverSettingsCollection.Count(); int waveSolverCnt = testBench.Children.WaveResistanceSolverSettingsCollection.Count(); int correlationSolverCnt = testBench.Children.CorrelationSettingsCollection.Count(); int hydrostaticsSolverCnt = testBench.Children.HydrostaticsSolverSettingsCollection.Count(); if ((calmSolverCnt + waveSolverCnt + correlationSolverCnt + hydrostaticsSolverCnt) < 1) { Logger.Instance.AddLogMessage("No CFD solver settings in the test bench", Severity.Error); return; } if (hydrostaticsSolverCnt > 1 || (calmSolverCnt + waveSolverCnt + correlationSolverCnt) > 1) { Logger.Instance.AddLogMessage( "Multiple CFD solver settings in the test bench", Severity.Error); Logger.Instance.AddLogMessage( "A test bench can only contain one hydrostatics and one calm, wave or correlation solver setting.", Severity.Info); return; } #region ValidAttributes double MinVelocity = 0; double MaxVelocity = 343; double AbsZero = -273.15; double MaxTemp = 100; double MinAngle = 0; double MaxAngle = 360; #endregion if (hydrostaticsSolverCnt == 1) { CyPhy.HydrostaticsSolverSettings solverSettings = testBench.Children.HydrostaticsSolverSettingsCollection.First(); if (solverSettings.Attributes.FluidTemperature < AbsZero || solverSettings.Attributes.FluidTemperature > MaxTemp) { string message = string.Format( "'{0}': 'FluidTemperature' attribute must be [{1} - {2}]", solverSettings.Name, AbsZero, MaxTemp); Logger.Instance.AddLogMessage( message, Severity.Error); } if (solverSettings.Attributes.PitchAngleStart < MinAngle || solverSettings.Attributes.PitchAngleStart > MaxAngle || solverSettings.Attributes.PitchAngleEnd < MinAngle || solverSettings.Attributes.PitchAngleEnd > MaxAngle || solverSettings.Attributes.RollAngleStart < MinAngle || solverSettings.Attributes.RollAngleStart > MaxAngle || solverSettings.Attributes.RollAngleEnd < MinAngle || solverSettings.Attributes.RollAngleEnd > MaxAngle || solverSettings.Attributes.PitchAngleStepSize < MinAngle || solverSettings.Attributes.PitchAngleStepSize > MaxAngle || solverSettings.Attributes.RollAngleStepSize < MinAngle || solverSettings.Attributes.RollAngleStepSize > MaxAngle) { string message = string.Format( "'{0}': 'Angle' attributes must be [{1}-{2}]", solverSettings.Name, MinAngle, MaxAngle); Logger.Instance.AddLogMessage( message, Severity.Error); } cfdConfigs.Add(new CFDConfig.HydrostaticsSolverSettings(solverSettings, testBench)); } if (calmSolverCnt == 1) { CyPhy.CalmWaterSolverSettings solverSettings = testBench.Children.CalmWaterSolverSettingsCollection.First(); if (solverSettings.Attributes.VehicleVelocity > MaxVelocity || solverSettings.Attributes.VehicleVelocity < MinVelocity) { string message = string.Format( "'{0}': 'Velocity' attribute must be [{1}-{2}]", solverSettings.Name, MinVelocity, MaxVelocity); Logger.Instance.AddLogMessage( message, Severity.Error); } if (solverSettings.Attributes.FluidTemperature < AbsZero || solverSettings.Attributes.FluidTemperature > MaxTemp) { string message = string.Format( "'{0}': 'FluidTemperature' attribute must be [{1} - {2}]", solverSettings.Name, AbsZero, MaxTemp); Logger.Instance.AddLogMessage( message, Severity.Error); } cfdConfigs.Add(new CFDConfig.CalmWaterSolverSettings(solverSettings, testBench)); return; } if (waveSolverCnt == 1) { CyPhy.WaveResistanceSolverSettings solverSettings = testBench.Children.WaveResistanceSolverSettingsCollection.First(); if (solverSettings.Attributes.VehicleVelocity > MaxVelocity || solverSettings.Attributes.VehicleVelocity < MinVelocity) { string message = string.Format( "'{0}': 'Velocity' attribute must be [{1}-{2}]", solverSettings.Name, MinVelocity, MaxVelocity); Logger.Instance.AddLogMessage( message, Severity.Error); } if (solverSettings.Attributes.FluidTemperature < AbsZero || solverSettings.Attributes.FluidTemperature > MaxTemp) { string message = string.Format( "'{0}': 'FluidTemperature' attribute must be [{1} - {2}]", solverSettings.Name, AbsZero, MaxTemp); Logger.Instance.AddLogMessage( message, Severity.Error); } if (solverSettings.Attributes.WaveFrequency < 0) { string message = string.Format( "'{0}': 'WaveFrequency' attribute must be greater than 0", solverSettings.Name); Logger.Instance.AddLogMessage( message, Severity.Error); } if (solverSettings.Attributes.WaveDirection < MinAngle || solverSettings.Attributes.WaveDirection > MaxAngle) { string message = string.Format( "'{0}': 'Angle' attributes must be [{1}-{2}]", solverSettings.Name, MinAngle, MaxAngle); Logger.Instance.AddLogMessage( message, Severity.Error); } cfdConfigs.Add(new CFDConfig.WaveResistanceSolverSettings(solverSettings, testBench)); return; } if (correlationSolverCnt == 1) { CyPhy.CorrelationSettings solverSettings = testBench.Children.CorrelationSettingsCollection.First(); if (solverSettings.Attributes.VehicleVelocity > MaxVelocity || solverSettings.Attributes.VehicleVelocity < 0) { string message = string.Format( "'{0}': 'Velocity' attribute must be [{1}-{2}]", solverSettings.Name, MinVelocity, MaxVelocity); Logger.Instance.AddLogMessage( message, Severity.Error); } cfdConfigs.Add(new CFDConfig.CorrelationSolverSettings(solverSettings, testBench)); return; } // Post Processing Blocks foreach (var postprocess in testBench.Children.PostProcessingCollection) { PostProcessScripts.Add(postprocess.Attributes.ScriptPath); } }