Example #1
0
        private static MgaFCO makeFCO(MgaModel parent, string role)
        {
            MgaFCO newFCO = parent.CreateChildObject((parent.Meta as MgaMetaModel).RoleByName[role]);

            newFCO.Name = role;
            return(newFCO);
        }
Example #2
0
        private void VisitComponentAssembly(MgaModel assembly)
        {
            #region Check arguments
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }
            if (assembly.MetaBase.MetaRef != MetaRef["ComponentAssembly"])
            {
                throw new ArgumentException("Input parameter was not a component assembly.", "assembly");
            }
            #endregion
            Logger.WriteDebug("VisitComponentAssembly: {0}", assembly.AbsPath);

            foreach (MgaModel asm in assembly.GetChildrenOfKind("ComponentAssembly"))
            {
                VisitComponentAssembly(asm);
            }

            foreach (MgaModel component in assembly.GetChildrenOfKind("Component"))
            {
                VisitComponent(component as MgaModel);
            }

            foreach (MgaModel connector in assembly.GetChildrenOfKind("Connector"))
            {
                VisitConnector(connector);
            }

            ExpandConnectorCompositionChildren(assembly);
        }
Example #3
0
        private static void GenerateAssemblies(MgaFolder componentAssemblyFolder, MgaModel assembly, int level, MgaModel leaf)
        {
            var elementsOnEachLevel = 2;
            var numberOfLevels      = 6;

            if (level <= numberOfLevels)
            {
                System.Console.Out.WriteLine(level);

                MgaFolder componentAssemblyChildFolder = componentAssemblyFolder.CreateFolder(componentAssemblyFolder.Project.RootMeta.RootFolder.DefinedFolderByName["ComponentAssemblies", true]);

                componentAssemblyChildFolder.Name = string.Format("ComponentAssembly Child folder {0}", level);

                for (int i = 0; i < elementsOnEachLevel; i++)
                {
                    var childAssembly = componentAssemblyChildFolder.CreateRootObject(assembly.Meta) as MgaModel;
                    childAssembly.Name = string.Format("ChildAssembly {0} {1}", level, i);

                    var cref = assembly.CreateChildObject((assembly.Meta as GME.MGA.Meta.MgaMetaModel).RoleByName["ComponentRef"]) as MgaReference;
                    cref.Name = string.Format("ComponentRef {0} {1}", level, i);

                    if (level < numberOfLevels)
                    {
                        cref.Referred = childAssembly as MgaFCO;
                        GenerateAssemblies(componentAssemblyFolder, childAssembly, level + 1, leaf);
                    }
                    else
                    {
                        cref.Referred = leaf as MgaFCO;
                    }
                }
            }
        }
Example #4
0
        public void UnrollComponentAssembly(MgaModel ca)
        {
            Logger.WriteDebug("UnrollComponentAssembly: {0}", ca.AbsPath);

            VisitComponentAssembly(ca);
            DeleteConnectorsAndPorts();
        }
Example #5
0
        private MgaFCO ClonePort(MgaModel parent, MgaFCO oldPort)
        {
            Logger.WriteDebug("ClonePort: {0}", oldPort.AbsPath);

            GME.MGA.Meta.MgaMetaRole role = null;

            foreach (GME.MGA.Meta.MgaMetaRole roleItem in (parent.Meta as GME.MGA.Meta.MgaMetaModel).Roles)
            {
                if (roleItem.Kind.MetaRef == oldPort.MetaBase.MetaRef)
                {
                    role = roleItem;
                    break;
                }
            }

            var newPortFCO = parent.CopyFCODisp(oldPort, role);

            String lastGood = oldPort.ID;
            String iter     = null;

            while (Traceability.TryGetMappedObject(lastGood, out iter) &&
                   lastGood != iter)
            {
                lastGood = iter;
            }
            Traceability.AddItem(newPortFCO.ID, lastGood);

            return(newPortFCO);
        }
Example #6
0
        public void UnrollTestBench(MgaModel tb)
        {
            Logger.WriteDebug("UnrollTestBench: {0}", tb.AbsPath);

            VisitTestBench(tb);
            DeleteConnectorsAndPorts();
        }
Example #7
0
        private void VisitTestComponent(MgaModel testComp)
        {
            #region Check arguments
            if (testComp == null)
            {
                throw new ArgumentNullException("testComp");
            }
            if (testComp.MetaBase.MetaRef != MetaRef["TestComponent"])
            {
                throw new ArgumentException("Input parameter was not a Test Component.", "testComp");
            }
            #endregion
            Logger.WriteDebug("VisitTestComponent: {0}", testComp.AbsPath);

            if (testComp.ArcheType != null)
            {
                Logger.WriteDebug("VisitTestComponent: Has an archetype, detaching {0}", testComp.AbsPath);

                SetAttributesLocally(testComp as MgaFCO);
                testComp.DetachFromArcheType();
            }

            foreach (MgaModel connector in testComp.GetChildrenOfKind("Connector"))
            {
                VisitConnector(connector);
            }
        }
Example #8
0
        private void VisitTestBench(MgaModel testbench)
        {
            #region Check arguments
            if (testbench == null)
            {
                throw new ArgumentNullException("testbench");
            }
            if (testbench.MetaBase.MetaRef != MetaRef["TestBench"])
            {
                throw new ArgumentException("Input parameter was not a connector.", "testbench");
            }
            #endregion
            Logger.WriteDebug("VisitTestBench: {0}", testbench.AbsPath);

            foreach (MgaModel asm in testbench.GetChildrenOfKind("ComponentAssembly"))
            {
                VisitComponentAssembly(asm);
            }

            foreach (MgaModel component in testbench.GetChildrenOfKind("Component"))
            {
                VisitComponent(component);
            }

            foreach (MgaModel testComp in testbench.GetChildrenOfKind("TestComponent"))
            {
                VisitTestComponent(testComp);
            }

            ExpandConnectorCompositionChildren(testbench);
        }
Example #9
0
        public List <TestBench> GetTestbenchesFromModel(MgaProject project, MgaModel currentobj, string outputBaseDir)
        {
            componentParameters = null;
            //this.logFileName = Path.Combine(
            //    Path.GetDirectoryName(project.ProjectConnStr.Substring("MGA=".Length)),
            //    "log",
            //    this.ComponentName + "." + System.Diagnostics.Process.GetCurrentProcess().Id + ".log");
            //META.Logger.AddFileListener(this.logFileName, this.ComponentName, project);

            // GMEConsole = GMEConsole.CreateFromProject(project);
            bool disposeLogger = false;

            if (this.Logger == null)
            {
                this.Logger   = new GMELogger(project, this.ComponentName);
                disposeLogger = true;
            }
            MgaGateway = new MgaGateway(project);
            MgaGateway.PerformInTransaction(delegate
            {
                this._GetTestbenchesFromModel(currentobj, outputBaseDir);
            });

            if (this.Logger != null && disposeLogger)
            {
                this.Logger.Dispose();
                this.Logger = null;
            }
            //META.Logger.RemoveFileListener(this.ComponentName);

            return(this.TestBenches);
        }
Example #10
0
        private static string GetNamespaceName(MgaObject obj)
        {
            Contract.Requires(obj != null);
            string    ns            = "";
            MgaModel  paradigmSheet = null;
            MgaFolder rootFolder    = null;

            if (obj.MetaBase.Name == "RootFolder")
            {
                rootFolder = obj as MgaFolder;
            }
            else
            {
                paradigmSheet = (obj as MgaFCO).ParentModel;
                rootFolder    = GetLibraryRoot(paradigmSheet.ParentFolder);
            }
            try
            {
                ns = rootFolder.RegistryValue["Namespace"];
            }
            catch
            {
                // com exception...
            }
            return(ns);
        }
Example #11
0
        public void UnrollComponent(MgaModel comp, Boolean cleanup = true)
        {
            Logger.WriteDebug("UnrollComponent: {0}", comp.AbsPath);

            VisitComponent(comp);
            if (cleanup)
            {
                DeleteConnectorsAndPorts();
            }
        }
Example #12
0
        public void migrateModel(MgaModel rootmodel)
        {
            RootFolder = null;
            RootModel  = rootmodel;

            createNewFCOs(rootmodel);
            directFCOs();
            copyOldLayout();
            deleteOldFCOs();
        }
