public Clm(IMgaModel cyPhyComponent) { this.CyPhyComponent = cyPhyComponent as IMgaModel; this.ProjectDir = Path.GetDirectoryName(this.CyPhyComponent.Project.ProjectConnStr.Substring("MGA=".Length)); this.ZipDownloadDir = Path.Combine(this.ProjectDir, "VFComponentDownloads"); }
public ComponentItem(IMgaModel component) { this.component = component; ModelicaModel = new List<IMgaModel>(); ModelicaModelOptions = new BindingList<ModelicaModel>(); Classification = component.StrAttrByName["Classifications"]; component .ChildFCOs .Cast<IMgaFCO>() .Where(x => x.Meta.Name == "ModelicaModel") .ToList() .ForEach(x => ModelicaModel.Add(x as IMgaModel)); ModelicaModel.Sort((x, y) => x.GetGuidDisp().CompareTo(y.GetGuidDisp())); int id = 0; ModelicaModel.ForEach(x => { var opt = new CyPhyComponentFidelitySelector.ModelicaModel() { Key = id++, Name = x.Name, Guid = x.GetGuidDisp() }; ModelicaModelOptions.Add(opt); }); Guid = component.GetGuidDisp(); }
public ComponentItem(IMgaModel component) { this.component = component; ModelicaModel = new List <IMgaModel>(); ModelicaModelOptions = new BindingList <ModelicaModel>(); Classification = component.StrAttrByName["Classifications"]; component .ChildFCOs .Cast <IMgaFCO>() .Where(x => x.Meta.Name == "ModelicaModel") .ToList() .ForEach(x => ModelicaModel.Add(x as IMgaModel)); ModelicaModel.Sort((x, y) => x.GetGuidDisp().CompareTo(y.GetGuidDisp())); int id = 0; ModelicaModel.ForEach(x => { var opt = new CyPhyComponentFidelitySelector.ModelicaModel() { Key = id++, Name = x.Name, Guid = x.GetGuidDisp() }; ModelicaModelOptions.Add(opt); }); Guid = component.GetGuidDisp(); }
/// <summary> /// Gets a new instance of a context checker based on a given context. /// Note: Execute within transaction. /// </summary> /// <param name="context">Test bench, Parameteric Exploration, or Test bench Suite</param> /// <returns>A new context specific checker if context is supported, otherwise null.</returns> /// <exception cref="ArgumentNullException" /> /// <exception cref="ArgumentOutOfRangeException" /> public static ContextChecker GetContextChecker(IMgaModel context) { if (context == null) { throw new ArgumentNullException(); } ContextChecker contextChecker = null; // get specialized context checker based on the context type. if (context.MetaBase.Name == typeof(CyPhy.TestBench).Name) { contextChecker = new TestBenchChecker(CyPhyClasses.TestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.CADTestBench).Name) { contextChecker = new StructuralFEATestBenchChecker(CyPhyClasses.CADTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.KinematicTestBench).Name) { contextChecker = new KinematicTestBenchChecker(CyPhyClasses.KinematicTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.CFDTestBench).Name) { contextChecker = new CFDTestBenchChecker(CyPhyClasses.CFDTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.BlastTestBench).Name) { contextChecker = new BlastTestBenchChecker(CyPhyClasses.BlastTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.BallisticTestBench).Name) { contextChecker = new BallisticTestBenchChecker(CyPhyClasses.BallisticTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.TestBenchSuite).Name) { contextChecker = new TestBenchSuiteChecker(CyPhyClasses.TestBenchSuite.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.ParametricExploration).Name) { contextChecker = new ParametricExplorationChecker(CyPhyClasses.ParametricExploration.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.CarTestBench).Name) { contextChecker = new CarTestBenchChecker(CyPhyClasses.CarTestBench.Cast(context)); } else { throw new ArgumentOutOfRangeException(string.Format("Given context is {0}, which is not supported. Try to run it on a test bench, PET or SoT.", context.Meta.Name)); } return(contextChecker); }
public static string GetComponentCategory(IMgaModel component) { Contract.Requires(component != null); string componentCategory = ""; if (component != null) { componentCategory = component.StrAttrByName["Classifications"]; } return(componentCategory); }
public ComponentSelectionForm(IMgaModel component, IMgaModel alternativeContainer, System.IO.TextWriter errorWriter = null, System.IO.TextWriter infoWriter = null) { InitializeComponent(); #region Initialize Class Variables this.component = component; this.alternativeContainer = alternativeContainer; this.dataSource = new List <ComponentListItem>(); this.ErrorWriter = (errorWriter == null) ? Console.Error : errorWriter; this.InfoWriter = (infoWriter == null) ? Console.Out : infoWriter; this.clm = new ClmLib.Clm(this.component); #endregion this.filterParameters = this.clm.GenerateFilter(alternativeContainer, this.ErrorWriter, this.InfoWriter); RefreshLocalComponentList(); }
public ComponentSelectionForm(IMgaModel component, IMgaModel alternativeContainer, System.IO.TextWriter errorWriter=null, System.IO.TextWriter infoWriter=null) { InitializeComponent(); #region Initialize Class Variables this.component = component; this.alternativeContainer = alternativeContainer; this.dataSource = new List<ComponentListItem>(); this.ErrorWriter = (errorWriter == null) ? Console.Error : errorWriter; this.InfoWriter = (infoWriter == null) ? Console.Out : infoWriter; this.clm = new ClmLib.Clm(this.component); #endregion this.filterParameters = this.clm.GenerateFilter(alternativeContainer, this.ErrorWriter, this.InfoWriter); RefreshLocalComponentList(); }
public ConfigurationSelection ShowConfigurationSelectionForm(IMgaModel context) { if (context == null) { throw new ArgumentNullException(); } ConfigurationSelection results = new ConfigurationSelection() { Context = context }; var configurationGroups = this.GetConfigurationGroups(context); ConfigurationSelectionInput configurationSelectionInput = new ConfigurationSelectionInput(); AnalysisModelProcessor analysisModelProcessor = null; this.ExecuteInTransaction(context, () => { analysisModelProcessor = AnalysisModelProcessor.GetAnalysisModelProcessor(context); configurationSelectionInput.Context = GMELightObject.GetGMELightFromMgaObject(context); configurationSelectionInput.Groups = configurationGroups.Select(x => x.ConvertToLight()).ToArray(); configurationSelectionInput.IsDesignSpace = configurationGroups.Any(x => x.Owner == null) == false; configurationSelectionInput.OperationModeInformation = string.Format("{0} - {1}", SplitCamelCase(analysisModelProcessor.GetInvokedObject().MetaBase.Name), SplitCamelCase(analysisModelProcessor.OriginalSystemUnderTest.Referred.DesignEntity.Kind)); configurationSelectionInput.OutputDirectory = analysisModelProcessor.GetResultsDirectory(); configurationSelectionInput.Target = GMELightObject.GetGMELightFromMgaObject(analysisModelProcessor.OriginalSystemUnderTest.Impl); }); var interpreters = analysisModelProcessor.GetWorkflow(); configurationSelectionInput.InterpreterNames = interpreters.Select(x => x.Name).ToArray(); using (ConfigurationSelectionForm selectionForm = new ConfigurationSelectionForm(configurationSelectionInput)) { System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.DialogResult.None; if (this.IsInteractive) { dialogResult = selectionForm.ShowDialog(); this.Logger.GMEConsoleLoggingLevel = selectionForm.ConfigurationSelectionResult.VerboseLogging ? CyPhyGUIs.GMELogger.MessageType_enum.Debug : CyPhyGUIs.SmartLogger.MessageType_enum.Info; } else { selectionForm.SaveSettingsAndResults(); dialogResult = System.Windows.Forms.DialogResult.OK; } if (dialogResult == System.Windows.Forms.DialogResult.OK) { var selectionResult = selectionForm.ConfigurationSelectionResult; results.KeepTemporaryModels = selectionResult.KeepTemporaryModels; results.OpenDashboard = selectionResult.OpenDashboard; results.PostToJobManager = selectionResult.PostToJobManager; results.SelectedConfigurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); this.ExecuteInTransaction(context, () => { foreach (var selectedId in selectionResult.SelectedConfigurations.Select(x => x.GMEId)) { var selectedGmeObject = context.Project.GetObjectByID(selectedId); if (selectedGmeObject == null) { throw new NullReferenceException("Selected configuration was not found in the project tree."); } results.SelectedConfigurations.Append(selectedGmeObject as MgaFCO); } }); } else { throw new ExecutionCanceledByUserException("Main form was canceled."); } } return results; }
/// <summary> /// /// </summary> /// <param name="context">TestBench, PET, PCC, or SoT</param> /// <returns>CWCs (if configurations are not exported) and ComponentAssembly elements</returns> public IMgaFCOs GetConfigurations(IMgaModel context) { if (context == null) { throw new ArgumentNullException(); } this.Logger.WriteDebug("Getting configurations for context"); IMgaFCOs configurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); foreach (var config in this.GetConfigurationGroups(context).SelectMany(x => x.Configurations.Cast<MgaFCO>())) { configurations.Append(config); } this.Logger.WriteDebug("Got {0} configurations for context", configurations.Count); return configurations; }
private void TurnOnAddons(IMgaModel context) { this.ExecuteInTransaction(context, () => { var addons = context.Project.AddOnComponents.Cast<IMgaComponentEx>().Where(x => this.addonNames.Contains(x.ComponentName)); foreach (var addon in addons) { try { addon.Enable(true); } catch (Exception ex) { // if one fails keep trying the other ones. this.Logger.WriteDebug("Turing on addon failed: {0} --> {1}", addon.ComponentName, ex.ToString()); } } }); }
private MasterInterpreterResult RunAnalysisModelProcessors( IMgaModel context, IMgaFCO configuration, bool postToJobManager = false, bool keepTempModels = false) { if (context == null || configuration == null) { throw new ArgumentNullException(); } this.Logger.WriteDebug("Preparing analysis model processor"); var result = new MasterInterpreterResult(); result.Context = context; result.Configuration = configuration; result.Success = true; string contextName = string.Empty; string configurationName = string.Empty; AnalysisModelProcessor analysisModelProcessor = null; Exception exceptionToThrow = null; try { this.Logger.WriteDebug("Turning off addons for perfomance reasons: {0}", string.Join(", ", this.addonNames)); this.TurnOffAddons(context); this.ExecuteInTransaction(context, () => { contextName = context.Name; configurationName = configuration.Name; this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 0, Context = contextName, Configuration = configuration.AbsPath, Title = "Initializing" }); // expand context for configuration this.Logger.WriteDebug("Getting analysis model processor instance for {0} type", context.MetaBase.Name); analysisModelProcessor = AnalysisModelProcessor.GetAnalysisModelProcessor(context); this.Logger.WriteDebug("Got {0} for {1} {2}", analysisModelProcessor.GetType().Name, context.MetaBase.Name, context.AbsPath); this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 25, Context = contextName, Configuration = configurationName, Title = "Expanding" }); if (configuration.MetaBase.Name == typeof(CyPhy.CWC).Name) { this.Logger.WriteDebug("{0} was specified as configuration. Start expanding it. {1}", configuration.MetaBase.Name, configuration.AbsPath); analysisModelProcessor.Expand(CyPhyClasses.CWC.Cast(configuration)); this.Logger.WriteDebug("Expand finished for {0}", configuration.AbsPath); } else if (configuration.MetaBase.Name == typeof(CyPhy.ComponentAssembly).Name) { this.Logger.WriteDebug("{0} was specified as configuration. Start expanding it. {1}", configuration.MetaBase.Name, configuration.AbsPath); analysisModelProcessor.Expand(CyPhyClasses.ComponentAssembly.Cast(configuration)); this.Logger.WriteDebug("Expand finished for {0}", configuration.AbsPath); } else { this.Logger.WriteDebug("{0} expand is not supported {1}", configuration.MetaBase.Name, configuration.AbsPath); throw new AnalysisModelContextNotSupportedException("Configuration type is not supported. Use CWC or Component Assembly."); } // TODO: give progress update about exporters & their success // design space might be saved multiple times if (analysisModelProcessor.OriginalSystemUnderTest.AllReferred is CyPhy.DesignContainer) { this.Logger.WriteDebug("Calling design space exporter"); bool successDesignSpaceExport = analysisModelProcessor.SaveDesignSpace(this.ProjectManifest); // FIXME: this would case the entire test bench to fail if it is a single configuration. // result.Success = result.Success && successDesignSpaceExport; if (successDesignSpaceExport) { this.Logger.WriteDebug("Design space exporter succeeded."); } else { this.Logger.WriteWarning("Design space exporter failed."); } } else { this.Logger.WriteDebug("[SKIP] Calling design space exporter, since the test bench is defined over a design and not a design space."); } this.Logger.WriteDebug("Calling design exporter"); bool successDesignExport = analysisModelProcessor.SaveDesign(this.ProjectManifest); // result.Success = result.Success && successDesignExport; if (successDesignExport) { this.Logger.WriteDebug("Design exporter succeeded."); } else { this.Logger.WriteWarning("Design exporter failed."); } this.Logger.WriteDebug("Saving test bench definition"); bool successTestBench = analysisModelProcessor.SaveTestBench(this.ProjectManifest); // result.Success = result.Success && successTestBench; if (successTestBench) { this.Logger.WriteDebug("Saving test bench definition succeeded."); } else { this.Logger.WriteWarning("Saving test bench definition failed."); } this.Logger.WriteDebug("Saving test bench manifest"); bool successTestBenchManifest = analysisModelProcessor.SaveTestBenchManifest(this.ProjectManifest); result.Success = result.Success && successTestBenchManifest; if (successTestBenchManifest) { this.Logger.WriteDebug("Saving test bench manifest succeeded."); } else { this.Logger.WriteError("Saving test bench manifest failed."); } this.Logger.WriteDebug("Serializing Project manifest file with updates."); this.ProjectManifest.Serialize(); this.Logger.WriteDebug("Project manifest was successfully saved."); }); this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 45, Context = contextName, Configuration = configurationName, Title = "Model is ready for interpreters" }); if (this.IsInteractive) { this.Logger.WriteDebug("Execution is interactive, showing interpreter configuration forms."); analysisModelProcessor.ShowInterpreterConfigs(this.interpreterConfigurations); } else { analysisModelProcessor.ShowInterpreterConfigs(this.interpreterConfigurations, interactive: false); this.Logger.WriteDebug("Execution is non interactive, not showing interpreter configuration forms. Using settings from files."); } analysisModelProcessor.InterpreterProgress += (object sender, InterpreterProgressEventArgs e) => { var interpreterName = e.Interpreter == null ? string.Empty : e.Interpreter.Name; this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 50 + (e.Percent / 5), // we have 20 percent room on the main progress Context = contextName, Configuration = configurationName, Title = string.Format("Running interpreters {0}% {1} success status: {2}", e.Percent, interpreterName, e.Success) }); }; this.Logger.WriteDebug("Running interpreters. Keeping temp models: {0}", keepTempModels); bool isVerbose = this.Logger.GMEConsoleLoggingLevel == CyPhyGUIs.SmartLogger.MessageType_enum.Debug; analysisModelProcessor.RunInterpreters(keepTempModels == false, isVerbose); result.OutputDirectory = analysisModelProcessor.OutputDirectory; this.Logger.WriteDebug("Interpreters finished."); this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 70, Context = contextName, Configuration = configurationName, Title = "All interpreters successfully finished" }); this.ExecuteInTransaction(context, () => { if (postToJobManager) { this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 80, Context = contextName, Configuration = configurationName, Title = "Posting to Job Manager" }); if (this.Manager == null) { this.Logger.WriteDebug("Job manager instance is null. Initializing one."); this.Manager = new JobManagerDispatch(); this.Logger.WriteDebug("Job manager dispatch is ready to receive jobs"); } this.Logger.WriteDebug("Posting to the job manager"); var postedToJobManager = analysisModelProcessor.PostToJobManager(this.Manager); result.Success = result.Success && postedToJobManager; if (postedToJobManager) { this.Logger.WriteInfo("Job posted to the job manager: {0}", context.Name); } else { this.Logger.WriteError("Job was not posted to the job manager: {0}", context.Name); } this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 89, Context = contextName, Configuration = configurationName, Title = "Posted to Job Manager" }); } else { this.Logger.WriteDebug("Not posting to the job manager"); this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 89, Context = contextName, Configuration = configurationName, Title = "Skip posting to Job Manager" }); } }); } catch (AnalysisModelInterpreterConfigurationFailedException ex) { this.Logger.WriteDebug(ex.ToString()); result.Success = false; result.Message = ex.Message; result.Exception = ex.ToString(); exceptionToThrow = ex; } catch (AnalysisModelInterpreterException ex) { this.Logger.WriteDebug(ex.ToString()); result.Success = false; result.Message = ex.Message; result.Exception = ex.ToString(); } catch (AnalysisModelExpandFailedException ex) { this.Logger.WriteDebug(ex.ToString()); result.Success = false; result.Message = ex.Message; result.Exception = ex.ToString(); } catch (Exception ex) { this.Logger.WriteDebug(ex.ToString()); result.Success = false; result.Message = ex.Message; if (ex.InnerException != null) { result.Message = string.Format("{0} ---> {1}", ex.Message, ex.InnerException.Message); } result.Exception = ex.ToString(); } finally { // clean up if interpreter is canceled this.ExecuteInTransaction(context, () => { // destroy objects if keepTempModels == false if (keepTempModels == false) { this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 90, Context = contextName, Configuration = configurationName, Title = "Removing temporary models" }); this.Logger.WriteDebug("Removing temporary models."); analysisModelProcessor.DeleteTemporaryObjects(); this.Logger.WriteDebug("Temporary models are removed."); this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 100, Context = contextName, Configuration = configurationName, Title = "Removing temporary models" }); } else { this.OnSingleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 100, Context = contextName, Configuration = configurationName, Title = "Keeping temporary models" }); } }); this.Logger.WriteDebug("Turning addons back on: {0}", string.Join(", ", this.addonNames)); this.TurnOnAddons(context); } if (exceptionToThrow != null) { this.Logger.WriteDebug(exceptionToThrow.ToString()); throw exceptionToThrow; } return result; }
/// <summary> /// Factory method to get a new analysis model processor instance based on a given context. /// </summary> /// <param name="context">Model context</param> /// <returns>New instance of an analysis model processor.</returns> /// <exception cref="ArgumentNullException">If context is null.</exception> /// <exception cref="AnalysisModelContextNotSupportedException">If context is not supported.</exception> public static AnalysisModelProcessor GetAnalysisModelProcessor(IMgaModel context) { if (context == null) { throw new ArgumentNullException("context"); } AnalysisModelProcessor analysisModelProcessor = null; if (context.MetaBase.Name == typeof(CyPhy.ParametricExploration).Name) { analysisModelProcessor = new ParametricExplorationProcessor(CyPhyClasses.ParametricExploration.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.TestBenchSuite).Name) { analysisModelProcessor = new TestBenchSuiteProcessor(CyPhyClasses.TestBenchSuite.Cast(context)); } else if (TestBenchTypeProcessor.SupportedTestBenchTypes.Contains(context.MetaBase.Name)) { if (context.Meta.Name == typeof(CyPhy.CFDTestBench).Name) { string[] openFoamKinds = new string[] { typeof(CyPhy.CalmWaterSolverSettings).Name, typeof(CyPhy.CorrelationSettings).Name, typeof(CyPhy.WaveResistanceSolverSettings).Name }; if (context.ChildFCOs.Cast <MgaFCO>().Any(fco => openFoamKinds.Contains(fco.Meta.Name))) { analysisModelProcessor = new MultiJobRunProcessor(CyPhyClasses.CFDTestBench.Cast(context)); } else { analysisModelProcessor = new TestBenchTypeProcessor(CyPhyClasses.TestBenchType.Cast(context)); } } else if (context.Meta.Name == typeof(CyPhy.BlastTestBench).Name) { var blastTestBench = CyPhyClasses.BlastTestBench.Cast(context); int tierLevel = (int)blastTestBench.Attributes.BlastTier; int tierThresholdForMuliJobRun = (int)CyPhyClasses.BlastTestBench.AttributesClass.BlastTier_enum._2; if (tierLevel > tierThresholdForMuliJobRun) { // use MultiJobRunProcessor if the current tier level is greater than the defined threshold analysisModelProcessor = new MultiJobRunProcessor(blastTestBench); } else { analysisModelProcessor = new TestBenchTypeProcessor(blastTestBench); } } else if (context.Meta.Name == typeof(CyPhy.BallisticTestBench).Name) { var ballisticTestBench = CyPhyClasses.BallisticTestBench.Cast(context); int tierLevel = (int)ballisticTestBench.Attributes.Tier; int tierThresholdForMuliJobRun = (int)CyPhyClasses.BallisticTestBench.AttributesClass.Tier_enum._2; if (tierLevel > tierThresholdForMuliJobRun) { // use MultiJobRunProcessor if the current tier level is greater than the defined threshold analysisModelProcessor = new MultiJobRunProcessor(ballisticTestBench); } else { analysisModelProcessor = new TestBenchTypeProcessor(ballisticTestBench); } } else { // test bench type analysisModelProcessor = new TestBenchTypeProcessor(CyPhyClasses.TestBenchType.Cast(context)); } } else { throw new AnalysisModelContextNotSupportedException(string.Format("{0} does not supported", context.MetaBase.Name)); } analysisModelProcessor.OriginalCurrentFCOName = context.Name; return(analysisModelProcessor); }
public ContextCheckerResult[] CheckContext(IMgaModel context) { if (context == null) { throw new ArgumentNullException(); } this.Logger.WriteDebug("Entering Context checker"); List<ContextCheckerResult> results = new List<ContextCheckerResult>(); this.ExecuteInTransaction(context, () => { if (context == null) { throw new ArgumentNullException("Context is null."); } this.Logger.WriteDebug("Getting context checker for {0}", context.MetaBase.Name); var contextChecker = ContextChecker.GetContextChecker(context); if (contextChecker == null) { this.Logger.WriteDebug("Failed to get context checker for {0}", context.MetaBase.Name); throw new ArgumentOutOfRangeException("Context is invalid."); } this.Logger.WriteDebug("Got context checker {0} for context {1}", contextChecker.GetType().Name, context.MetaBase.Name); this.Logger.WriteDebug("Checking context"); contextChecker.Check(); this.Logger.WriteDebug("Context is checked"); results = contextChecker.Details; }); return results.ToArray(); }
private ConfigurationGroup[] GetConfigurationGroups(IMgaModel context) { if (context == null) { throw new ArgumentNullException(); } List<ConfigurationGroup> configurationGroups = new List<ConfigurationGroup>(); IMgaFCOs configurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); this.ExecuteInTransaction(context, () => { CyPhy.TestBenchType testBenchType = null; if (context.MetaBase.Name == typeof(CyPhy.ParametricExploration).Name) { testBenchType = CyPhyClasses.ParametricExploration.Cast(context).Children.TestBenchRefCollection.FirstOrDefault().Referred.TestBenchType; } else if (context.MetaBase.Name == typeof(CyPhy.TestBenchSuite).Name) { testBenchType = CyPhyClasses.TestBenchSuite.Cast(context).Children.TestBenchRefCollection.FirstOrDefault().Referred.TestBenchType; } else { // test bench type testBenchType = CyPhyClasses.TestBenchType.Cast(context); } var referredSut = testBenchType.Children.TopLevelSystemUnderTestCollection.FirstOrDefault().Referred.DesignEntity; if (referredSut is CyPhy.ComponentAssembly) { configurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); configurations.Append(referredSut.Impl as MgaFCO); configurationGroups.Add(new ConfigurationGroup() { Configurations = configurations }); } else if (referredSut is CyPhy.DesignContainer) { var configItems = (referredSut as CyPhy.DesignContainer) .Children .ConfigurationsCollection; foreach (CyPhy.Configurations configItem in configItems) { configurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); foreach (var cwc in configItem.Children.CWCCollection) { if (cwc.DstConnections.Config2CACollection.Any()) { foreach (var componentAssemblyRef in cwc.DstConnections.Config2CACollection.Select(x => x.DstEnds.ComponentAssemblyRef)) { if (componentAssemblyRef.Referred.ComponentAssembly != null) { configurations.Append(componentAssemblyRef.Referred.ComponentAssembly.Impl as MgaFCO); } else { this.Logger.WriteWarning("Null reference to generated component assembly for {0} within {1}.", cwc.Name, configItem.Name); } } } else { // CA exporter will be required to call configurations.Append(cwc.Impl as MgaFCO); } } configurationGroups.Add(new ConfigurationGroup() { Configurations = configurations, IsDirty = configItem.Attributes.isDirty, Owner = configItem.Impl as MgaModel }); } } else { throw new NotImplementedException(); } }); return configurationGroups.ToArray(); }
public void Main(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, ComponentStartMode startMode) { GMEConsole.Clear(); System.Windows.Forms.Application.DoEvents(); IMgaFCO selectedObj = null; bool isContextValid = CheckForValidContext(currentobj); if (isContextValid == false) { return; } // get all the ComponentRefs in the DesignContainer var crefs = (currentobj as IMgaModel). ChildFCOs. Cast <IMgaFCO>(). Where(x => x.MetaBase.Name == "ComponentRef"); // If there is exactly '1', select it if (crefs.Count() == 1) { selectedObj = crefs.FirstOrDefault(); } if (selectedObj == null) { if (selectedobjs.Count != 1) { GMEConsole.Error.WriteLine(SelectedObjErrorMessage); return; } selectedObj = selectedobjs.Cast <IMgaFCO>().FirstOrDefault(); } if (selectedObj == null) { GMEConsole.Error.WriteLine(SelectedObjErrorMessage); return; } if (selectedObj.MetaBase.Name != "ComponentRef") { GMEConsole.Error.WriteLine(SelectedObjErrorMessage); return; } if ((selectedObj as IMgaReference).Referred == null) { GMEConsole.Error.WriteLine("Selected ComponentRef is a null reference."); return; } GMEConsole.Info.WriteLine("Running CLM_light..."); // everything is checked we can operate on the objects IMgaFCO designContainer = currentobj; IMgaFCO componentRef = selectedObj; IMgaModel component = (selectedObj as IMgaReference).Referred as IMgaModel; GMEConsole.Info.WriteLine("Discovering components."); //GMEConsole.Info.WriteLine("{0} components were found.", components.Count); // TODO: filter detected components if needed using (ComponentSelectionForm csf = new ComponentSelectionForm(component, currentobj as IMgaModel, GMEConsole.Error, GMEConsole.Info)) { var dialogresult = csf.ShowDialog(); if (dialogresult == System.Windows.Forms.DialogResult.OK) { GMEConsole.Info.WriteLine("Inserting new components."); List <IMgaFCO> components = new List <IMgaFCO>(); foreach (var item in csf.dgvSelector.SelectedRows) { var dgvr = item as System.Windows.Forms.DataGridViewRow; var cli = dgvr.DataBoundItem as ComponentListItem; components.Add(cli.Fco); } GMEConsole.Info.WriteLine("{0} components were selected.", components.Count); List <KeyValuePair <IMgaFCO, string> > messages = new List <KeyValuePair <IMgaFCO, string> >(); var insertedComponents = InsertComponents(designContainer, componentRef, components, messages); } } GMEConsole.Info.WriteLine("Done."); }
public MasterInterpreterResult[] RunInTransactionOnOneConfig( IMgaModel context, IMgaFCO configuration, bool postToJobManager = false, bool keepTempModels = false) { MgaFCOs configurations = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); configurations.Append(configuration as MgaFCO); return this.RunInTransactionOnMultipleConfigs(context, configurations, postToJobManager, keepTempModels); }
public List <IMgaFCO> InsertComponents( IMgaFCO designContainer, IMgaFCO componentRef, List <IMgaFCO> components, List <KeyValuePair <IMgaFCO, string> > messages) { Contract.Requires(designContainer as IMgaModel != null); Contract.Requires(componentRef as IMgaReference != null); Contract.Requires((componentRef as IMgaReference).Referred != null); Contract.Requires(components != null); List <IMgaFCO> result = new List <IMgaFCO>(); IMgaModel container = designContainer as IMgaModel; IMgaReference compRef = componentRef as IMgaReference; var childComps = container. ChildFCOs. Cast <IMgaFCO>(). Where(x => x.MetaBase.Name == "ComponentRef"). Cast <IMgaReference>(). Select(x => x.Referred). ToList(); // get all connections which has the componentRef as an endpoint var childConnections = container. ChildFCOs. Cast <IMgaFCO>(). Where(x => x is IMgaSimpleConnection). Cast <IMgaSimpleConnection>(). ToList(); // ith new component int iNewComponent = 0; foreach (var compToCreate in components) { if (childComps.Contains(compToCreate)) { // If the component already exists this function will not create it again // skip messages.Add(new KeyValuePair <IMgaFCO, string>(compToCreate, "Component already exists.")); continue; } // create reference var newRef = container.CreateReference(componentRef.MetaRole, compToCreate as MgaFCO); newRef.Name = compToCreate.Name; //////// //VehicleForge.VFSession session = null; //VFComponentExchange results = session.SendGetRequest<VFComponentExchange>(""); //VFComponentExchange resultjson = Newtonsoft.Json.JsonConvert.DeserializeObject<VFComponentExchange>(""); //////// result.Add(newRef); bool compatible = true; // create connections foreach (var connectionToCreate in childConnections) { if (SafeMgaObjectCompare(connectionToCreate.SrcReferences.Cast <IMgaFCO>().FirstOrDefault(), compRef) || SafeMgaObjectCompare(connectionToCreate.DstReferences.Cast <IMgaFCO>().FirstOrDefault(), compRef)) { try { var connRole = connectionToCreate.MetaRole; var connSrc = connectionToCreate.Src; var connDst = connectionToCreate.Dst; var connSrcReference = connectionToCreate.SrcReferences.Cast <MgaFCO>().FirstOrDefault(); var connDstReference = connectionToCreate.DstReferences.Cast <MgaFCO>().FirstOrDefault(); // overwrite the new endpoints if (SafeMgaObjectCompare(connectionToCreate.SrcReferences.Cast <IMgaFCO>().FirstOrDefault(), compRef)) { connSrcReference = newRef; // Check for objects with same name and same type var srcCandidates = compToCreate.ChildObjects.OfType <MgaFCO>().Where(x => x.Name == connSrc.Name && x.Meta.Name == connSrc.Meta.Name); MgaFCO srcCandidate = srcCandidates.FirstOrDefault(); if (srcCandidates.Count() > 1) { messages.Add(new KeyValuePair <IMgaFCO, string>( compToCreate, "Not Inserted. It has more than one matching object named: " + connSrc.Name)); compatible = false; } if (srcCandidate == null) { messages.Add(new KeyValuePair <IMgaFCO, string>( compToCreate, "Not Inserted. It does not have a port with name: " + connSrc.Name)); compatible = false; } connSrc = srcCandidate; } if (SafeMgaObjectCompare(connectionToCreate.DstReferences.Cast <IMgaFCO>().FirstOrDefault(), compRef)) { connDstReference = newRef; //var dstCandidate = compToCreate.ObjectByPath[connDst.Name] as MgaFCO; var dstCandidates = compToCreate.ChildObjects.OfType <MgaFCO>().Where(x => x.Name == connDst.Name && x.Meta.Name == connDst.Meta.Name); MgaFCO dstCandidate = dstCandidates.FirstOrDefault(); if (dstCandidates.Count() > 1) { messages.Add(new KeyValuePair <IMgaFCO, string>( compToCreate, "Not Inserted. It has more than one matching object named: " + connDst.Name)); compatible = false; } if (dstCandidate == null) { messages.Add(new KeyValuePair <IMgaFCO, string>( compToCreate, "Not Inserted. It does not have port with name: " + connDst.Name)); compatible = false; } connDst = dstCandidate; } // check end points if (connSrc != null && connDst != null) { var newConnection = container.CreateSimpleConnDisp( connRole, connSrc, connDst, connSrcReference, connDstReference); } } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.ToString()); System.Diagnostics.Trace.TraceError("Probably some ports do not match."); compatible = false; } } } if (compatible) { iNewComponent = iNewComponent + 1; foreach (IMgaPart part in newRef.Parts) { int x = 0; int y = 0; string icon; componentRef.PartByMetaPart[part.Meta].GetGmeAttrs(out icon, out x, out y); part.SetGmeAttrs(icon, x, y + 80 * iNewComponent); } } else { //messages.Add(new KeyValuePair<IMgaFCO, string>(compToCreate, "Component was skipped: " + compToCreate.Name)); result.Remove(newRef); newRef.DestroyObject(); } } foreach (var item in messages) { GMEConsole.Error.WriteLine("{0}: {1}", item.Key.ToMgaHyperLink(), item.Value); } GMEConsole.Info.WriteLine("{0} components were inserted. Detailed list as follows:", result.Count); foreach (var item in result) { GMEConsole.Info.WriteLine("- {0}", item.ToMgaHyperLink()); } return(result); }
/// <summary> /// Gets a new instance of a context checker based on a given context. /// Note: Execute within transaction. /// </summary> /// <param name="context">Test bench, Parameteric Exploration, or Test bench Suite</param> /// <returns>A new context specific checker if context is supported, otherwise null.</returns> /// <exception cref="ArgumentNullException" /> /// <exception cref="ArgumentOutOfRangeException" /> public static ContextChecker GetContextChecker(IMgaModel context) { if (context == null) { throw new ArgumentNullException(); } ContextChecker contextChecker = null; // get specialized context checker based on the context type. if (context.MetaBase.Name == typeof(CyPhy.TestBench).Name) { contextChecker = new TestBenchChecker(CyPhyClasses.TestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.CADTestBench).Name) { contextChecker = new StructuralFEATestBenchChecker(CyPhyClasses.CADTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.KinematicTestBench).Name) { contextChecker = new KinematicTestBenchChecker(CyPhyClasses.KinematicTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.CFDTestBench).Name) { contextChecker = new CFDTestBenchChecker(CyPhyClasses.CFDTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.BlastTestBench).Name) { contextChecker = new BlastTestBenchChecker(CyPhyClasses.BlastTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.BallisticTestBench).Name) { contextChecker = new BallisticTestBenchChecker(CyPhyClasses.BallisticTestBench.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.TestBenchSuite).Name) { contextChecker = new TestBenchSuiteChecker(CyPhyClasses.TestBenchSuite.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.ParametricExploration).Name) { contextChecker = new ParametricExplorationChecker(CyPhyClasses.ParametricExploration.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.CarTestBench).Name) { contextChecker = new CarTestBenchChecker(CyPhyClasses.CarTestBench.Cast(context)); } else { throw new ArgumentOutOfRangeException(string.Format("Given context is {0}, which is not supported. Try to run it on a test bench, PET or SoT.", context.Meta.Name)); } return contextChecker; }
public Dictionary <string, ComponentLibraryFilterParameter> GenerateFilter( IMgaModel alternativeDesignContainer, System.IO.TextWriter errorWriter = null, System.IO.TextWriter infoWriter = null) { var consoleErrorLogger = (errorWriter == null) ? Console.Error : errorWriter; var consoleInfoLogger = (infoWriter == null) ? Console.Out : infoWriter; Dictionary <string, ComponentLibraryFilterParameter> filterParams = new Dictionary <string, ComponentLibraryFilterParameter>(); List <string> filtersWithConflictingMaxMin = new List <string>(); // Get all the PropertyConstraint objects in the DesignContainer var propertyConstraints = alternativeDesignContainer.ChildFCOs.OfType <MgaAtom>().Where(x => x.Meta.Name == "PropertyConstraint"); // Iterate over the PropertyConstraint collection and create/modify filters: foreach (MgaFCO propConstraint in propertyConstraints) { string filterName = null; string filterUnit = null; string targetType = propConstraint.StrAttrByName["TargetType"]; double targetValue = propConstraint.FloatAttrByName["TargetValue"]; // Check if they are connected to a Property var propertyConstraintConnectionPoints = propConstraint.PartOfConns; // One PropertyConstraint might be connected to multiple Properties (valid in GME); might need to create multiple filters per foreach (MgaConnPoint cp in propertyConstraintConnectionPoints) { MgaConnection conn = (cp as MgaConnPoint).Owner; if (conn.Meta.Name != "PropertyConstraintBinding") { continue; } else { // get the Property MgaFCO property = (conn as IMgaSimpleConnection).Dst; // We want to skip PropertyConstraints connected directly to the selected Component (they don't agree with Desert...) if (property.ParentModel.ID == this.CyPhyComponent.ID) { errorWriter.WriteLine( "PropertyConstraint '{0}' should not be connected directly to the ComponentRef Property. Constraint on Property '{1}' will be ignored.", propConstraint.Name, property.Name); infoWriter.WriteLine( "Please create a Property within this DesignContainer, name it 'ComponentProperty.Name', and connect the PropertyConstraint."); continue; } // Check if the 'floating' Property has a matching property (by name) in the selected component bool componentHasMatchingProperty = false; foreach (MgaConnPoint connPoint in property.PartOfConns) { MgaConnection valueFlow = connPoint.Owner; if (valueFlow.Meta.Name != "ValueFlow") { continue; } // check if the ValueFlow is FROM the component TO the 'floating' property MgaFCO dst = (valueFlow as IMgaSimpleConnection).Dst; MgaFCO src = (valueFlow as IMgaSimpleConnection).Src; if (property != dst) { errorWriter.WriteLine( "DesignContainer Property '{0}' is the Source of a ValueFlow into '{1}'; Constraint '{2}' will be ignored.", property.Name, dst.Name, propConstraint.Name); infoWriter.WriteLine( "To correctly filter your search results, DesignContainer Properties must get their values from Component Properties."); continue; } bool srcIsWithinComponent = src.ParentModel.ID == this.CyPhyComponent.ID; bool namesMatch = property.Name == src.Name; if (srcIsWithinComponent && namesMatch) { componentHasMatchingProperty = true; break; } } if (!componentHasMatchingProperty) { errorWriter.WriteLine( "Property '{0}' is not connected to a Property with a matching name. Constraint '{1}' will be ignored.", property.Name, propConstraint.Name); infoWriter.WriteLine( "To correctly filter your search results, the names of DesignContainer Properties must match the Properties within Components."); continue; } filterName = property.Name; if ((property as MgaReference).Referred != null) { // TODO: Might need to use Adam's QUDT stuff to get the correct unit; for now, just get the referred unit's name. filterUnit = (property as MgaReference).Referred.Name; } } // if that property already has a filter, modify it (add max, add min) // else create a new filter for this property //bool discreteFilter = false; double newMaximum = double.NaN; double newMinimum = double.NaN; //double myEpsilon = targetValue * 1E-12; double scaledEpsilon = targetValue == 0 ? double.Epsilon : Math.Pow(10, Math.Floor(Math.Log10(targetValue)) - 15); switch (targetType) { case "Must Be Less Than": newMaximum = targetValue; break; case "Must Not Exceed": newMaximum = targetValue + scaledEpsilon; break; case "Must Equal": newMaximum = targetValue + scaledEpsilon; newMinimum = targetValue - scaledEpsilon; //discreteFilter = true; break; case "Must Equal or Exceed": newMinimum = targetValue - scaledEpsilon; break; default: // "Must Exceed" newMinimum = targetValue; break; } // Create a new filter object ContinuousFilterParameter newParam = new ContinuousFilterParameter(filterName); // Check if there is an existing filter with this name if (filterParams.ContainsKey(filterName)) { // Get the existing filter ComponentLibraryFilterParameter filterParameter = filterParams[filterName]; // Type check it if (filterParameter is ContinuousFilterParameter) { // Assign it to this local var to modify it newParam = filterParameter as ContinuousFilterParameter; } } // Overwrite filter attributes with new info, or leave them as before double currentMinimum = double.MinValue; double currentMaximum = double.MaxValue; // check if the PropertyConstraint could affect the filter's minimum value if (!double.IsNaN(newMinimum)) { // if the current MinValue is of type 'double', compare with newMinimum, possibly overwrite if (double.TryParse(newParam.MinValue, out currentMinimum)) { if (newMinimum > currentMinimum) { // the 'new' PropertyConstraint minimum is higher (more strict) than the existing one; overwrite it newParam.MinValue = newMinimum.ToString("G17"); } } } // check if the PropertyConstraint could affect the filter's maximum value if (!double.IsNaN(newMaximum)) { // if the current MaxValue is of type 'double', compare with newMaximum, possibly overwrite if (double.TryParse(newParam.MaxValue, out currentMaximum)) { if (newMaximum < currentMaximum) { // the 'new' PropertyConstraint maximum is lower (more strict) than the existing one; overwrite it newParam.MaxValue = newMaximum.ToString("G17"); } } } newParam.Unit = filterUnit != null ? filterUnit : null; filterParams[filterName] = newParam; // check if a filter's minimum is greater than its maximum, log the conflict if (double.TryParse(newParam.MaxValue, out currentMaximum) && double.TryParse(newParam.MinValue, out currentMinimum)) { if (currentMaximum < currentMinimum) { filtersWithConflictingMaxMin.Add(filterName); } } //if (discreteFilter) //{ // continue; // //DiscreteFilterParameter newParam = new DiscreteFilterParameter(filterName); // //List<string> filterParameterValues = new List<string>(); // //filterParameterValues.Add(targetValue.ToString()); // //newParam.Values = filterParameterValues; // //filterParams[filterName] = newParam; //} //else //{ // Make a ContinuousFilter (this is done in all cases) //} } } foreach (string name in filtersWithConflictingMaxMin) { if (filterParams.ContainsKey(name)) { string min = (filterParams[name] as ContinuousFilterParameter).MinValue; string max = (filterParams[name] as ContinuousFilterParameter).MaxValue; consoleErrorLogger.WriteLine( "Property '{0}' has conflicting PropertyConstraints (Min {1} > Max {2}); no filter will be generated.", name, min, max); filterParams.Remove(name); } } return(filterParams); }
public static T CreateObject <T>( ISIS.GME.Common.Interfaces.Container parent, string roleStr = null) where T : ISIS.GME.Common.Classes.Base, new() { Contract.Requires(parent != null); T result = new T(); string Kind = typeof(T).Name; if (parent.Impl is IMgaModel) { IMgaModel model = parent.Impl as IMgaModel; MgaMetaRole role = null; if (string.IsNullOrEmpty(roleStr)) { try { // try to use user defined role role = (model.MetaBase as IMgaMetaModel).RoleByName[Kind]; } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Role was not found in the container."); sb.AppendLine("Paradigm violation."); sb.AppendFormat("Container type: {0} Requested role: {1}", parent.Kind, result.GetType().Name); throw new Exception(sb.ToString(), ex); } } else { try { // try to use user defined role role = (model.MetaBase as IMgaMetaModel).RoleByName[roleStr]; } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine("Role was not found in the container."); sb.AppendLine("Paradigm violation."); sb.AppendFormat("Container type: {0} Requested role: {1}", parent.Kind, result.GetType().Name); throw new Exception(sb.ToString(), ex); } } try { MgaFCO fco = model.CreateChildObject(role); result.Impl = fco as IMgaObject; return(result); } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine("New element could not be created."); sb.AppendFormat("Container type: {0} Requested role: {1}", parent.Kind, result.GetType().Name); throw new Exception(sb.ToString(), ex); } } else if (parent.Impl is MgaFolder) { if (string.IsNullOrEmpty(roleStr)) { MgaFolder folder = parent.Impl as MgaFolder; foreach (MgaMetaFolder item in folder.MetaFolder.LegalChildFolders) { if (item.Name == Kind) { MgaFolder f = folder.CreateFolder(item); result.Impl = f as IMgaObject; return(result); } } if (result.Impl == null) { foreach (MgaMetaFCO item in folder.MetaFolder.LegalRootObjects) { if (item.Name == Kind) { IMgaFCO fco = folder.CreateRootObject(item); result.Impl = fco as IMgaObject; return(result); } } } } else { MgaFolder folder = parent.Impl as MgaFolder; foreach (MgaMetaFolder item in folder.MetaFolder.LegalChildFolders) { if (item.Name == roleStr) { MgaFolder f = folder.CreateFolder(item); result.Impl = f as IMgaObject; return(result); } } if (result.Impl == null) { foreach (MgaMetaFCO item in folder.MetaFolder.LegalRootObjects) { if (item.Name == roleStr) { IMgaFCO fco = folder.CreateRootObject(item); result.Impl = fco as IMgaObject; return(result); } } } } } return(null); }
void referenceConnectionCopy() { foreach (IMgaConnection otherIMgaConnection in _iMgaConnectionSet) { IMgaModel otherIMgaConnectionParent = otherIMgaConnection.ParentModel; IMgaModel newIMgaConnectionParent = getCorrespondingIMgaFCO(otherIMgaConnectionParent) as IMgaModel; if (newIMgaConnectionParent == null) { Dictionary <string, IMgaFCO> nameTargetMap = new Dictionary <string, IMgaFCO>(); foreach (IMgaConnPoint otherIMgaConnPoint in otherIMgaConnection.ConnPoints) { nameTargetMap[otherIMgaConnPoint.ConnRole] = otherIMgaConnPoint.Target; } gmeConsole.Error.Write("Could not make connection between "); bool first = true; foreach (string key in nameTargetMap.Keys) { if (first) { first = false; } else { gmeConsole.Error.Write(", "); } gmeConsole.Error.Write("\"" + key + "\"=\"" + nameTargetMap[key].AbsPath + "\""); } gmeConsole.Error.Write(" in main model: Could not access parent (path: \"" + otherIMgaConnectionParent.AbsPath + "\")"); _exitStatus |= Errors.PathError; continue; } IMgaConnection newIMgaConnection = newIMgaConnectionParent.CreateChildObject(otherIMgaConnection.MetaRole) as IMgaConnection; foreach (IMgaConnPoint otherIMgaConnPointToCopy in otherIMgaConnection.ConnPoints) { IMgaFCO otherTarget = otherIMgaConnPointToCopy.Target; MgaFCO newTarget = getCorrespondingIMgaFCO(otherTarget) as MgaFCO; if (newTarget == null) { gmeConsole.Error.WriteLine("Could not find connection target of path \"" + otherTarget.AbsPath + "\" and role \"" + otherIMgaConnPointToCopy.ConnRole + "\" for connection of path \"" + newIMgaConnection.AbsPath + "\""); newIMgaConnection.DestroyObject(); newIMgaConnection = null; _exitStatus |= Errors.PathError; break; } MgaFCOs newMgaFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); bool referenceError = false; foreach (IMgaFCO otherReferenceIMgaFCO in otherIMgaConnPointToCopy.References) { IMgaFCO newReferenceIMgaFCO = getCorrespondingIMgaFCO(otherReferenceIMgaFCO); if (newReferenceIMgaFCO == null) { gmeConsole.Error.WriteLine("Could not make connection reference \"" + otherReferenceIMgaFCO.AbsPath + "\" for connection \"" + newIMgaConnection.AbsPath + "\", role \"" + otherIMgaConnPointToCopy.ConnRole + "\"."); newIMgaConnection.DestroyObject(); newIMgaConnection = null; referenceError = true; _exitStatus |= Errors.PathError; break; } newMgaFCOs.Append(newReferenceIMgaFCO as MgaFCO); } if (referenceError) { break; } MgaConnPoint newMgaConnPoint = null; newIMgaConnection.AddConnPoint(otherIMgaConnPointToCopy.ConnRole, 1, newTarget, newMgaFCOs, out newMgaConnPoint); } if (newIMgaConnection != null) { attributesAndRegistryCopy(newIMgaConnection, otherIMgaConnection); } } }
/// <summary> /// All RunInTransaction public functions should end up calling this function. /// It checks all constraints and initializes the variables. /// <para><remarks>Execute outside of transactions.</remarks></para> /// </summary> /// <param name="context">Master interpreter runs on this model.</param> /// <param name="configurations">Configurations to run the context with.</param> /// <param name="postToJobManager">True posts all jobs to the job manager.</param> /// <param name="keepTempModels">The interpreter will keep all temporary models.</param> /// <returns>Results that represent, which configurations where successful and which ones failed.</returns> /// <exception cref="ArgumentNullException" /> /// <exception cref="InvalidOperationException" /> /// <exception cref="ExecutionCanceledByUserException" /> public MasterInterpreterResult[] RunInTransactionOnMultipleConfigs( IMgaModel context, IMgaFCOs configurations, bool postToJobManager = false, bool keepTempModels = false) { if (context == null || configurations == null) { throw new ArgumentNullException(); } this.Logger.WriteDebug("Start main method for master interpreter."); this.Logger.WriteDebug("Start copying dashboard sync."); this.copyDashboard.Invoke(); if (this.ProjectManifest == null) { this.ExecuteInTransaction(context, () => { this.ProjectManifest = this.CreateOrUpdateProjectManifest(context.Project); }); } string projectPath = this.ProjectManifest.OutputDirectory; this.Logger.WriteDebug("Project directory: {0}", projectPath); // delete all previous interpreter configurations this.interpreterConfigurations.Clear(); var results = new List<MasterInterpreterResult>(); IMgaFCOs resolvedConfigurations = this.ResolveConfigurations(configurations); if (resolvedConfigurations.Count == 0) { this.Logger.WriteInfo("Configurations were not specified. Use all configurations for the given context."); resolvedConfigurations = this.GetConfigurations(context); } var count = 0; this.ExecuteInTransaction(context, () => { count = resolvedConfigurations.Count; }); var currentNumber = 0; this.Logger.WriteInfo("Number of configurations to execute: {0}", count); this.ExecuteInTransaction(context, () => { this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 0, Context = context.Name, Title = "Starting" }); }); this.Logger.WriteDebug("Wait for dashboard copy to finish"); this.Logger.WriteDebug("Dashboard copy finished"); this.ExecuteInTransaction(context, () => { this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 1, Context = context.Name, Title = "Updating local dashboard" }); }); int successes = 0; int failures = 0; foreach (MgaFCO configuration in resolvedConfigurations) { if (this.IsCancelled) { this.Logger.WriteWarning("Execution was cancelled."); break; } this.Logger.WriteDebug("Processing {0} out of {1} [{2} success(es) and {3} failure(s)]", currentNumber + 1, count, successes, failures); this.ExecuteInTransaction(context, () => { this.Logger.WriteDebug("Configuration {0}", configuration.AbsPath); this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = currentNumber * 99 / count, Context = context.Name, Configuration = configuration.Name, Title = string.Format("Processing {0} out of {1} [{2} success(es) and {3} failure(s)]", currentNumber + 1, count, successes, failures) }); }); this.Logger.WriteDebug("Starting analysis model processor"); var thisResult = this.RunAnalysisModelProcessors(context, configuration, postToJobManager, keepTempModels); this.Logger.WriteDebug("Analysis model processor is done"); results.Add(thisResult); currentNumber++; if (thisResult.Success) { successes++; } else { failures++; } } this.Logger.WriteDebug("Generate dashboard script files"); this.GenerateDashboardScriptFiles(); this.Logger.WriteDebug("Dashboard script files generated"); this.ExecuteInTransaction(context, () => { this.OnMultipleConfigurationProgress(new ProgressCallbackEventArgs() { Percent = 100, Context = context.Name, Title = "Finished" }); }); this.Results = results.ToArray(); return this.Results; }
public void connectionCopy() { HashSet <IMgaConnection> otherIMgaConnectionSet = new HashSet <IMgaConnection>(); foreach (IMgaFCO otherIMgaFCO in _hasConnectionList) { IEnumerable <IMgaConnPoint> otherIMgaConnPoints = otherIMgaFCO.PartOfConns.Cast <IMgaConnPoint>(); if (otherIMgaFCO is IMgaReference) { otherIMgaConnPoints = otherIMgaConnPoints.Concat(((IMgaReference)otherIMgaFCO).UsedByConns .Cast <IMgaConnPoint>().Where(cp => cp.References[1] == otherIMgaFCO)); } IMgaFCO newIMgaFCO = getCorrespondingIMgaFCO(otherIMgaFCO); if (newIMgaFCO == null) { gmeConsole.Error.WriteLine("Could not make any connections to \"" + otherIMgaFCO.AbsPath + "\" in main model during merge: FCO not found."); _exitStatus |= Errors.PathError; continue; } // AT THIS POINT, NO CONNECTIONS SHOULD EXIST EXCEPT FOR CONNECTIONS THAT ARE INSTANCE/SUBTYPES foreach (IMgaConnPoint otherIMgaConnPoint in otherIMgaConnPoints) { if (otherIMgaConnPoint.References.Count > 0) { if (!_fcoMap.ContainsKey(otherIMgaConnPoint.References[1])) { continue; } } // GET ACTUAL CONNECTION IMgaConnection otherIMgaConnection = otherIMgaConnPoint.Owner; // ANY CONNECTIONS THAT ARE INSTANCES/SUBTYPES IN THE "OTHER" MODEL (I.E. ORIGINAL MODEL IN THE OTHER FILE) // MUST BE INSTANCES/SUBTYPES IN "NEW" MODEL. I.E. THEY ALREADY EXIST IN THE "NEW" MODEL, SO SKIP if (otherIMgaConnection.ArcheType != null) { continue; } // IF CONNECTION ALREADY PROCESSED, SKIP if (otherIMgaConnectionSet.Contains(otherIMgaConnection)) { continue; } otherIMgaConnectionSet.Add(otherIMgaConnection); _iMgaConnectionSet.Remove(otherIMgaConnection); IMgaModel otherIMgaConnectionParent = otherIMgaConnection.ParentModel; IMgaModel newIMgaConnectionParent = getCorrespondingIMgaFCO(otherIMgaConnectionParent) as IMgaModel; if (newIMgaConnectionParent == null) { gmeConsole.Error.WriteLine("Could not make connection to \"" + otherIMgaFCO.AbsPath + "\" in main model: Could not access parent (path: \"" + otherIMgaConnectionParent.AbsPath + "\")."); _exitStatus |= Errors.PathError; continue; } IMgaConnection newIMgaConnection = newIMgaConnectionParent.CreateChildObject(otherIMgaConnection.MetaRole) as IMgaConnection; foreach (IMgaConnPoint otherIMgaConnPointToCopy in otherIMgaConnection.ConnPoints) { IMgaFCO otherTarget = otherIMgaConnPointToCopy.Target; MgaFCO newTarget = getCorrespondingIMgaFCO(otherTarget) as MgaFCO; if (newTarget == null) { gmeConsole.Error.WriteLine("Could not find connection target of path \"" + otherTarget.AbsPath + "\" and role \"" + otherIMgaConnPointToCopy.ConnRole + "\" for connection of path \"" + newIMgaConnection.AbsPath + "\""); newIMgaConnection.DestroyObject(); newIMgaConnection = null; _exitStatus |= Errors.PathError; break; } MgaFCOs newMgaFCOs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs")); bool referenceError = false; foreach (IMgaFCO otherReferenceIMgaFCO in otherIMgaConnPointToCopy.References) { IMgaFCO newReferenceIMgaFCO = getCorrespondingIMgaFCO(otherReferenceIMgaFCO); if (newReferenceIMgaFCO == null) { gmeConsole.Error.WriteLine("Could not make connection reference \"" + otherReferenceIMgaFCO.AbsPath + "\" for connection \"" + newIMgaConnection.AbsPath + "\", role \"" + otherIMgaConnPointToCopy.ConnRole + "\"."); newIMgaConnection.DestroyObject(); newIMgaConnection = null; referenceError = true; _exitStatus |= Errors.PathError; break; } newMgaFCOs.Append(newReferenceIMgaFCO as MgaFCO); } if (referenceError) { break; } MgaConnPoint newMgaConnPoint = null; newIMgaConnection.AddConnPoint(otherIMgaConnPointToCopy.ConnRole, 1, newTarget, newMgaFCOs, out newMgaConnPoint); } if (newIMgaConnection != null) { attributesAndRegistryCopy(newIMgaConnection, otherIMgaConnection); } } } }
public bool TryCheckContext(IMgaModel context, out ContextCheckerResult[] results) { if (context == null) { throw new ArgumentNullException(); } this.Logger.WriteDebug("Entering TryCheckContext checker"); var success = true; List<ContextCheckerResult> checkerResult = null; this.ExecuteInTransaction(context, () => { if (context == null) { success = false; } if (success) { this.Logger.WriteDebug("Getting context checker for {0}", context.MetaBase.Name); var contextChecker = ContextChecker.GetContextChecker(context); if (contextChecker != null) { this.Logger.WriteDebug("Got context checker {0} for context {1}", contextChecker.GetType().Name, context.MetaBase.Name); this.Logger.WriteDebug("Checking context"); success = contextChecker.TryCheck(); this.Logger.WriteDebug("Context is checked"); checkerResult = contextChecker.Details; } else { success = false; } } }); results = checkerResult.ToArray(); return success; }
public static string GetComponentCategory(IMgaModel component) { Contract.Requires(component != null); string componentCategory = ""; if (component != null) { componentCategory = component.StrAttrByName["Classifications"]; } return componentCategory; }
/// <summary> /// Factory method to get a new analysis model processor instance based on a given context. /// </summary> /// <param name="context">Model context</param> /// <returns>New instance of an analysis model processor.</returns> /// <exception cref="ArgumentNullException">If context is null.</exception> /// <exception cref="AnalysisModelContextNotSupportedException">If context is not supported.</exception> public static AnalysisModelProcessor GetAnalysisModelProcessor(IMgaModel context) { if (context == null) { throw new ArgumentNullException("context"); } AnalysisModelProcessor analysisModelProcessor = null; if (context.MetaBase.Name == typeof(CyPhy.ParametricExploration).Name) { analysisModelProcessor = new ParametricExplorationProcessor(CyPhyClasses.ParametricExploration.Cast(context)); } else if (context.MetaBase.Name == typeof(CyPhy.TestBenchSuite).Name) { analysisModelProcessor = new TestBenchSuiteProcessor(CyPhyClasses.TestBenchSuite.Cast(context)); } else if (TestBenchTypeProcessor.SupportedTestBenchTypes.Contains(context.MetaBase.Name)) { if (context.Meta.Name == typeof(CyPhy.CFDTestBench).Name) { string[] openFoamKinds = new string[] { typeof(CyPhy.CalmWaterSolverSettings).Name, typeof(CyPhy.CorrelationSettings).Name, typeof(CyPhy.WaveResistanceSolverSettings).Name }; if (context.ChildFCOs.Cast<MgaFCO>().Any(fco => openFoamKinds.Contains(fco.Meta.Name))) { analysisModelProcessor = new MultiJobRunProcessor(CyPhyClasses.CFDTestBench.Cast(context)); } else { analysisModelProcessor = new TestBenchTypeProcessor(CyPhyClasses.TestBenchType.Cast(context)); } } else if (context.Meta.Name == typeof(CyPhy.BlastTestBench).Name) { var blastTestBench = CyPhyClasses.BlastTestBench.Cast(context); int tierLevel = (int)blastTestBench.Attributes.BlastTier; int tierThresholdForMuliJobRun = (int)CyPhyClasses.BlastTestBench.AttributesClass.BlastTier_enum._2; if (tierLevel > tierThresholdForMuliJobRun) { // use MultiJobRunProcessor if the current tier level is greater than the defined threshold analysisModelProcessor = new MultiJobRunProcessor(blastTestBench); } else { analysisModelProcessor = new TestBenchTypeProcessor(blastTestBench); } } else if (context.Meta.Name == typeof(CyPhy.BallisticTestBench).Name) { var ballisticTestBench = CyPhyClasses.BallisticTestBench.Cast(context); int tierLevel = (int)ballisticTestBench.Attributes.Tier; int tierThresholdForMuliJobRun = (int)CyPhyClasses.BallisticTestBench.AttributesClass.Tier_enum._2; if (tierLevel > tierThresholdForMuliJobRun) { // use MultiJobRunProcessor if the current tier level is greater than the defined threshold analysisModelProcessor = new MultiJobRunProcessor(ballisticTestBench); } else { analysisModelProcessor = new TestBenchTypeProcessor(ballisticTestBench); } } else { // test bench type analysisModelProcessor = new TestBenchTypeProcessor(CyPhyClasses.TestBenchType.Cast(context)); } } else { throw new AnalysisModelContextNotSupportedException(string.Format("{0} does not supported", context.MetaBase.Name)); } analysisModelProcessor.OriginalCurrentFCOName = context.Name; return analysisModelProcessor; }
public Dictionary<string, ComponentLibraryFilterParameter> GenerateFilter( IMgaModel alternativeDesignContainer, System.IO.TextWriter errorWriter = null, System.IO.TextWriter infoWriter = null) { var consoleErrorLogger = (errorWriter == null) ? Console.Error : errorWriter; var consoleInfoLogger = (infoWriter == null) ? Console.Out : infoWriter; Dictionary<string, ComponentLibraryFilterParameter> filterParams = new Dictionary<string, ComponentLibraryFilterParameter>(); List<string> filtersWithConflictingMaxMin = new List<string>(); // Get all the PropertyConstraint objects in the DesignContainer var propertyConstraints = alternativeDesignContainer.ChildFCOs.OfType<MgaAtom>().Where(x => x.Meta.Name == "PropertyConstraint"); // Iterate over the PropertyConstraint collection and create/modify filters: foreach (MgaFCO propConstraint in propertyConstraints) { string filterName = null; string filterUnit = null; string targetType = propConstraint.StrAttrByName["TargetType"]; double targetValue = propConstraint.FloatAttrByName["TargetValue"]; // Check if they are connected to a Property var propertyConstraintConnectionPoints = propConstraint.PartOfConns; // One PropertyConstraint might be connected to multiple Properties (valid in GME); might need to create multiple filters per foreach (MgaConnPoint cp in propertyConstraintConnectionPoints) { MgaConnection conn = (cp as MgaConnPoint).Owner; if (conn.Meta.Name != "PropertyConstraintBinding") { continue; } else { // get the Property MgaFCO property = (conn as IMgaSimpleConnection).Dst; // We want to skip PropertyConstraints connected directly to the selected Component (they don't agree with Desert...) if (property.ParentModel.ID == this.CyPhyComponent.ID) { errorWriter.WriteLine( "PropertyConstraint '{0}' should not be connected directly to the ComponentRef Property. Constraint on Property '{1}' will be ignored.", propConstraint.Name, property.Name); infoWriter.WriteLine( "Please create a Property within this DesignContainer, name it 'ComponentProperty.Name', and connect the PropertyConstraint."); continue; } // Check if the 'floating' Property has a matching property (by name) in the selected component bool componentHasMatchingProperty = false; foreach (MgaConnPoint connPoint in property.PartOfConns) { MgaConnection valueFlow = connPoint.Owner; if (valueFlow.Meta.Name != "ValueFlow") { continue; } // check if the ValueFlow is FROM the component TO the 'floating' property MgaFCO dst = (valueFlow as IMgaSimpleConnection).Dst; MgaFCO src = (valueFlow as IMgaSimpleConnection).Src; if (property != dst) { errorWriter.WriteLine( "DesignContainer Property '{0}' is the Source of a ValueFlow into '{1}'; Constraint '{2}' will be ignored.", property.Name, dst.Name, propConstraint.Name); infoWriter.WriteLine( "To correctly filter your search results, DesignContainer Properties must get their values from Component Properties."); continue; } bool srcIsWithinComponent = src.ParentModel.ID == this.CyPhyComponent.ID; bool namesMatch = property.Name == src.Name; if (srcIsWithinComponent && namesMatch) { componentHasMatchingProperty = true; break; } } if (!componentHasMatchingProperty) { errorWriter.WriteLine( "Property '{0}' is not connected to a Property with a matching name. Constraint '{1}' will be ignored.", property.Name, propConstraint.Name); infoWriter.WriteLine( "To correctly filter your search results, the names of DesignContainer Properties must match the Properties within Components."); continue; } filterName = property.Name; if ((property as MgaReference).Referred != null) { // TODO: Might need to use Adam's QUDT stuff to get the correct unit; for now, just get the referred unit's name. filterUnit = (property as MgaReference).Referred.Name; } } // if that property already has a filter, modify it (add max, add min) // else create a new filter for this property //bool discreteFilter = false; double newMaximum = double.NaN; double newMinimum = double.NaN; //double myEpsilon = targetValue * 1E-12; double scaledEpsilon = targetValue == 0 ? double.Epsilon : Math.Pow(10, Math.Floor(Math.Log10(targetValue)) - 15); switch (targetType) { case "Must Be Less Than": newMaximum = targetValue; break; case "Must Not Exceed": newMaximum = targetValue + scaledEpsilon; break; case "Must Equal": newMaximum = targetValue + scaledEpsilon; newMinimum = targetValue - scaledEpsilon; //discreteFilter = true; break; case "Must Equal or Exceed": newMinimum = targetValue - scaledEpsilon; break; default: // "Must Exceed" newMinimum = targetValue; break; } // Create a new filter object ContinuousFilterParameter newParam = new ContinuousFilterParameter(filterName); // Check if there is an existing filter with this name if (filterParams.ContainsKey(filterName)) { // Get the existing filter ComponentLibraryFilterParameter filterParameter = filterParams[filterName]; // Type check it if (filterParameter is ContinuousFilterParameter) { // Assign it to this local var to modify it newParam = filterParameter as ContinuousFilterParameter; } } // Overwrite filter attributes with new info, or leave them as before double currentMinimum = double.MinValue; double currentMaximum = double.MaxValue; // check if the PropertyConstraint could affect the filter's minimum value if (!double.IsNaN(newMinimum)) { // if the current MinValue is of type 'double', compare with newMinimum, possibly overwrite if (double.TryParse(newParam.MinValue, out currentMinimum)) { if (newMinimum > currentMinimum) { // the 'new' PropertyConstraint minimum is higher (more strict) than the existing one; overwrite it newParam.MinValue = newMinimum.ToString("G17"); } } } // check if the PropertyConstraint could affect the filter's maximum value if (!double.IsNaN(newMaximum)) { // if the current MaxValue is of type 'double', compare with newMaximum, possibly overwrite if (double.TryParse(newParam.MaxValue, out currentMaximum)) { if (newMaximum < currentMaximum) { // the 'new' PropertyConstraint maximum is lower (more strict) than the existing one; overwrite it newParam.MaxValue = newMaximum.ToString("G17"); } } } newParam.Unit = filterUnit != null ? filterUnit : null; filterParams[filterName] = newParam; // check if a filter's minimum is greater than its maximum, log the conflict if (double.TryParse(newParam.MaxValue, out currentMaximum) && double.TryParse(newParam.MinValue, out currentMinimum)) { if (currentMaximum < currentMinimum) { filtersWithConflictingMaxMin.Add(filterName); } } //if (discreteFilter) //{ // continue; // //DiscreteFilterParameter newParam = new DiscreteFilterParameter(filterName); // //List<string> filterParameterValues = new List<string>(); // //filterParameterValues.Add(targetValue.ToString()); // //newParam.Values = filterParameterValues; // //filterParams[filterName] = newParam; //} //else //{ // Make a ContinuousFilter (this is done in all cases) //} } } foreach (string name in filtersWithConflictingMaxMin) { if (filterParams.ContainsKey(name)) { string min = (filterParams[name] as ContinuousFilterParameter).MinValue; string max = (filterParams[name] as ContinuousFilterParameter).MaxValue; consoleErrorLogger.WriteLine( "Property '{0}' has conflicting PropertyConstraints (Min {1} > Max {2}); no filter will be generated.", name, min, max); filterParams.Remove(name); } } return filterParams; }