Example #13
0
        private static bool AddCylinder(CyPhy.Cylinder cylinder,
                                        List <KeyValuePair <string, string> > featureList)
        {
            bool status = true;

            if (cylinder != null)
            {
                // start, end, radius
                MgaModel      cylinderMga = cylinder.Impl as MgaModel;
                List <MgaFCO> startPts    = new List <MgaFCO>();
                startPts = FindByRole(cylinderMga, "CylinderStart");
                List <MgaFCO> endPts = new List <MgaFCO>();
                endPts = FindByRole(cylinderMga, "CylinderEnd");
                List <MgaFCO> radiusPts = new List <MgaFCO>();
                radiusPts = FindByRole(cylinderMga, "CylinderRadius");

                if (startPts.Count != 1 || endPts.Count != 1 || radiusPts.Count != 1)
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry must contain 1 CylinderStart, 1 CylinderEnd, and 1 CylinderRadius: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return(false);
                }

                CyPhy.Point startPt = CyPhyClasses.Point.Cast(startPts[0]);
                if (!CreateFeatureFromPoint(startPt,
                                            featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry's CylinderStart point must connect to a Point datum inside a CADModel: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return(false);
                }
                CyPhy.Point endPt = CyPhyClasses.Point.Cast(endPts[0]);
                if (!CreateFeatureFromPoint(endPt,
                                            featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry's CylinderEnd point must connect to a Point datum inside a CADModel: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return(false);
                }
                CyPhy.Point radiusPt = CyPhyClasses.Point.Cast(radiusPts[0]);
                if (!CreateFeatureFromPoint(radiusPt,
                                            featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry's CylinderRadius point must connect to a Point datum inside a CADModel: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return(false);
                }
            }
            else
            {
                status = false;
            }

            //var height = (extrusion.Impl as MgaModel).ChildFCOs.Cast<MgaFCO>().Where(x => x.MetaRole.Name == "ExtrusionHeight").FirstOrDefault();

            return(status);
        }
Example #14
0
        public void migrateProject()
        {
            RootFolder = project.RootFolder;
            RootModel = null;

            List<MgaFolder> folders = getAllFolders(project.RootFolder);
            List<MgaFolder> C = new List<MgaFolder>(); //components
            List<MgaFolder> DS = new List<MgaFolder>(); //design spaces
            List<MgaFolder> CA = new List<MgaFolder>(); // component assemblies
            List<MgaFolder> TC = new List<MgaFolder>(); //test components
            List<MgaFolder> T = new List<MgaFolder>(); //testing
            List<MgaFolder> other = new List<MgaFolder>();

            foreach (MgaFolder folder in folders)
            {
                if (folder == null)
                    continue;
                if (folder.MetaFolder.DisplayedName == "Components")
                    C.Add(folder);
                else if (folder.MetaFolder.DisplayedName == "Design Spaces")
                    DS.Add(folder);
                else if (folder.MetaFolder.DisplayedName == "Component Assemblies")
                    CA.Add(folder);
                else if (folder.MetaFolder.DisplayedName == "Test Components")
                    TC.Add(folder);
                else if (folder.MetaFolder.DisplayedName == "Testing")
                    T.Add(folder);
                else
                    other.Add(folder);
            }
            
            foreach (MgaFolder folder in C)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            foreach (MgaFolder folder in DS)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            foreach (MgaFolder folder in CA)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            foreach (MgaFolder folder in TC)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            foreach (MgaFolder folder in T)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            foreach (MgaFolder folder in other)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            directFCOs();
            copyOldLayout();
            deleteOldFCOs();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TestBenchTypeElaborator"/> class with a subject
        /// object on which the elaboration will be performed.
        /// </summary>
        /// <param name="subject">Component Assembly object.</param>
        /// <exception cref="ArgumentNullException">If any arguments are null</exception>
        public TestBenchTypeElaborator(MgaModel subject)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            // initialize object with the given parameters
            this.Subject = subject;

            // initialize collections
            this.Traceability = new Dictionary<string, string>();
        }
Example #16
0
        /// <summary>
        /// Gets a new instance of an elaborator based on a given context.
        /// </summary>
        /// <param name="subject">Given context</param>
        /// <param name="logger">Logger which can be used to log messages.</param>
        /// <returns>A new instance of a context aware elaborator.</returns>
        /// <exception cref="ArgumentNullException">If subject or logger null.</exception>
        /// <exception cref="NotSupportedException">If subject does not have an associated elaborator class.</exception>
        public static Elaborator GetElaborator(MgaModel subject, CyPhyGUIs.GMELogger logger, bool UnrollConnectors)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            var        factory    = new CyPhyTypeFactory(subject.Project.RootMeta);
            Elaborator elaborator = null;

            if (subject.MetaBase.MetaRef == factory.TestBenchMeta ||
                subject.MetaBase.MetaRef == factory.CADTestBenchMeta ||
                subject.MetaBase.MetaRef == factory.BlastTestBenchMeta ||
                subject.MetaBase.MetaRef == factory.BallisticTestBenchMeta ||
                subject.MetaBase.MetaRef == factory.CFDTestBenchMeta ||
                subject.MetaBase.MetaRef == factory.KinematicTestBenchMeta ||
                subject.MetaBase.MetaRef == factory.CarTestBenchMeta)
            {
                elaborator = new TestBenchTypeElaborator(subject, UnrollConnectors);
            }
            else if (subject.MetaBase.MetaRef == factory.ComponentAssemblyMeta)
            {
                elaborator = new ComponentAssemblyElaborator(subject, UnrollConnectors);
            }
            else if (subject.MetaBase.MetaRef == factory.DesignContainerMeta)
            {
                elaborator = new DesignContainerElaborator(subject, UnrollConnectors);
            }
            else
            {
                throw new NotSupportedException(string.Format("Not supported context: {0} [{1}]", subject.Name, subject.MetaBase.Name));
            }

            if (subject.IsLibObject)
            {
                throw new NotSupportedException(string.Format("{0} cannot be a library object.", subject.MetaBase.Name));
            }

            elaborator.Logger  = logger;
            elaborator.Factory = factory;
            // TODO: how can we determine this?
            elaborator.IsElaborated = false;

            return(elaborator);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TestBenchTypeElaborator"/> class with a subject
        /// object on which the elaboration will be performed.
        /// </summary>
        /// <param name="subject">Component Assembly object.</param>
        /// <exception cref="ArgumentNullException">If any arguments are null</exception>
        public TestBenchTypeElaborator(MgaModel subject, bool UnrollConnectors)
            : base(UnrollConnectors)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            // initialize object with the given parameters
            this.Subject = subject;

            // initialize collections
            this.Traceability   = new Dictionary <string, string>();
            this.ComponentGUIDs = new HashSet <string>();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ComponentAssemblyElaborator"/> class with a subject
        /// object on which the elaboration will be performed.
        /// </summary>
        /// <param name="subject">Component Assembly object.</param>
        /// <exception cref="ArgumentNullException">If any arguments are null</exception>
        public ComponentAssemblyElaborator(MgaModel subject)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            // initialize subject
            this.Subject = subject;

            // initialize collections
            this.Traceability = new Dictionary<string, string>();
            this.InnerElaborators = new List<ComponentAssemblyElaborator>();
            this.ComponentAssemblyReferences = new Queue<MgaFCO>();
        }
Example #19
0
        private static MgaFCO makeConn(MgaModel parent, MgaFCO src, MgaFCO dst, string role, MgaFCOs srcRef = null, MgaFCOs dstRef = null)
        {
            MgaFCO newConn;

            if (srcRef == null && dstRef == null)
            {
                newConn = parent.CreateSimplerConnDisp((parent.Meta as MgaMetaModel).RoleByName[role], src, dst);
            }
            else
            {
                newConn = parent.CreateSimpleConn((parent.Meta as MgaMetaModel).RoleByName[role], src, dst, srcRef, dstRef);
            }
            newConn.Name = role;
            return(newConn);
        }
Example #20
0
        private void DisplayPCCIterations(MgaObject subject, bool attributeChanged)
        {
            List <string> kinds = new List <string>()
            {
                "PCCDriver",
                "PCCParameterBeta",
                "PCCParameterUniform",
                "PCCParameterLNormal",
                "PCCParameterNormal"
            };

            if (kinds.Contains(subject.MetaBase.Name) == false)
            {
                return;
            }


            MgaModel PCCDriver = null;

            if (attributeChanged && subject.MetaBase.Name == "PCCDriver")
            {
                // TODO: Compute and
                PCCDriver = subject as MgaModel;
            }
            else if (attributeChanged == false && subject.MetaBase.Name == "PCCDriver")
            {
                // Compute and prin

                //GME.MGA.Meta.objtype_enum type;
                //MgaObject parent;
                //(subject as MgaFCO).GetParent(out parent, out type);
                PCCDriver = subject as MgaModel;
            }
            else
            {
                return;
            }

            //Compute and print PCCDriver
            var nbrOfParameters = PCCDriver.ChildFCOs.Cast <MgaFCO>().Where(x => kinds.Contains(x.Meta.Name)).Count();
            var saMethod        = PCCDriver.StrAttrByName["PCC_SA_Methods"];
            var upMethod        = PCCDriver.StrAttrByName["PCC_UP_Methods"];

            GMEConsole.Out.WriteLine("{2}Iterations : UP : {0}, SA : {1}",
                                     this.GetNumberOfIterations(upMethod, nbrOfParameters),
                                     this.GetNumberOfIterations(saMethod, nbrOfParameters),
                                     INFO_BADGE);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ComponentAssemblyElaborator"/> class with a subject
        /// object on which the elaboration will be performed.
        /// </summary>
        /// <param name="subject">Component Assembly object.</param>
        /// <exception cref="ArgumentNullException">If any arguments are null</exception>
        public ComponentAssemblyElaborator(MgaModel subject, bool UnrollConnectors)
            : base(UnrollConnectors)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            // initialize subject
            this.Subject = subject;

            // initialize collections
            this.Traceability                = new Dictionary <string, string>();
            this.ComponentGUIDs              = new HashSet <string>();
            this.InnerElaborators            = new List <ComponentAssemblyElaborator>();
            this.ComponentAssemblyReferences = new Queue <MgaFCO>();
        }
Example #22
0
        public void migrateFolder(MgaFolder rootfolder)
        {
            RootFolder = rootfolder;
            RootModel  = null;

            List <MgaFolder> folders = getAllFolders(rootfolder);

            foreach (MgaFolder folder in folders)
            {
                foreach (MgaModel model in folder.ChildObjects.OfType <MgaModel>())
                {
                    createNewFCOs(model);
                }
            }
            directFCOs();
            copyOldLayout();
            deleteOldFCOs();
        }
Example #23
0
        private Dictionary <string, List <MgaFCO> > GetAllChildren(MgaModel root)
        {
            if (root == null)
            {
                return(new Dictionary <string, List <MgaFCO> >());
            }

            var result = new Dictionary <string, List <MgaFCO> >();
            var models = new List <MgaModel>();

            foreach (var childObject in root.ChildObjects.OfType <MgaFCO>())
            {
                var kind = childObject.Meta.Name;
                if (!result.ContainsKey(kind))
                {
                    result[kind] = new List <MgaFCO>();
                }

                result[kind].Add(childObject);

                if (childObject is MgaModel)
                {
                    models.Add((MgaModel)childObject);
                }
            }

            foreach (var model in models)
            {
                var tmp = GetAllChildren(model);

                foreach (var tmpChild in tmp.Where(tmpChild => tmpChild.Value != null))
                {
                    if (!result.ContainsKey(tmpChild.Key))
                    {
                        result[tmpChild.Key] = new List <MgaFCO>();
                    }

                    result[tmpChild.Key].AddRange(tmpChild.Value);
                }
            }

            return(result);
        }
Example #24
0
        /// <summary>
        /// Given an FCO, take each attribute and explicitly assign it.
        /// This gets around a problem where attribute values are wiped out
        /// if they were inherited, and then inheritance was broken.
        /// </summary>
        /// <param name="fco"></param>
        public static void SetAttributesLocally(MgaFCO fco)
        {
            if (fco is MgaModel)
            {
                MgaModel model = fco as MgaModel;
                foreach (MgaFCO child in model.ChildFCOs)
                {
                    SetAttributesLocally(child);
                }
            }

            foreach (MgaAttribute attr in fco.Attributes)
            {
                if (attr.Status > (int)attstatus_enum.ATTSTATUS_HERE)
                {
                    attr.Value = attr.Value;
                }
            }
        }
Example #25
0
        /// <summary>
        /// Generic port "clone" function that creates and copies a port/pin or pin.
        /// </summary>
        /// <param name="parent">The MgaModel that will contain newly-created clone</param>
        /// <param name="oldPort">The original port or pin to be cloned</param>
        /// <returns>newPortFCO -- The cloned port/pin created in the parent.</returns>
        private MgaFCO ClonePort(MgaModel parent, MgaFCO oldPort)
        {
            Logger.WriteDebug("ClonePort: {0}", oldPort.AbsPath);

            GME.MGA.Meta.MgaMetaRole role = null;

            foreach (GME.MGA.Meta.MgaMetaRole roleItem in (parent.Meta as GME.MGA.Meta.MgaMetaModel).Roles)
            {
                if (roleItem.Kind.MetaRef == oldPort.MetaBase.MetaRef)
                {
                    role = roleItem;
                    break;
                }
            }

            var newPortFCO = parent.CopyFCODisp(oldPort, role);

            //newPortFCO.SetAttributeByNameDisp("ID", null);
            return(newPortFCO);
        }
Example #26
0
        /// <summary>
        /// For a given connector, see what connections involve its constituent ports.
        /// For each such connection, modify it to terminate at the new standalone port.
        /// </summary>
        /// <param name="connector">The CyPhy Connector to be processed</param>
        private void RedirectConnectionsToConstituentPorts(MgaModel connector)
        {
            #region Check arguments
            if (connector == null)
            {
                throw new ArgumentNullException("connector");
            }
            if (connector.MetaBase.MetaRef != MetaRef["Connector"])
            {
                throw new ArgumentException("Input parameter was not a connector.", "connector");
            }
            #endregion
            Logger.WriteDebug("RedirectConnectionsToConstituentPorts: {0}", connector.AbsPath);

            foreach (var port in ConnectorToStandalonePortMap[connector])
            {
                foreach (MgaConnPoint connPoint in port.SourcePort.PartOfConns)
                {
                    var connection = connPoint.Owner as MgaSimpleConnection;
                    var parent     = connection.ParentModel;

                    if (connection.Src == port.SourcePort)
                    {
                        var objMetaRole = (parent.Meta as MgaMetaModel).RoleByName["PortComposition"];
                        parent.CreateSimplerConnDisp(objMetaRole, port.StandalonePort, connection.Dst);

                        //connection.SetSrc(null, port.StandalonePort);
                    }
                    else if (connection.Dst == port.SourcePort)
                    {
                        var objMetaRole = (parent.Meta as MgaMetaModel).RoleByName["PortComposition"];
                        parent.CreateSimplerConnDisp(objMetaRole, connection.Src, port.StandalonePort);

                        //connection.SetDst(null, port.StandalonePort);
                    }

                    connection.DestroyObject();
                }
            }
        }
Example #27
0
        private void VisitComponent(MgaModel comp)
        {
            #region Check arguments
            if (comp == null)
            {
                throw new ArgumentNullException("comp");
            }
            if (comp.MetaBase.MetaRef != MetaRef["Component"])
            {
                throw new ArgumentException("Input parameter was not a component.", "comp");
            }
            #endregion
            Logger.WriteDebug("VisitComponent: {0}", comp.AbsPath);

            if (componentsProcessed.Contains(comp))
            {
                Logger.WriteDebug("VisitComponent: Skipping (already processed) {0}", comp.AbsPath);

                return;
            }

            // Is this an instance?
            // If so, process the archetype only.
            if (comp.ArcheType != null)
            {
                Logger.WriteDebug("VisitComponent: Processing Archetype instead {0}", comp.AbsPath);

                var archetype = comp.ArcheType as MgaModel;
                VisitComponent(archetype);

                return;
            }

            foreach (MgaModel connector in comp.GetChildrenOfKind("Connector"))
            {
                VisitConnector(connector);
            }
        }
Example #28
0
        public void TestInitArguments()
        {
            MgaProject project = new MgaProject();

            project.OpenEx("MGA=" + mgaFile, "CyPhyML", null);
            try
            {
                project.BeginTransactionInNewTerr();
                try
                {
                    string petExperimentPath = "/@Testing/@ParametricExploration/@TestAnalysis";
                    string assemblyDir       = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
                    string pyFile            = Path.Combine(assemblyDir,
                                                            "..\\..\\..\\..\\models\\PET_simple_proof-of-concept\\sample_analysis.py");

                    MgaModel model   = (MgaModel)project.ObjectByPath[petExperimentPath];
                    var      params_ = CyPhyPET.CyPhyPETInterpreter.GetPythonComponentInitializerParameters(pyFile, (MgaFCO)model);
                    Assert.Equal(new string[] { "self", "config1", "config2", "opt1", "opt2" }, params_.args);
                    Assert.Equal(new string[] { "self", "config1", "config2" }, params_.requiredArgs);
                    Assert.Equal(new object[] { null, 0.0 }, params_.defaults);

                    var analysisBlock = ISIS.GME.Dsml.CyPhyML.Classes.AnalysisBlock.Cast(model.ObjectByPath["/@AnalysisBlock"]);
                    CyPhyPET.CyPhyPETInterpreter.EditConfigurationParameters(params_, analysisBlock, showGui: false);

                    var kwargs = CyPhyPET.CyPhyPETInterpreter.GetConfigurationParameters(analysisBlock);
                    CyPhyPET.CyPhyPETInterpreter.GetParamsAndUnknownsForPythonOpenMDAO(pyFile, analysisBlock, kwargs);
                }
                finally
                {
                    project.AbortTransaction();
                }
            }
            finally
            {
                project.Close(true);
            }
        }
Example #29
0
        private static MgaFCO GenerateTestModel(MgaProject project, MgaFCO currentobj)
        {
            MgaFolder folderComponentAssemblies = project.RootFolder.CreateFolder(project.RootMeta.RootFolder.DefinedFolderByName["ComponentAssemblies", true]);

            folderComponentAssemblies.Name = "00 ComponentAssemblies";

            MgaModel ca = folderComponentAssemblies.CreateRootObject(project.RootMeta.RootFolder.DefinedFCOByName["ComponentAssembly", true]) as MgaModel;

            ca.Name = string.Format("00 Generated Component Assembly {0}", DateTime.Now);

            MgaFolder folderComponents = project.RootFolder.CreateFolder(project.RootMeta.RootFolder.DefinedFolderByName["Components", true]);

            folderComponents.Name = "00 Components";

            MgaModel leaf = folderComponents.CreateRootObject(project.RootMeta.RootFolder.DefinedFCOByName["Component", true]) as MgaModel;

            leaf.Name = string.Format("00 Generated Component {0}", DateTime.Now);

            // generate syntetic model
            GenerateAssemblies(folderComponentAssemblies, ca, 0, leaf);

            currentobj = ca as MgaFCO;
            return(currentobj);
        }
        /// <summary>
        /// For a given connector, see what connections involve its constituent ports.
        /// For each such connection, modify it to terminate at the new standalone port.
        /// </summary>
        /// <param name="connector">The CyPhy Connector to be processed</param>
        private void RedirectConnectionsToConstituentPorts(MgaModel connector)
        {
            #region Check arguments
            if (connector == null)
            {
                throw new ArgumentNullException("connector");
            }
            if (connector.MetaBase.MetaRef != MetaRef["Connector"])
            {
                throw new ArgumentException("Input parameter was not a connector.", "connector");
            }
            #endregion
            Logger.WriteDebug("RedirectConnectionsToConstituentPorts: {0}", connector.AbsPath);

            foreach (var port in ConnectorToStandalonePortMap[connector])
            {
                foreach (MgaConnPoint connPoint in port.SourcePort.PartOfConns)
                {
                    var connection = connPoint.Owner as MgaSimpleConnection;
                    var parent = connection.ParentModel;

                    if (connection.Src == port.SourcePort)
                    {
                        var objMetaRole = (parent.Meta as MgaMetaModel).RoleByName["PortComposition"];
                        parent.CreateSimplerConnDisp(objMetaRole, port.StandalonePort, connection.Dst);

                        //connection.SetSrc(null, port.StandalonePort);
                    }
                    else if (connection.Dst == port.SourcePort)
                    {
                        var objMetaRole = (parent.Meta as MgaMetaModel).RoleByName["PortComposition"];
                        parent.CreateSimplerConnDisp(objMetaRole, connection.Src, port.StandalonePort);

                        //connection.SetDst(null, port.StandalonePort);
                    }

                    connection.DestroyObject();
                }
            }
        }
Example #31
0
        private void TraverseComposites(CyPhy.Component component)
        {
            foreach (var material in component.Children.MaterialContentsCollection)
            {
                CAD.ElementType cadElement = new CAD.ElementType()
                {
                    _id          = UtilityHelpers.MakeUdmID(),
                    ElementType1 = "SURFACE"
                };

                MgaModel      materialMga = material.Impl as MgaModel;
                List <MgaFCO> startDirPts = new List <MgaFCO>();
                List <MgaFCO> endDirPts   = new List <MgaFCO>();

                startDirPts = CyPhy2CAD_CSharp.DataRep.CADGeometry.FindByRole(materialMga, "Start_Direction");
                endDirPts   = CyPhy2CAD_CSharp.DataRep.CADGeometry.FindByRole(materialMga, "End_Direction");

                if (startDirPts.Count != 1 && endDirPts.Count != 1)
                {
                    Logger.Instance.AddLogMessage("Material Content must contain one Start_Direction and one End_Direction point.", Severity.Warning);
                    continue;
                }


                CyPhy.Point startDirPt          = CyPhyClasses.Point.Cast(startDirPts[0]);
                string      startDirPtDatumName = GetFeatureName(startDirPt);

                CyPhy.Point endDirPt          = CyPhyClasses.Point.Cast(endDirPts[0]);
                string      endDirPtDatumName = GetFeatureName(endDirPt);

                CAD.OrientationType cadOrientation = new CAD.OrientationType()
                {
                    _id = UtilityHelpers.MakeUdmID()
                };
                CAD.GeometryType cadGeometry = new CAD.GeometryType()
                {
                    _id = UtilityHelpers.MakeUdmID()
                };


                CAD.FeatureType cadStartFeature = new CAD.FeatureType()
                {
                    _id         = UtilityHelpers.MakeUdmID(),
                    ComponentID = DisplayID,
                    Name        = startDirPtDatumName,
                    MetricID    = DisplayID + ":" + startDirPtDatumName
                };
                TestBenchModel.TBComputation startFeatureComputation = new TestBenchModel.TBComputation()
                {
                    ComponentID        = DisplayID,
                    ComputationType    = TestBenchModel.TBComputation.Type.POINTCOORDINATES,
                    Details            = startDirPtDatumName,
                    FeatureDatumName   = startDirPtDatumName,
                    MetricID           = DisplayID + ":" + startDirPtDatumName,
                    RequestedValueType = "Vector"
                };
                pointCoordinatesList.Add(startFeatureComputation);
                if (String.IsNullOrEmpty(startDirPtDatumName))
                {
                    Logger.Instance.AddLogMessage("Empty point datum name [" + startDirPt.Path + "]", Severity.Warning);
                }

                CAD.FeatureType cadEndFeature = new CAD.FeatureType()
                {
                    _id         = UtilityHelpers.MakeUdmID(),
                    ComponentID = DisplayID,
                    Name        = endDirPtDatumName,
                    MetricID    = DisplayID + ":" + endDirPtDatumName
                };
                TestBenchModel.TBComputation endFeatureComputation = new TestBenchModel.TBComputation()
                {
                    ComponentID        = DisplayID,
                    ComputationType    = TestBenchModel.TBComputation.Type.POINTCOORDINATES,
                    Details            = endDirPtDatumName,
                    FeatureDatumName   = endDirPtDatumName,
                    MetricID           = DisplayID + ":" + endDirPtDatumName,
                    RequestedValueType = "Vector"
                };
                pointCoordinatesList.Add(endFeatureComputation);
                if (String.IsNullOrEmpty(endDirPtDatumName))
                {
                    Logger.Instance.AddLogMessage("Empty point datum name [" + endDirPt.Path + "]", Severity.Warning);
                }

                CAD.FeaturesType cadFeatures = new CAD.FeaturesType()
                {
                    _id                        = UtilityHelpers.MakeUdmID(),
                    FeatureID                  = material.ID,
                    GeometryType               = "Vector",
                    FeatureInterfaceType       = "CAD_DATUM",
                    FeatureGeometryType        = "POINT",
                    PrimaryGeometryQualifier   = "",
                    SecondaryGeometryQualifier = ""
                };

                cadFeatures.Feature     = new CAD.FeatureType[2];
                cadFeatures.Feature[0]  = cadStartFeature;
                cadFeatures.Feature[1]  = cadEndFeature;
                cadGeometry.Features    = new CAD.FeaturesType[1];
                cadGeometry.Features[0] = cadFeatures;
                cadOrientation.Geometry = cadGeometry;


                // Material Layups
                CAD.MaterialLayupType cadLayers = new CAD.MaterialLayupType()
                {
                    _id       = UtilityHelpers.MakeUdmID(),
                    Position  = material.Attributes.Position.ToString().ToUpper(),
                    Offset    = (material.Attributes.Position.ToString().ToUpper() != "OFFSET_BY_VALUE") ? 0 : (material.Attributes.PositionOffset),
                    Direction = material.Attributes.MaterialLayupDirection.ToString().ToUpper()
                };

                int layerCnt = material.Children.MaterialLayerCollection.Count();
                if (layerCnt > 0)
                {
                    cadLayers.Layer = new CAD.LayerType[layerCnt];

                    int k = 0;
                    foreach (var layer in material.Children.MaterialLayerCollection.OrderBy(i => i.Attributes.LayerID))
                    {
                        CAD.LayerType cadLayer = new CAD.LayerType()
                        {
                            _id           = UtilityHelpers.MakeUdmID(),
                            ID            = layer.Attributes.LayerID,
                            Drop_Order    = layer.Attributes.DropOrder,
                            Material_Name = layer.Attributes.LayerMaterial,
                            Orientation   = layer.Attributes.LayerOrientation,
                            Thickness     = layer.Attributes.LayerThickness
                        };

                        cadLayers.Layer[k] = cadLayer;
                        k++;
                    }
                }

                CAD.ElementContentsType cadElementContents = new CAD.ElementContentsType();
                cadElementContents._id           = UtilityHelpers.MakeUdmID();
                cadElementContents.Orientation   = cadOrientation;
                cadElementContents.MaterialLayup = cadLayers;
                cadElement.ElementContents       = cadElementContents;


                if (material.DstConnections.ContentsToGeometryCollection.Count() < 1 || material.DstConnections.ContentsToGeometryCollection.Count() > 1)
                {
                    Logger.Instance.AddLogMessage("Material Content need to connect to one Face geometry.", Severity.Warning);
                    continue;
                }


                // Face, Polygon, or Extrusion Geometry
                CyPhy.ContentsToGeometry conn = material.DstConnections.ContentsToGeometryCollection.FirstOrDefault();
                if (conn != null)
                {
                    CyPhy.Face      faceGeometry      = conn.DstEnds.Face;
                    CyPhy.Polygon   polgonGeometry    = conn.DstEnds.Polygon;
                    CyPhy.Extrusion extrusionGeometry = conn.DstEnds.Extrusion;


                    int countGeometryTypes = 0;

                    if (faceGeometry != null)
                    {
                        ++countGeometryTypes;
                    }
                    if (polgonGeometry != null)
                    {
                        ++countGeometryTypes;
                    }
                    if (extrusionGeometry != null)
                    {
                        ++countGeometryTypes;
                    }

                    if (countGeometryTypes != 1)
                    {
                        Logger.Instance.AddLogMessage("MaterialContents must be connected to one and only one geometry type (i.e. FACE, POLOGON, or EXTRUSION).", Severity.Warning);
                        continue;
                    }


                    // Approach when only FACE was supported
                    //String primBoundaryQ = faceGeometry.Attributes.BoundaryQualifier.ToString().Replace("_", string.Empty);
                    //MgaModel faceMga = faceGeometry.Impl as MgaModel;
                    //List<MgaFCO> normalDirPts = new List<MgaFCO>();
                    //normalDirPts = CyPhy2CAD_CSharp.DataRep.CADGeometry.FindByRole(faceMga, "Direction_Reference_Point");

                    String        primBoundaryQ = "";
                    MgaModel      faceMga;
                    List <MgaFCO> normalDirPts = new List <MgaFCO>();

                    if (faceGeometry != null)
                    {
                        primBoundaryQ = faceGeometry.Attributes.BoundaryQualifier.ToString().Replace("_", string.Empty);
                        faceMga       = faceGeometry.Impl as MgaModel;
                        normalDirPts  = CyPhy2CAD_CSharp.DataRep.CADGeometry.FindByRole(faceMga, "Direction_Reference_Point");
                    }
                    else if (polgonGeometry != null)
                    {
                        primBoundaryQ = polgonGeometry.Attributes.BoundaryQualifier.ToString().Replace("_", string.Empty);
                        faceMga       = polgonGeometry.Impl as MgaModel;
                        normalDirPts  = CyPhy2CAD_CSharp.DataRep.CADGeometry.FindByRole(faceMga, "Direction_Reference_Point");
                    }
                    else if (extrusionGeometry != null)
                    {
                        primBoundaryQ = extrusionGeometry.Attributes.BoundaryQualifier.ToString().Replace("_", string.Empty);
                        faceMga       = extrusionGeometry.Impl as MgaModel;
                        normalDirPts  = CyPhy2CAD_CSharp.DataRep.CADGeometry.FindByRole(faceMga, "Direction_Reference_Point");
                    }

                    if (normalDirPts.Count != 1)
                    {
                        Logger.Instance.AddLogMessage("Geometry (FACE, POLYGON, or EXTRUSION) can contain only one Direction_Reference_Point point.", Severity.Warning);
                        continue;
                    }

                    CyPhy.Point normalDirPt         = CyPhyClasses.Point.Cast(normalDirPts.FirstOrDefault());
                    string      normalPtFeatureName = GetFeatureName(normalDirPt);
                    if (String.IsNullOrEmpty(normalPtFeatureName))
                    {
                        Logger.Instance.AddLogMessage("Direction_Reference_Point point of the Face/Ploygon/Extrusion geometry doesn't have a datum name. Make sure it is connected to a valid point inside a CADModel.", Severity.Warning);
                        continue;
                    }

                    CyPhy2CAD_CSharp.DataRep.CADGeometry faceOrExtruOrPolyGeometryRep = null;
                    if (faceGeometry != null)
                    {
                        faceOrExtruOrPolyGeometryRep = CyPhy2CAD_CSharp.DataRep.CADGeometry.CreateGeometry(faceGeometry);
                        if (faceOrExtruOrPolyGeometryRep == null)
                        {
                            Logger.Instance.AddLogMessage("Unsuccessfully created a representation of a Face Geometry.", Severity.Warning);
                            continue;
                        }
                    }
                    else if (polgonGeometry != null)
                    {
                        faceOrExtruOrPolyGeometryRep = CyPhy2CAD_CSharp.DataRep.CADGeometry.CreateGeometry(polgonGeometry);
                        if (faceOrExtruOrPolyGeometryRep == null)
                        {
                            Logger.Instance.AddLogMessage("Unsuccessfully created a representation of a Polygon Geometry.", Severity.Warning);
                            continue;
                        }
                    }
                    else if (extrusionGeometry != null)
                    {
                        faceOrExtruOrPolyGeometryRep = CyPhy2CAD_CSharp.DataRep.CADGeometry.CreateGeometry(extrusionGeometry);
                        if (faceOrExtruOrPolyGeometryRep == null)
                        {
                            Logger.Instance.AddLogMessage("Unsuccessfully created a representation of a Extrusion Geometry.", Severity.Warning);
                            continue;
                        }
                    }

                    // Element/Geometry
                    CAD.GeometryType cadFaceOrExtruOrPolyGeometryOut = faceOrExtruOrPolyGeometryRep.ToCADXMLOutput();
                    if (cadFaceOrExtruOrPolyGeometryOut == null)
                    {
                        Logger.Instance.AddLogMessage("Unsuccessfully converted a representation of a Face/Ploygon/Extrusion Geometry to CAD xml.", Severity.Warning);
                        continue;
                    }


                    cadElement.Geometry = cadFaceOrExtruOrPolyGeometryOut;
                    foreach (var faceOrExtruOrPolyGeomFeatures in cadFaceOrExtruOrPolyGeometryOut.Features)
                    {
                        foreach (var feature_temp in faceOrExtruOrPolyGeomFeatures.Feature)
                        {
                            TestBenchModel.TBComputation faceGeometryComputation = new TestBenchModel.TBComputation()
                            {
                                ComponentID        = DisplayID,
                                ComputationType    = TestBenchModel.TBComputation.Type.POINTCOORDINATES,
                                Details            = feature_temp.Name,
                                FeatureDatumName   = feature_temp.Name,
                                MetricID           = feature_temp.MetricID,
                                RequestedValueType = "Vector"
                            };
                            pointCoordinatesList.Add(faceGeometryComputation);
                        }
                    }

                    // Element/Geometry

                    string direction_temp = "";

                    if (faceGeometry != null)
                    {
                        direction_temp = (faceGeometry.Attributes.NormalDirection == CyPhyClasses.Face.AttributesClass.NormalDirection_enum.Toward_Reference_Point) ? "TOWARD" : "AWAY";
                    }
                    else if (polgonGeometry != null)
                    {
                        direction_temp = (polgonGeometry.Attributes.NormalDirection == CyPhyClasses.Polygon.AttributesClass.NormalDirection_enum.Toward_Reference_Point) ? "TOWARD" : "AWAY";
                    }
                    else if (extrusionGeometry != null)
                    {
                        direction_temp = (extrusionGeometry.Attributes.NormalDirection == CyPhyClasses.Extrusion.AttributesClass.NormalDirection_enum.Toward_Reference_Point) ? "TOWARD" : "AWAY";
                    }

                    CAD.SurfaceNormalType cadSurfaceNormal = new CAD.SurfaceNormalType()
                    {
                        _id       = UtilityHelpers.MakeUdmID(),
                        Direction = direction_temp
                    };

                    CAD.FeaturesType cadSurfaceNormFeatures = new CAD.FeaturesType()
                    {
                        _id                        = UtilityHelpers.MakeUdmID(),
                        FeatureID                  = normalDirPt.ID,
                        GeometryType               = "POINT",
                        FeatureInterfaceType       = "CAD_DATUM",
                        FeatureGeometryType        = "POINT",
                        Feature                    = new CAD.FeatureType[1],
                        PrimaryGeometryQualifier   = primBoundaryQ,
                        SecondaryGeometryQualifier = ""
                    };

                    cadSurfaceNormFeatures.Feature[0] = new CAD.FeatureType()
                    {
                        _id         = UtilityHelpers.MakeUdmID(),
                        Name        = normalPtFeatureName,
                        ComponentID = DisplayID,
                        MetricID    = DisplayID + ":" + normalPtFeatureName
                    };
                    TestBenchModel.TBComputation surfNormalComputation = new TestBenchModel.TBComputation()
                    {
                        ComponentID        = DisplayID,
                        ComputationType    = TestBenchModel.TBComputation.Type.POINTCOORDINATES,
                        Details            = normalPtFeatureName,
                        FeatureDatumName   = normalPtFeatureName,
                        MetricID           = DisplayID + ":" + normalPtFeatureName,
                        RequestedValueType = "Vector"
                    };
                    pointCoordinatesList.Add(surfNormalComputation);
                    if (String.IsNullOrEmpty(normalPtFeatureName))
                    {
                        Logger.Instance.AddLogMessage("Empty point datum name [" + normalDirPt.Path + "]", Severity.Warning);
                    }

                    CAD.GeometryType cadSurfaceNormGeom = new CAD.GeometryType()
                    {
                        _id      = UtilityHelpers.MakeUdmID(),
                        Features = new CAD.FeaturesType[1],
                    };

                    cadSurfaceNormGeom.Features[0] = cadSurfaceNormFeatures;
                    cadSurfaceNormal.Geometry      = cadSurfaceNormGeom;
                    cadElement.SurfaceNormal       = cadSurfaceNormal;
                }

                this.CadElementsList.Add(cadElement);
            }
        }
        public void MigrateAllChildren(MgaModel root)
        {
            // Recursively get all children of this object, indexed by kind.
            Dictionary<string, List<MgaFCO>> dlf_AllFCOs = RecursivelyGetAllChildren(root);

            // Get self too.
            var kind = root.Meta.Name;
            if (!dlf_AllFCOs.ContainsKey(kind))
                dlf_AllFCOs[kind] = new List<MgaFCO>();
            dlf_AllFCOs[kind].Add(root as MgaFCO);

            // For each found FCO, migrate.
            // The key (kind name) isn't used at all

            #region ObsoleteCode

            foreach (KeyValuePair<string, List<MgaFCO>> kvp in dlf_AllFCOs)
            {
                if (kvp.Key == "ComponentRef")
                {
                    foreach (MgaFCO fco in kvp.Value)
                    {
                        if ((fco as MgaReference).Referred != null)
                        {
                            MgaFCO referredComponent = (fco as MgaReference).Referred;
                            MigrateAllChildren(referredComponent as MgaModel);
                        }
                    }
                }
                else
                {
                    foreach (MgaFCO fco in kvp.Value)
                    {
                        MigrateObject(fco);
                    }
                }
            }

            #endregion

            foreach (KeyValuePair<string, List<MgaFCO>> kvp in dlf_AllFCOs)
            {
                foreach (MgaFCO fco in kvp.Value)
                {
                    MigrateObject(fco);
                }
            }

            if (root.Meta.Name == "ComponentAssembly" ||
                root.Meta.Name == "DesignContainer")
            {
                migrateSystemConns(root);
            }

            // ModelicaModel objects aren't replaced, but are changing to a new aspect.
            // Copy its position from the current Behavior aspect to the new Modelica aspect.
            if (dlf_AllFCOs.ContainsKey("ModelicaModel"))
            {
                foreach (MgaFCO fco_ModelicaModel in dlf_AllFCOs["ModelicaModel"])
                {
                    var part = fco_ModelicaModel.Parts.Cast<IMgaPart>().Where(p => p.MetaAspect.Name == "BehaviorModelsAspect").FirstOrDefault();
                    string icon;
                    int x;
                    int y;
                    part.GetGmeAttrs(out icon, out x, out y);

                    foreach (var part_ in fco_ModelicaModel.Parts.Cast<IMgaPart>())
                    {
                        part_.SetGmeAttrs(icon, x, y);
                    }
                }
            }
        }
        private void VisitTestBench(MgaModel testbench)
        {
            #region Check arguments
            if (testbench == null)
            {
                throw new ArgumentNullException("testbench");
            }
            if (testbench.MetaBase.MetaRef != MetaRef["TestBench"])
            {
                throw new ArgumentException("Input parameter was not a connector.", "testbench");
            }
            #endregion
            Logger.WriteDebug("VisitTestBench: {0}", testbench.AbsPath);

            foreach (MgaModel asm in testbench.GetChildrenOfKind("ComponentAssembly"))
            {
                VisitComponentAssembly(asm);
            }

            foreach (MgaModel component in testbench.GetChildrenOfKind("Component"))
            {
                VisitComponent(component);
            }

            foreach (MgaModel testComp in testbench.GetChildrenOfKind("TestComponent"))
            {
                VisitTestComponent(testComp);
            }

            ExpandConnectorCompositionChildren(testbench);
        }
        private void migrateSystemConns(MgaModel SystemModel)
        {
            string parName = (SystemModel.ParentFolder == null) ? SystemModel.ParentModel.Name : SystemModel.ParentFolder.Name;
            //GMEConsole.Info.WriteLine("migrateSystemConns({0}.{1})", parName, SystemModel.Name);

            var connections = SystemModel.ChildObjects.OfType<MgaSimpleConnection>();
            string systemName = SystemModel.Name;
            string systemID = SystemModel.ID;

            foreach (var conn in connections)
            {
                if (conn.Meta.Name == "JoinStructures" ||
                    conn.Meta.Name == "ValueFlow" ||
                    conn.Meta.Name == "PortComposition")
                {
                    continue;
                }

               
                string srcPortName = conn.Src.Name;
                string srcParentName = conn.Src.ParentModel.Name;
                string srcPortID = conn.Src.ID;
                string srcParentID = conn.Src.ParentModel.ID;

                var srcReferences = conn.SrcReferences;
                if (srcReferences.Count != 0)
                {
                    srcParentName = srcReferences.Cast<IMgaFCO>().FirstOrDefault().Name;
                    srcParentID = srcReferences.Cast<IMgaFCO>().FirstOrDefault().ID;
                }

                string dstPortName = conn.Dst.Name;
                string dstParentName = conn.Dst.ParentModel.Name;
                string dstPortID = conn.Dst.ID;
                string dstParentID = conn.Dst.ParentModel.ID;

                var dstReferences = conn.DstReferences;
                if (dstReferences.Count != 0)
                {
                    dstParentName = dstReferences.Cast<IMgaFCO>().FirstOrDefault().Name;
                    dstParentID = dstReferences.Cast<IMgaFCO>().FirstOrDefault().ID;
                }

                try
                {
                    MgaFCO newConnSrcParent =
                        (srcParentID == systemID) ?
                        SystemModel as MgaFCO :
                        SystemModel.get_ChildFCO(srcParentName);
                    if (newConnSrcParent == null)
                    {
                        newConnSrcParent = SystemModel.ChildObjects.OfType<MgaReference>()
                            .FirstOrDefault(x => x.Referred != null &&
                                x.Referred.Name == srcParentName) as MgaFCO;
                    }
                    if (newConnSrcParent == null)
                    {
                        GMEConsole.Warning.WriteLine(
                            "Could not find 'srcParent'; Try to make manual connection: {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                            srcParentName,
                            srcPortName,
                            dstParentName,
                            dstPortName,
                            systemID,
                            systemName);
                        continue;
                    }

                    MgaFCO newConnSrcPort = null;
                    if (newConnSrcParent is MgaReference &&
                        (newConnSrcParent as MgaReference).Referred != null)
                    {
                        MgaFCO referredComp = (newConnSrcParent as MgaReference).Referred;
                        newConnSrcPort = referredComp.ChildObjects.OfType<MgaModel>()
                            .FirstOrDefault(x => x.Name == srcPortName &&
                                x.Meta.Name == "ModelicaConnector") as MgaFCO;
                    }
                    else
                    {
                        newConnSrcPort = newConnSrcParent.ChildObjects.OfType<MgaFCO>()
                            .FirstOrDefault(x => x.Name == srcPortName &&
                                x.Meta.Name == "ModelicaConnector");
                    }

                    MgaFCO newConnDstParent =
                        (dstParentID == systemID) ?
                        SystemModel as MgaFCO :
                        SystemModel.get_ChildFCO(dstParentName);
                    if (newConnDstParent == null)
                    {
                        newConnDstParent = SystemModel.ChildObjects.OfType<MgaReference>()
                            .FirstOrDefault(x => x.Referred != null &&
                                x.Referred.Name == dstParentName) as MgaFCO;
                    }
                    if (newConnDstParent == null)
                    {
                        GMEConsole.Warning.WriteLine(
                            "Could not find 'dstParent'; Try to make manual connection: {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                            srcParentName,
                            srcPortName,
                            dstParentName,
                            dstPortName,
                            systemID,
                            systemName);
                        continue;
                    }

                    MgaFCO newConnDstPort = null;
                    if (newConnDstParent is MgaReference &&
                        (newConnDstParent as MgaReference).Referred != null)
                    {
                        MgaFCO referredComp = (newConnDstParent as MgaReference).Referred;
                        newConnDstPort = referredComp.ChildObjects.OfType<MgaFCO>()
                            .FirstOrDefault(x => x.Name == dstPortName &&
                                x.Meta.Name == "ModelicaConnector");
                    }
                    else
                    {
                        newConnDstPort = newConnDstParent.ChildObjects.OfType<MgaFCO>()
                            .FirstOrDefault(x => x.Name == dstPortName &&
                                x.Meta.Name == "ModelicaConnector");
                    }

                    if (newConnSrcPort == null)
                    {
                        string systemParentName =
                            (SystemModel.ParentModel == null) ?
                            SystemModel.ParentFolder.Name :
                            SystemModel.ParentModel.Name;
                        GMEConsole.Warning.WriteLine(
                            "Could not find 'srcPort'; Try to make manual connection: {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                            srcParentName,
                            srcPortName,
                            dstParentName,
                            dstPortName,
                            systemID,
                            systemName);
                        continue;
                    }
                    if (newConnDstPort == null)
                    {
                        string systemParentName =
                            (SystemModel.ParentModel == null) ?
                            SystemModel.ParentFolder.Name :
                            SystemModel.ParentModel.Name;

                        GMEConsole.Warning.WriteLine(
                            "Could not find 'dstPort'; Try to make manual connection: {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                            srcParentName,
                            srcPortName,
                            dstParentName,
                            dstPortName,
                            systemID,
                            systemName);
                        continue;
                    }


                    if (newConnDstParent != null &&
                        newConnDstPort != null &&
                        newConnSrcParent != null &&
                        newConnSrcPort != null)
                    {
                        try
                        {
                            var newConnection = SystemModel.CreateSimpleConnDisp(
                                (SystemModel.Meta as MgaMetaModel).RoleByName["PortComposition"],
                                newConnSrcPort,
                                newConnDstPort,
                                newConnSrcParent,
                                newConnDstParent);
                        }
                        catch (Exception ex)
                        {
                            GMEConsole.Warning.WriteLine(
                                "Exception making connection between {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                                newConnSrcParent.Name,
                                newConnSrcPort.Name,
                                newConnDstParent.Name,
                                newConnDstPort.Name,
                                systemID,
                                systemName);
                            GMEConsole.Error.WriteLine("trace: {0}",
                                ex.StackTrace);
                            GMEConsole.Error.WriteLine("message: {0}",
                                ex.Message);
                        }
                    }
                    else
                    {
                        GMEConsole.Warning.WriteLine(
                            "Object missing for connection between {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                            srcParentName,
                            srcPortName,
                            dstParentName,
                            dstPortName,
                            systemID,
                            systemName);
                    }
                }
                catch (Exception ex)
                {
                    GMEConsole.Warning.WriteLine(
                        "Unknown Exception making connection between {0}.{1}<=>{2}.{3} within <a href=\"mga:{4}\">{5}</a>",
                        srcParentName,
                        srcPortName,
                        dstParentName,
                        dstPortName,
                        systemID,
                        systemName);
                    GMEConsole.Error.WriteLine("trace: {0}",
                        ex.StackTrace);
                    GMEConsole.Error.WriteLine("message: {0}",
                        ex.Message);
                }
            }
        }
        private Dictionary<string, List<MgaFCO>> GetAllChildren(MgaModel root)
        {
            if (root == null) return new Dictionary<string, List<MgaFCO>>();

            var result = new Dictionary<string, List<MgaFCO>>();
            var models = new List<MgaModel>();

            foreach (var childObject in root.ChildObjects.OfType<MgaFCO>())
            {
                var kind = childObject.Meta.Name;
                if (!result.ContainsKey(kind))
                    result[kind] = new List<MgaFCO>();

                result[kind].Add(childObject);

                if (childObject is MgaModel) models.Add((MgaModel)childObject);
            }

            foreach (var model in models)
            {
                var tmp = GetAllChildren(model);

                foreach (var tmpChild in tmp.Where(tmpChild => tmpChild.Value != null))
                {
                    if (!result.ContainsKey(tmpChild.Key))
                        result[tmpChild.Key] = new List<MgaFCO>();

                    result[tmpChild.Key].AddRange(tmpChild.Value);
                }
            }

            return result;
        }
Example #36
0
 private static MgaFCO makeFCO(MgaModel parent, string role)
 {
     MgaFCO newFCO = parent.CreateChildObject((parent.Meta as MgaMetaModel).RoleByName[role]);
     newFCO.Name = role;
     return newFCO;
 }
Example #37
0
        //assume root model (located directly in folder) will not need replacing
        //creates all model, atoms, and reference replacements (not connections)
        //Parents of new/old objects is set to the new object if model is being replaced
        //properties are copied over
        private void createNewFCOs(MgaModel model)
        {
            bool newParent = model.ParentFolder == null && oldToNewFCO.ContainsKey(model as MgaFCO);
            if (model == null || migratedModels.Contains(model) || (model.IsInstance && !newParent)) //if model already migrated, stop //INSTANCE BUG SOLUTION
                return;

            
            //INSTANCE BUG SOLUTION
            if (model.IsInstance) //newParent = true
            {
                foreach (var childObject in model.ChildObjects.OfType<MgaFCO>())
                {
                    oldToNewFCO.Add(childObject, null);
                    if (childObject is MgaModel)
                        createNewFCOs(childObject as MgaModel);
                }
                migratedModels.Add(model);
                return;
            }
            //END SOLUTION

            foreach (var childObject in model.ChildObjects.OfType<MgaFCO>())
            {
                string role = (childObject as MgaFCO).MetaRole.Name;

                //special case (cadmodel): assumes cadmodel is not replaced
                if (role == "CADModel")
                {
                    string cadFileType = childObject.get_StrAttrByName("FileType");
                    string cadFileExtension = (cadFileType == "Part") ? ".prt" : ".asm";

                    //check already has resource?
                    bool makeFCOs = true;
                    foreach (MgaConnPoint point in childObject.PartOfConns)
                    {
                        if (point.Owner.MetaRole.Name == "UsesResource")
                        {
                            makeFCOs = false;

                            MgaConnection conn = point.Owner;
                            MgaFCO resourceObj = null;
                            if ((conn as IMgaSimpleConnection).Dst.Meta.Name == "Resource")
                            {
                                resourceObj = (conn as IMgaSimpleConnection).Dst;
                            }
                            else if ((conn as IMgaSimpleConnection).Src.Meta.Name == "Resource")
                            {
                                resourceObj = (conn as IMgaSimpleConnection).Src;
                            }

                            if (resourceObj != null)
                                UpdateResourcePath(resourceObj,
                                                   cadFileExtension);
                        }
                    }

                    if (makeFCOs)
                    {
                        MgaFCO resource;
                        MgaFCO conn;
                        if (newParent)
                        {
                            MgaFCO newCAD = makeFCO(oldToNewFCO[model as MgaFCO] as MgaModel, childObject.MetaRole.Name);
                            oldToNewFCO.Add(childObject, newCAD);
                            copyFCO(childObject, newCAD);
                            resource = makeFCO(oldToNewFCO[model as MgaFCO] as MgaModel, "Resource");
                            conn = makeConn(oldToNewFCO[model as MgaFCO] as MgaModel, newCAD, resource, "UsesResource");
                        }
                        else
                        {
                            resource = makeFCO(model, "Resource");
                            conn = makeConn(model, childObject, resource, "UsesResource");
                        }
                        resource.set_StrAttrByName("Path", childObject.get_StrAttrByName("FilePathWithinResource"));
                        childObject.set_StrAttrByName("FilePathWithinResource", "");
                        UpdateResourcePath(resource,
                                           cadFileExtension);
                    }
                }

                if (childObject.ArcheType != null && RootFolder != project.RootFolder 
                    && !oldToNewFCO.ContainsKey(childObject.ArcheType) && !willBeMigrated(childObject.ArcheType)) //migrate archetype if not going to be/hasn't been migrated 
                        createNewFCOs(childObject.ArcheType.ParentModel);
                if (oldToNewRole.ContainsKey(role) 
                    && !oldToNewFCO.ContainsKey(childObject)
                    && !(childObject is MgaConnection)) //if child type is obselete, not yet migrated, and not a connection
                {
                    //general case for models/atoms/references
                    if (newParent)
                        oldToNewFCO.Add(childObject, makeFCO(oldToNewFCO[model as MgaFCO] as MgaModel, oldToNewRole[role]));
                    else
                        oldToNewFCO.Add(childObject, makeFCO(model, oldToNewRole[role]));
                    if(childObject.Name != childObject.MetaRole.Name && childObject.Name != childObject.Meta.Name && childObject.Name != childObject.Meta.DisplayedName) //name default?
                        oldToNewFCO[childObject].Name = childObject.Name;

                    //copy over specified properties to new FCO
                    if (role == "StructuralInterface")
                    {
                        oldToNewFCO[childObject].set_StrAttrByName("Definition", childObject.get_StrAttrByName("Type"));
                        oldToNewFCO[childObject].Name = childObject.Name;
                    }
                    else if (role == "SurfaceGeometry" || role == "AxisGeometry" || role == "PointGeometry" || role == "CoordinateSystemGeometry")
                    {
                        oldToNewFCO[childObject].set_StrAttrByName("DatumName", childObject.get_StrAttrByName("Datum"));
                    } 
                }
                else if (newParent && !oldToNewFCO.ContainsKey(childObject) && !(childObject is MgaConnection)) //if child type not obselete, not yet migrated, needs a new parent (and not a connection)
                {
                    MgaFCO copy = makeFCO(oldToNewFCO[model as MgaFCO] as MgaModel, childObject.MetaRole.Name);
                    copyFCO(childObject, copy);
                    oldToNewFCO.Add(childObject, copy);
                }

                //for directFCOs
                if (childObject is MgaConnection || childObject is MgaReference)
                    oldConnsAndRefs.Add(childObject);
                if (childObject.ArcheType != null)
                    oldSubsAndInstances.Add(childObject);
                //recursion
                if (childObject is MgaModel)
                    createNewFCOs(childObject as MgaModel);
            }
            migratedModels.Add(model);
        }
Example #38
0
        public void migrateModel(MgaModel rootmodel)
        {
            RootFolder = null;
            RootModel = rootmodel;

            createNewFCOs(rootmodel);
            directFCOs();
            copyOldLayout();
            deleteOldFCOs();
        }
Example #39
0
        public void migrateFolder(MgaFolder rootfolder)
        {
            RootFolder = rootfolder;
            RootModel = null;

            List<MgaFolder> folders = getAllFolders(rootfolder);
            foreach (MgaFolder folder in folders)
                foreach (MgaModel model in folder.ChildObjects.OfType<MgaModel>())
                    createNewFCOs(model);
            directFCOs();
            copyOldLayout();
            deleteOldFCOs();
        }
        private void VisitTestComponent(MgaModel testComp)
        {
            #region Check arguments
            if (testComp == null)
            {
                throw new ArgumentNullException("testComp");
            }
            if (testComp.MetaBase.MetaRef != MetaRef["TestComponent"])
            {
                throw new ArgumentException("Input parameter was not a Test Component.", "testComp");
            }
            #endregion
            Logger.WriteDebug("VisitTestComponent: {0}", testComp.AbsPath);

            if (testComp.ArcheType != null)
            {
                Logger.WriteDebug("VisitTestComponent: Has an archetype, detaching {0}", testComp.AbsPath);

                SetAttributesLocally(testComp as MgaFCO);
                testComp.DetachFromArcheType();
            }

            foreach (MgaModel connector in testComp.GetChildrenOfKind("Connector"))
            {
                VisitConnector(connector);
            }
        }
        private void VisitComponentAssembly(MgaModel assembly)
        {
            #region Check arguments
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }
            if (assembly.MetaBase.MetaRef != MetaRef["ComponentAssembly"])
            {
                throw new ArgumentException("Input parameter was not a component assembly.", "assembly");
            }
            #endregion
            Logger.WriteDebug("VisitComponentAssembly: {0}", assembly.AbsPath);

            foreach (MgaModel asm in assembly.GetChildrenOfKind("ComponentAssembly"))
            {
                VisitComponentAssembly(asm);
            }

            foreach (MgaModel component in assembly.GetChildrenOfKind("Component"))
            {
                VisitComponent(component as MgaModel);
            }

            foreach (MgaModel connector in assembly.GetChildrenOfKind("Connector"))
            {
                VisitConnector(connector);
            }

            ExpandConnectorCompositionChildren(assembly);
        }
Example #42
0
 private static MgaFCO makeConn(MgaModel parent, MgaFCO src, MgaFCO dst, string role, MgaFCOs srcRef=null, MgaFCOs dstRef=null)
 {
     MgaFCO newConn;
     if (srcRef == null && dstRef == null)
         newConn = parent.CreateSimplerConnDisp((parent.Meta as MgaMetaModel).RoleByName[role], src, dst);
     else
         newConn = parent.CreateSimpleConn((parent.Meta as MgaMetaModel).RoleByName[role], src, dst, srcRef, dstRef);
     newConn.Name = role;
     return newConn;
 }
        private void VisitComponent(MgaModel comp)
        {
            #region Check arguments
            if (comp == null)
            {
                throw new ArgumentNullException("comp");
            }
            if (comp.MetaBase.MetaRef != MetaRef["Component"])
            {
                throw new ArgumentException("Input parameter was not a component.", "comp");
            }
            #endregion
            Logger.WriteDebug("VisitComponent: {0}", comp.AbsPath);

            if (componentsProcessed.Contains(comp))
            {
                Logger.WriteDebug("VisitComponent: Skipping (already processed) {0}", comp.AbsPath);

                return;
            }

            // Is this an instance?
            // If so, process the archetype only.
            if (comp.ArcheType != null)
            {
                Logger.WriteDebug("VisitComponent: Processing Archetype instead {0}", comp.AbsPath);

                var archetype = comp.ArcheType as MgaModel;
                VisitComponent(archetype);

                return;
            }

            foreach (MgaModel connector in comp.GetChildrenOfKind("Connector"))
            {
                VisitConnector(connector);
            }
        }
        private static void GenerateAssemblies(MgaFolder componentAssemblyFolder, MgaModel assembly, int level, MgaModel leaf)
        {
            var elementsOnEachLevel = 2;
            var numberOfLevels = 6;

            if (level <= numberOfLevels)
            {
                System.Console.Out.WriteLine(level);

                MgaFolder componentAssemblyChildFolder = componentAssemblyFolder.CreateFolder(componentAssemblyFolder.Project.RootMeta.RootFolder.DefinedFolderByName["ComponentAssemblies", true]);

                componentAssemblyChildFolder.Name = string.Format("ComponentAssembly Child folder {0}", level);

                for (int i = 0; i < elementsOnEachLevel; i++)
                {
                    var childAssembly = componentAssemblyChildFolder.CreateRootObject(assembly.Meta) as MgaModel;
                    childAssembly.Name = string.Format("ChildAssembly {0} {1}", level, i);

                    var cref = assembly.CreateChildObject((assembly.Meta as GME.MGA.Meta.MgaMetaModel).RoleByName["ComponentRef"]) as MgaReference;
                    cref.Name = string.Format("ComponentRef {0} {1}", level, i);

                    if (level < numberOfLevels)
                    {
                        cref.Referred = childAssembly as MgaFCO;
                        GenerateAssemblies(componentAssemblyFolder, childAssembly, level + 1, leaf);
                    }
                    else
                    {
                        cref.Referred = leaf as MgaFCO;
                    }
                }
            }
        }
        public void UnrollComponent(MgaModel comp, Boolean cleanup = true)
        {
            Logger.WriteDebug("UnrollComponent: {0}", comp.AbsPath);

            VisitComponent(comp);
            if (cleanup)
            {
                DeleteConnectorsAndPorts();
            }
        }
        // Recursive function that will keep looking for:
        //      -DesignContainers
        //      -ComponentAssemblies
        //      -ComponentRefs => referred Component
        // and migrate the deepest level first
        public void migrateModel(MgaModel model)
        {
            try
            {
                MgaModel archetype =
                    (model.ArcheType == null) ?
                    model :
                    model.ArcheType as MgaModel;

                // Skip the model if its archetype has already been migrated
                if (migratedModels.Contains(archetype))
                {
                    return;
                }
                // Skip the model if it contains 'new' port types
                if (archetype.ChildObjects.OfType<MgaModel>().Where(x => x.Meta.Name == "ModelicaConnector").FirstOrDefault() != null)
                {
                    GMEConsole.Info.WriteLine(
                        "Found new connector type in MgaModel, assumed to be migrated: <a href=\"mga:{0}\">{1}</a>",
                        archetype.ID,
                        archetype.Name);

                    return;
                }

                string parName = (archetype.ParentFolder == null) ? archetype.ParentModel.Name : archetype.ParentFolder.Name;
                //GMEConsole.Info.WriteLine("migrateModel(<a href=\"mga:{0}\">{1}</a>)", archetype.ID, archetype.Name);

                // if this model is an archetype, make a copy to preserve original
                MgaModel untouchedOriginal = makeCopyOfModel(archetype, "_original");
                mapModel_migrated2original.Add(archetype, untouchedOriginal);

                // get all the children of this model, and migrate them also. Assume only on TLSUT within a model
                var topLevelSUT = archetype.ChildObjects.OfType<MgaReference>().Where(x => x.Meta.Name == "TopLevelSystemUnderTest").FirstOrDefault();
                var testComponents = archetype.ChildObjects.OfType<MgaModel>().Where(x => x.Meta.Name == "TestComponent");
                var components = archetype.ChildObjects.OfType<MgaModel>().Where(x => x.Meta.Name == "Component");
                var childDesignContainers = archetype.ChildObjects.OfType<MgaModel>().Where(x => x.Meta.Name == "DesignContainer");
                var childComponentAssemblies = archetype.ChildObjects.OfType<MgaModel>().Where(x => x.Meta.Name == "ComponentAssembly");
                var childComponentRefs = archetype.ChildObjects.OfType<MgaReference>().Where(x => x.Meta.Name == "ComponentRef");
                var childComponentAssemblyRefs = archetype.ChildObjects.OfType<MgaReference>().Where(x => x.Meta.Name == "ComponentAssemblyRef");
                var childModelicaModels = archetype.ChildFCOs.OfType<MgaModel>().Where(x => x.Meta.Name == "ModelicaModel");
                var childEnvironments = archetype.ChildFCOs.OfType<MgaModel>().Where(x => x.Meta.Name == "Environment");

                foreach (var mm in childModelicaModels)
                {
                    migrateModel(mm);
                }

                foreach (var env in childEnvironments)
                {
                    migrateModel(env);
                }

                foreach (MgaModel tComp in testComponents)
                {
                    migrateModel(tComp);
                }

                foreach (MgaModel comp in components)
                {
                    migrateModel(comp);
                }

                foreach (MgaReference compRef in childComponentRefs)
                {
                    if (compRef.Referred != null)
                    {
                        MgaModel referred = compRef.Referred as MgaModel;
                        migrateModel(referred);
                    }
                }

                foreach (MgaModel dc in childDesignContainers)
                {
                    migrateModel(dc);
                }

                foreach (MgaModel ca in childComponentAssemblies)
                {
                    migrateModel(ca);
                }

                foreach (MgaReference compAssemblyRef in childComponentAssemblyRefs)
                {
                    if (compAssemblyRef.Referred != null)
                    {
                        MgaModel referred = compAssemblyRef.Referred as MgaModel;
                        migrateModel(referred);
                    }
                }

                if (topLevelSUT != null)
                {
                    if (topLevelSUT.Referred != null)
                    {
                        MgaModel referredSystem = topLevelSUT.Referred as MgaModel;
                        migrateModel(referredSystem);
                    }
                }

                migratePorts(archetype);
                migratedModels.Add(archetype);
            }
            catch (Exception ex)
            {
                GMEConsole.Info.WriteLine(
                    "Could not migrate: <a href=\"mga:{0}\">{1}</a>. ({2})",
                    model.ID,
                    model.Name,
                    model.AbsPath);

                GMEConsole.Error.WriteLine(ex.Message);
            }
        }
Example #47
0
 private static List<MgaFCO> FindByRole(MgaModel mgaModel,
                         string roleName)
 {
     return mgaModel.ChildFCOs.Cast<MgaFCO>().Where(x => x.MetaRole.Name == roleName).ToList();
 }
        private MgaModel makeCopyOfModel(MgaModel originalModel, string nameModifier)
        {
            MgaModel copyForMigration = null;

            if (originalModel.ParentFolder != null)
            {
                MgaFolder parentFolder = originalModel.ParentFolder;
                copyForMigration = (MgaModel)parentFolder.CopyFCODisp(originalModel as MgaFCO);
                copyForMigration.Name = originalModel.Name + nameModifier;
            }
            //else if (originalModel.ParentModel != null)
            //{
            //    GMEConsole.Info.WriteLine(
            //        "Did not copy: <a href=\"mga:{0}\">{1}</a>. (not a Root Object)",
            //        originalModel.ID,
            //        originalModel.Name);
            //}

            return copyForMigration;
        }
        public void migratePorts(MgaModel rootModel)
        {
            string parName = (rootModel.ParentFolder == null) ? rootModel.ParentModel.Name : rootModel.ParentFolder.Name;
            //GMEConsole.Info.WriteLine("migratePorts({0}.{1})", parName, rootModel.Name);
            string kind = rootModel.Meta.Name;

            var childFCOs = rootModel.ChildFCOs.Cast<MgaFCO>().Where(x =>
                x.Meta.Name != "Property" &&
                x.Meta.Name != "ModelicaParameter" &&
                x.Meta.Name != "ModelicaMaterialSpec");

            foreach (var fco in childFCOs)
            {
                MigrateObject(fco);
            }

            if (kind == "ComponentAssembly" ||
                kind == "DesignContainer" ||
                kind == "TestBench")
            {
                migrateSystemConns(rootModel);
            }
        }
Example #50
0
 private MgaFCO CreateChild(MgaModel parent, Type type)
 {
     var role = ((MgaMetaModel)parent.MetaBase).RoleByName[type.Name];
     return (MgaFCO)((MgaModel)parent).CreateChildObject(role);
 }
Example #51
0
        private MgaFCO CreateChild(MgaModel parent, Type type)
        {
            var role = ((MgaMetaModel)parent.MetaBase).RoleByName[type.Name];

            return((MgaFCO)((MgaModel)parent).CreateChildObject(role));
        }
Example #52
0
        private void _GetTestbenchesFromModel(MgaModel sot, string outputBaseDir)
        {
            var tbRefs = sot
                         .ChildObjects
                         .OfType <MgaReference>()
                         .Where(x => x.Meta.Name == typeof(CyPhy.TestBenchRef).Name);

            foreach (var tbRef in tbRefs)
            {
                var task = tbRef
                           .Referred
                           .ChildObjects
                           .OfType <MgaReference>()
                           .FirstOrDefault(x => x.Meta.Name == typeof(CyPhy.WorkflowRef).Name)
                           .Referred
                           .ChildObjects
                           .OfType <MgaAtom>()
                           .FirstOrDefault();

                var parameters     = task.StrAttrByName["Parameters"];
                var parametersDict = new Dictionary <string, string>();
                if (string.IsNullOrWhiteSpace(parameters) == false)
                {
                    try
                    {
                        parametersDict = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(parameters);
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine(ex);
                        //Trace.TraceWarning(ex.ToString());
                        this.Logger.WriteWarning(ex.ToString());
                    }
                }

                var testbench = new TestBench();
                testbench.OutputDirectory = GetRandomTBDir(outputBaseDir);
                if (Directory.Exists(testbench.OutputDirectory) == false)
                {
                    Directory.CreateDirectory(testbench.OutputDirectory);
                }
                testbench.Project     = tbRef.Project;
                testbench.CurrentObj  = tbRef.Referred;
                testbench.ParamInvoke = paramInvoked;

                testbench.Name   = string.Format("{0}__{1}", tbRef.Referred.RegistryValue["TestBenchUniqueName"], tbRef.Referred.Name);
                testbench.ProgId = task.StrAttrByName["COMName"];
                testbench.WorkflowParametersDict = parametersDict;

                TestBenches.Add(testbench);
            }

            UpdateDependency(sot);
            if (this.DependencyGraph == null)
            {
                this.Logger.WriteWarning("Dependency was not determined running all test benches without dependencies.");
                return;
            }

            // Update Testbench upstream and downstream dependencies based on the MgaFCO dependency map/list
            foreach (var chain in this.DependencyGraph.Where(x => x.Key.Meta.Name == typeof(CyPhy.TestBenchRef).Name))
            {
                this.TestBenches.First(x => x.CurrentObj.ID == ((MgaReference)chain.Key).Referred.ID).UpstreamTestBenches.AddRange(
                    chain.Value.Select(x => this.TestBenches.First(y => y.CurrentObj.ID == ((MgaReference)x).Referred.ID)));
            }
            foreach (var tb in this.TestBenches)
            {
                foreach (var upstream in tb.UpstreamTestBenches)
                {
                    upstream.DownstreamTestBenches.Add(tb);
                }
                tb.CollectDeps();
            }
        }
        // What do we have to do here now?
        // Well, if this connector has instances, we need to add port maps for those things too.
        // Then those connectors need to be visited to connections can be adjusted.
        private void VisitConnector(MgaModel connector)
        {
            #region Check arguments
            if (connector == null)
            {
                throw new ArgumentNullException("connector");
            }
            if (connector.MetaBase.MetaRef != MetaRef["Connector"])
            {
                throw new ArgumentException("Input parameter was not a connector.", "connector");
            }
            if (ConnectorsProcessed.Contains(connector))
            {
                return;
            }
            #endregion
            Logger.WriteDebug("VisitConnector: {0}", connector.AbsPath);

            ConnectorToStandalonePortMap.Add(connector, new List<PortWrapper>());
            var parent = connector.ParentModel;
            
            Boolean connectorIsArchetype = (connector.ArcheType == null);
            Boolean parentIsArchetype = (parent.ArcheType == null);
            if (parentIsArchetype)
            {
                Logger.WriteDebug("VisitConnector: Processing with parent as Archetype");

                if (connectorIsArchetype)
                {
                    Logger.WriteDebug("VisitConnector: Processing connector as Archetype");
                }
                else
                {
                    Logger.WriteDebug("VisitConnector: Processing connector as Derived");
                    Logger.WriteDebug("VisitConnector: Setting connector's local attributes and detaching");

                    SetAttributesLocally(connector as MgaFCO);
                    connector.DetachFromArcheType();
                }

                // I'm an archetype.
                // Go through each supported port, clone it, and create a wrapper.
                // Add it to traceability.
                // Redirect connections to constituent ports.
                foreach (MgaFCO port in connector.ChildFCOs)
                {
                    if (false == SupportedPortTypesMeta.Contains(port.MetaBase.MetaRef))
                    {
                        Logger.WriteDebug("VisitConnector: Skipping unsupported port {0}", port.AbsPath);

                        continue;
                    }

                    var newPort = ClonePort(parent, port);
                    newPort.Name = String.Format("{0}__{1}", connector.Name, port.Name);

                    var wrapper = new PortWrapper()
                    {
                        SourceConnector = connector,
                        SourcePortRole = port.Name,
                        SourcePort = port,
                        StandalonePort = newPort
                    };
                    ConnectorToStandalonePortMap[connector].Add(wrapper);

                    // See if the derived guy is itself in the Traceability.
                    String lastGood = port.ID;
                    String iter = null;
                    while (Traceability.TryGetMappedObject(lastGood, out iter) 
                           && lastGood != iter)
                    {
                        lastGood = iter;
                    }
                    Traceability.AddItem(newPort.ID, lastGood);
                }

                RedirectConnectionsToConstituentPorts(connector);
            }
            else
            {
                Logger.WriteDebug("VisitConnector: Processing as Derived");

                var connectorArchetype = connector.ArcheType as MgaModel;

                // I'm derived. What we need to do is go through each
                // port, and create a new wrapper for each one.
                foreach (MgaFCO derivedPort in connector.ChildFCOs)
                {
                    if (false == SupportedPortTypesMeta.Contains(derivedPort.MetaBase.MetaRef))
                    {
                        Logger.WriteDebug("VisitConnector: Skipping unsupported derived port {0}", derivedPort.AbsPath);

                        continue;
                    }

                    // Find the wrapper for these guys
                    var orgWrapper = ConnectorToStandalonePortMap[connectorArchetype]
                                                    .FirstOrDefault(w => w.SourceConnector == connectorArchetype
                                                                      && w.SourcePort == derivedPort.ArcheType);

                    if (orgWrapper == null)
                    {
                        Logger.WriteDebug("VisitConnector: orgWrapper is null for {0}", derivedPort.AbsPath);
                        throw new ArgumentNullException("orgWrapper is null for " + derivedPort.AbsPath);
                    }

                    // Now guess at the standalone port.
                    MgaFCO standalonePort = null;
                    foreach (MgaFCO brokenOutPort in parent.ChildFCOs)
                    {
                        if (brokenOutPort.ArcheType != null
                            && brokenOutPort.ArcheType == orgWrapper.StandalonePort)
                        {
                            standalonePort = brokenOutPort;
                            break;
                        }
                    }

                    if (standalonePort == null)
                    {
                        Logger.WriteDebug("VisitConnector: standalonePort is null for {0}", derivedPort.AbsPath);
                        throw new ArgumentNullException("standalonePort is null for " + derivedPort.AbsPath);
                    }

                    var wrapper = new PortWrapper()
                    {
                        SourceConnector = connector,
                        SourcePortRole = derivedPort.Name,
                        SourcePort = derivedPort,
                        StandalonePort = standalonePort
                    };
                    ConnectorToStandalonePortMap[connector].Add(wrapper);

                    // See if the derived guy is itself in the Traceability.
                    String lastGood = derivedPort.ID;
                    String iter = null;
                    while (Traceability.TryGetMappedObject(lastGood, out iter)
                           && lastGood != iter)
                    {
                        lastGood = iter;
                    }
                    Traceability.AddItem(standalonePort.ID, lastGood);
                }
            }

            foreach (MgaModel derivedConnector in connector.DerivedObjects)
            {
                Logger.WriteDebug("VisitConnector: Visiting derived connector {0}", derivedConnector.AbsPath);
                VisitConnector(derivedConnector);
            }

            ConnectorsProcessed.Add(connector);
        }
Example #54
0
        /// <summary>
        /// Call this function within a transaction!
        /// </summary>
        /// <param name="outputDirectory"></param>
        /// <param name="project"></param>
        /// <param name="rootDS"></param>
        /// <param name="textWriter"></param>
        /// <returns></returns>
        public static MetaAvmProject Create(
            string outputDirectory,
            MgaProject project = null,
            MgaModel rootDS = null,
            GME.CSharp.GMEConsole console = null
            )
        {
            MetaAvmProject avmProj = new MetaAvmProject();

            string currentDir = Environment.CurrentDirectory;

            Directory.SetCurrentDirectory(outputDirectory);

            string avmProjFileName = Path.GetFullPath(Path.Combine(outputDirectory, "manifest.project.json"));

            if (File.Exists(avmProjFileName))
            {
                string sjson = "{}";
                using (StreamReader reader = new StreamReader(avmProjFileName))
                {
                    sjson = reader.ReadToEnd();
                    avmProj = JsonConvert.DeserializeObject<AVM.DDP.MetaAvmProject>(sjson);
                }
            }

            if (console != null)
            {
                avmProj.infoTextWriter = console.Info;
                avmProj.errorTextWriter = console.Error;
            }

            avmProj.m_filename = avmProjFileName;

            avmProj.Project.LastModified = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");

            if (avmProj.Project.Results.UrlHints.Contains("./results/results.metaresults.json") == false)
            {
                avmProj.Project.Results.UrlHints.Add("./results/results.metaresults.json");
            }

            if (avmProj.Project.Requirements.UrlHints.Contains("./requirements/requirements.json") == false)
            {
                avmProj.Project.Requirements.UrlHints.Add("./requirements/requirements.json");
            }

            string reqSourceRepository = string.Empty;
            string reqId = string.Empty;
            string reqText = string.Empty;

            if (project != null)
            {
                CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project);

                var topLevelLinks = rf.Children.RequirementsCollection
                    .SelectMany(x => x.Children.RequirementLinkCollection);

                var defaults = topLevelLinks.Where(x => x.Name.ToLowerInvariant() == "default");
                var reqDefault = defaults.FirstOrDefault();
                if (defaults.Count() > 1)
                {
                    // more requ found first one will be used
                    string msg = string.Format("More than one Requirement was not found {0} in use.", reqDefault.Impl.AbsPath);
                    Trace.TraceWarning(msg);
                    avmProj.infoTextWriter.WriteLine(msg);

                }

                if (reqDefault != null)
                {
                    reqSourceRepository = reqDefault.Attributes.SourceRepository;
                    reqId = reqDefault.Attributes.ID;
                    reqText = reqDefault.Attributes.Text;
                }
                else
                {
                    // requ not found
                    string msg = "Requirement was not found.";
                    Trace.TraceWarning(msg);
                    avmProj.infoTextWriter.WriteLine(msg);
                }
            }

            avmProj.Project.Requirements.vfLink = reqSourceRepository;
            avmProj.Project.Requirements.id = reqId;
            avmProj.Project.Requirements.text = reqText;

            string dirName = Path.GetFullPath(Path.Combine(outputDirectory, "requirements"));

            if (Directory.Exists(dirName) == false)
            {
                Directory.CreateDirectory(dirName);
                string requFileName = Path.GetFullPath(Path.Combine(dirName, "requirements.json"));

                if (File.Exists(requFileName) == false)
                {
                    using (StreamWriter writer = new StreamWriter(requFileName))
                    {
                        // default requirement
                        writer.WriteLine(@"{");
                        writer.WriteLine("    \"name\": \"Undefined\",");
                        writer.WriteLine("    \"children\": []");
                        writer.WriteLine(@"}");
                    }
                }
            }

            string designSpaceFolder = "design-space";
            dirName = Path.GetFullPath(Path.Combine(outputDirectory, designSpaceFolder));

            if (Directory.Exists(dirName) == false)
            {
                Directory.CreateDirectory(dirName);
            }

            if (rootDS != null)
            {
                // export designspace
                var dsProjectJsonLink = Path.Combine(".", designSpaceFolder, rootDS.Name + ".metadesign.json").Replace('\\', '/');
                var dsFileName = Path.Combine(dirName, rootDS.Name + ".metadesign.json");

                if (avmProj.Project.DesignSpaceModels.Contains(dsProjectJsonLink) == false)
                {
                    avmProj.Project.DesignSpaceModels.Add(dsProjectJsonLink);
                }
                var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(rootDS);
                var design = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(designContainer);
                string d = design.SerializeToFile(Path.GetFullPath(dsFileName));
            }

            Directory.SetCurrentDirectory(currentDir);
            return avmProj;
        }
        private MgaFCO ClonePort(MgaModel parent, MgaFCO oldPort)
        {
            Logger.WriteDebug("ClonePort: {0}", oldPort.AbsPath);

            GME.MGA.Meta.MgaMetaRole role = null;

            foreach (GME.MGA.Meta.MgaMetaRole roleItem in (parent.Meta as GME.MGA.Meta.MgaMetaModel).Roles)
            {
                if (roleItem.Kind.MetaRef == oldPort.MetaBase.MetaRef)
                {
                    role = roleItem;
                    break;
                }
            }

            var newPortFCO = parent.CopyFCODisp(oldPort, role);
            //newPortFCO.SetAttributeByNameDisp("ID", null);
            return newPortFCO;
        }
        public void UnrollTestBench(MgaModel tb)
        {
            Logger.WriteDebug("UnrollTestBench: {0}", tb.AbsPath);

            VisitTestBench(tb);
            DeleteConnectorsAndPorts();
        }
        public void UnrollComponentAssembly(MgaModel ca)
        {
            Logger.WriteDebug("UnrollComponentAssembly: {0}", ca.AbsPath);

            VisitComponentAssembly(ca);
            DeleteConnectorsAndPorts();
        }
Example #58
0
        /// <summary>
        /// Call this function within a transaction!
        /// </summary>
        /// <param name="outputDirectory"></param>
        /// <param name="project"></param>
        /// <param name="rootDS"></param>
        /// <param name="textWriter"></param>
        /// <returns></returns>
        public static MetaAvmProject Create(
            string outputDirectory,
            MgaProject project            = null,
            MgaModel rootDS               = null,
            GME.CSharp.GMEConsole console = null
            )
        {
            MetaAvmProject avmProj = new MetaAvmProject();

            outputDirectory = Path.GetFullPath(outputDirectory);
            Directory.CreateDirectory(outputDirectory);

            string avmProjFileName = Path.GetFullPath(Path.Combine(outputDirectory, "manifest.project.json"));

            using (new MutexWrapper(avmProjFileName))
            {
                if (File.Exists(avmProjFileName))
                {
                    string sjson = "{}";
                    using (StreamReader reader = new StreamReader(avmProjFileName))
                    {
                        sjson = reader.ReadToEnd();

                        try
                        {
                            avmProj = JsonConvert.DeserializeObject <AVM.DDP.MetaAvmProject>(sjson);
                        }
                        catch (Newtonsoft.Json.JsonReaderException ex)
                        {
                            throw new Exception(string.Format("{0} file is probably malformed. Not a valid json. {1}{2}", Path.GetFullPath(avmProjFileName), Environment.NewLine, ex.Message));
                        }
                    }
                }
            }

            if (console != null)
            {
                avmProj.infoTextWriter  = console.Info;
                avmProj.errorTextWriter = console.Error;
            }

            avmProj.OutputDirectory = outputDirectory;
            avmProj.m_filename      = avmProjFileName;


            avmProj.Project.LastModified = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");

            if (avmProj.Project.Results.UrlHints.Contains("./results/results.metaresults.json") == false)
            {
                avmProj.Project.Results.UrlHints.Add("./results/results.metaresults.json");
            }

            if (avmProj.Project.Requirements.UrlHints.Contains("./requirements/requirements.json") == false)
            {
                avmProj.Project.Requirements.UrlHints.Add("./requirements/requirements.json");
            }

            string reqSourceRepository = string.Empty;
            string reqId   = string.Empty;
            string reqText = string.Empty;

            if (project != null)
            {
                avmProj.Project.CyPhyProjectFileName = MgaExtensions.MgaExtensions.GetProjectName(project);

                CyPhy.RootFolder rf = ISIS.GME.Dsml.CyPhyML.Classes.RootFolder.GetRootFolder(project);

                var topLevelLinks = rf.Children.RequirementsCollection
                                    .SelectMany(x => x.Children.RequirementLinkCollection);

                var defaults   = topLevelLinks.Where(x => x.Name.ToLowerInvariant() == "default");
                var reqDefault = defaults.FirstOrDefault();
                if (defaults.Count() > 1)
                {
                    // more requ found first one will be used
                    string msg = string.Format("More than one Requirement was not found {0} in use.", reqDefault.Impl.AbsPath);
                    Trace.TraceWarning(msg);
                    avmProj.infoTextWriter.WriteLine(msg);
                }

                if (reqDefault != null)
                {
                    reqSourceRepository = reqDefault.Attributes.SourceRepository;
                    reqId   = reqDefault.Attributes.ID;
                    reqText = reqDefault.Attributes.Text;
                }
                else
                {
                    // requ not found
                    string msg = "Requirement was not found.";
                    Trace.TraceWarning(msg);

                    // RESTORE THIS MESSAGE ONCE WE SWITCH TO USING GMELOGGER
                    // avmProj.infoTextWriter.WriteLine(msg);
                }
            }

            avmProj.Project.Requirements.vfLink = reqSourceRepository;
            avmProj.Project.Requirements.id     = reqId;
            avmProj.Project.Requirements.text   = reqText;

            string dirName = Path.Combine(outputDirectory, "requirements");

            if (Directory.Exists(dirName) == false)
            {
                Directory.CreateDirectory(dirName);
                string requFileName = Path.GetFullPath(Path.Combine(dirName, "requirements.json"));

                using (new MutexWrapper(requFileName))
                {
                    if (File.Exists(requFileName) == false)
                    {
                        using (StreamWriter writer = new StreamWriter(requFileName))
                        {
                            // default requirement
                            writer.WriteLine(@"{");
                            writer.WriteLine("    \"name\": \"Undefined\",");
                            writer.WriteLine("    \"children\": []");
                            writer.WriteLine(@"}");
                        }
                    }
                }
            }

            string designSpaceFolder = "design-space";

            dirName = Path.GetFullPath(Path.Combine(outputDirectory, designSpaceFolder));

            Directory.CreateDirectory(dirName);

            if (rootDS != null)
            {
                // export designspace
                var dsProjectJsonLink = Path.Combine(".", designSpaceFolder, rootDS.Name + ".adm").Replace('\\', '/');
                var dsFileName        = Path.Combine(dirName, rootDS.Name + ".adm");

                if (avmProj.Project.DesignSpaceModels.Contains(dsProjectJsonLink) == false)
                {
                    avmProj.Project.DesignSpaceModels.Add(dsProjectJsonLink);
                }
                var designContainer = ISIS.GME.Dsml.CyPhyML.Classes.DesignContainer.Cast(rootDS);
                var design          = CyPhy2DesignInterchange.CyPhy2DesignInterchange.Convert(designContainer);
                using (new MutexWrapper(dsFileName))
                {
                    design.SaveToFile(dsFileName);
                }
            }

            return(avmProj);
        }
        /// <summary>
        /// Given a container, find all ConnectorComposition connections, and make 
        /// new connections between the new "standalone" ports that have been created.
        /// </summary>
        /// <param name="container"></param>
        private void ExpandConnectorCompositionChildren(MgaModel container)
        {
            Logger.WriteDebug("ExpandConnectorCompositionChildren: {0}", container.AbsPath);

            // Find PortComposition role for this parent type
            GME.MGA.Meta.MgaMetaRole role = null;
            foreach (GME.MGA.Meta.MgaMetaRole roleItem in (container.Meta as GME.MGA.Meta.MgaMetaModel).Roles)
            {
                if (roleItem.Name == "PortComposition")
                {
                    role = roleItem;
                    break;
                }
            }

            // For each ConnectorComposition, create new connections between the new "standalone" ports.
            // Since we did depth-first recursion in modifying the connectors, they should all be "expanded"
            // and ready to go.
            foreach (MgaSimpleConnection connectorComposition in container.GetChildrenOfKind("ConnectorComposition"))
            {
                MgaModel connector1 = connectorComposition.Src as MgaModel;
                MgaModel connector2 = connectorComposition.Dst as MgaModel;

                var portsConn1 = ConnectorToStandalonePortMap[connector1];
                var portsConn2 = ConnectorToStandalonePortMap[connector2];

                // For each port, find the analogue from the other connector.
                foreach (var port1 in portsConn1)
                {
                    var kindPort1 = port1.SourcePort.MetaBase.Name;

                    // Try to match by role & kind.
                    var port2 = portsConn2.FirstOrDefault(p2 => p2.SourcePortRole == port1.SourcePortRole
                                                             && p2.SourcePort.MetaBase.Name == kindPort1);

                    // Nominal match case failed. Try alternatives.
                    if (port2 == null)
                    {
                        // If we failed to match by the methods above, we'll try another method.
                        // Try to see if each port's kind is unique to its connector (e.g.: They are the only ModelicaConnectors in their parent Connectors).
                        // If so, then we will go ahead and match them, but yield a warning.

                        Boolean port1KindIsUnique = portsConn1.Where(pc => kindPort1 == pc.SourcePort.MetaBase.Name).Count() == 1;

                        var port2KindMatches = portsConn2.Where(pc => kindPort1 == pc.SourcePort.MetaBase.Name);
                        Boolean port2KindIsUnique = port2KindMatches.Count() == 1;

                        if (port1KindIsUnique && port2KindIsUnique)
                        {
                            // Match anyway based on unique kinds.
                            port2 = port2KindMatches.First();

                            Logger.WriteWarning("Non-name match: " +
                                                "Port {0} in Connector {1} and Port {2} in Connector {3}",
                                                GmeConsoleHelper.ToMgaHyperLink(port1.SourcePort, Traceability),
                                                GmeConsoleHelper.ToMgaHyperLink(port1.SourceConnector, Traceability),
                                                GmeConsoleHelper.ToMgaHyperLink(port2.SourcePort, Traceability),
                                                GmeConsoleHelper.ToMgaHyperLink(port2.SourceConnector, Traceability));
                        }
                        else
                        {
                            // Kinds were not unique, so we can't guess.
                            Logger.WriteWarning("NO MATCH found for Port {0} of Connector {1} with any Port within Connector {2}",
                                                GmeConsoleHelper.ToMgaHyperLink(port1.SourcePort, Traceability),
                                                GmeConsoleHelper.ToMgaHyperLink(port1.SourceConnector, Traceability),
                                                GmeConsoleHelper.ToMgaHyperLink(connector2, Traceability));
                            continue;
                        }
                    }

                    var conn = container.CreateChildObject(role) as MgaSimpleConnection;
                    conn.SetSrc(EmptyArray, port1.StandalonePort);
                    conn.SetDst(EmptyArray, port2.StandalonePort);
                }
            }
        }