Exemplo n.º 1
0
        public static void GenerateSimulink(TestBench selectedTestBench, string outputDirectory, string projectDirectory)
        {
            // Reset block name cache (interpreters don't necessarily get reloaded between executions, so
            // we need to reset any static variables ourselves that need to be reset between executions)
            SimulinkBlock.ResetBlockNameCache();

            var model = new SimulinkModel(selectedTestBench);

            // Copy support files
            CopySupportFile(outputDirectory, "CreateOrOverwriteModel.m", Resources.CreateOrOverwriteModel);
            CopySupportFile(outputDirectory, "PopulateTestBenchParams.py", Resources.PopulateTestBenchParams);

            CopyCopyFiles(selectedTestBench, projectDirectory, outputDirectory);

            var postProcessScripts = GetAndCopyPostProcessScripts(selectedTestBench, projectDirectory, outputDirectory);

            using (var writer = File.CreateText(Path.Combine(outputDirectory, "build_simulink.m.in")))
            {
                model.GenerateSimulinkModelCode(writer);
            }

            using (var writer = File.CreateText(Path.Combine(outputDirectory, "run_simulink.m")))
            {
                model.GenerateSimulinkExecutionCode(writer);
            }

            using (var writer = File.CreateText(Path.Combine(outputDirectory, "run.cmd")))
            {
                GenerateRunCmd(writer, postProcessScripts);
            }
        }
        public override void visit(TestBench obj)
        {
            if (CodeGenerator.verbose) CodeGenerator.GMEConsole.Info.WriteLine("CyPhyBuildVisitor::visit TestBench: {0}", obj.Name);

            var testBench = obj.Impl;
            
            if (testBench.Children.ComponentAssemblyCollection.Count() == 0)
            {
                CodeGenerator.GMEConsole.Error.WriteLine("No valid component assembly in testbench {0}", obj.Name);
                return;
            }

            foreach (var ca in testBench.Children.ComponentAssemblyCollection)
            {
                var componentAssembly_obj = new ComponentAssembly(ca);
                obj.ComponentAssemblies.Add(componentAssembly_obj);
            }

            foreach (var tc in testBench.Children.TestComponentCollection)
            {
                var testComponent_obj = new Component(tc);
                obj.TestComponents.Add(testComponent_obj);
            }

            // Save CyPhy TestBench parameters, such as "simulationTime", in the CyPhy2SystemC testbench object.  MOT-516
            foreach (var p in testBench.Children.ParameterCollection)
            {
                string paramName = p.Name;
                if (!obj.TestParameters.ContainsKey(paramName))
                {
                    obj.TestParameters[paramName] = p;
                }
            }
        }
Exemplo n.º 3
0
        public static void Output()
        {
            var       Tenv       = Input();
            TestBench _TestBench = new TestBench(Tenv);

            Console.WriteLine("Время перегрева двигателя на тестовом стенде \n{0}", _TestBench.TestStartICE());
        }
Exemplo n.º 4
0
        private static IList <string> GetAndCopyPostProcessScripts(TestBench selectedTestBench, string projectDirectory, string outputDirectory)
        {
            var scripts = new List <string>();

            foreach (var postprocessItem in selectedTestBench.Children.PostProcessingCollection)
            {
                if (postprocessItem.Attributes.ScriptPath != "")
                {
                    var fileNameOnly = Path.GetFileName(postprocessItem.Attributes.ScriptPath);

                    if (fileNameOnly != null)
                    {
                        if (File.Exists(Path.Combine(outputDirectory, fileNameOnly)))
                        {
                            GMEConsole.Warning.WriteLine(
                                "PostProcessing script {0} already exists in output directory", fileNameOnly);
                        }
                        else
                        {
                            File.Copy(Path.Combine(projectDirectory, postprocessItem.Attributes.ScriptPath), Path.Combine(outputDirectory, fileNameOnly));
                            scripts.Add(fileNameOnly);
                        }
                    }
                }
            }

            return(scripts);
        }
Exemplo n.º 5
0
        private void InitializeRealTestBench()
        {
            var torqueCell = new AnalogInputDevice(new ModbusServer());
            var servoDrive = new ServoDrive(new ModbusServer());

            TestBench.Initialize(torqueCell, servoDrive);
        }
 private List<Component> CollectGroundNodes(TestBench obj)
 {
     var gnds = obj.TestComponents.Where(t =>
         Grounds.Any(GetSpiceType(t).Item2.Contains)
         ).ToList();
     var cgnds = obj.ComponentAssemblies.SelectMany(ca => CollectGroundNodes(ca)).ToList();
     return gnds.Union(cgnds).ToList();
 }
Exemplo n.º 7
0
        private void InitializeSimulatedTestBench(TestType testType)
        {
            // get the behavior for the simulators, based on test type.
            var engine     = new SimulatorEngine(new Stopwatch());
            var torqueCell = new SimulatedTorqueCell(engine);
            var servoDrive = new SimulatedServoDrive(engine);

            TestBench.Initialize(torqueCell, servoDrive);
        }
Exemplo n.º 8
0
 public void Setup()
 {
     m_relayFixture = TestBench.GetRelayCrossConnectFixture();
     m_relayFixture.Setup();
     if (s_table != null)
     {
         m_relayFixture.GetRelay().InitTable(s_table);
     }
 }
Exemplo n.º 9
0
        public Task MoveTestBenchAsync(TestBench testBench, string oldName)
        {
            var oldFileName = Path.Combine(TestBenchPath, oldName + ".json");
            var newFileName = Path.Combine(TestBenchPath, testBench.Name + ".json");

            var oldScreenshotName = Path.Combine(TestBenchPath, oldName + ".png");
            var newScreenshotName = Path.Combine(TestBenchPath, testBench.Name + ".png");

            File.Move(oldFileName, newFileName);
            File.Move(oldScreenshotName, newScreenshotName);

            return(Task.FromResult(true));
        }
Exemplo n.º 10
0
        public Task SaveTestBenchAsync(TestBench testBench)
        {
            var outJson = JsonConvert.SerializeObject(testBench, Formatting.Indented,
                                                      new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            var filename = Path.Combine(TestBenchPath, testBench.Name + ".json");

            Console.WriteLine(filename);
            File.WriteAllText(filename, outJson);

            return(Task.FromResult(true));
        }
 /// <summary>
 /// Gets an epilog string with an sc_start() function call.
 /// </summary>
 /// <param name="obj">The testbench object possibly containing a "simulationTime" parameter.</param>
 /// <returns>A string containing an sc_start function call, with a time-limit parameter.</returns>
 /// <seealso>MOT-516: Modify CyPhy2SystemC interpreter to actually use the "simulationTime" parameter.
 public string getScStartString(TestBench obj)
 {
     string rVal = "\tsc_start();\n";
     string timeLimitParamName = "simulationTime";
     double number = 0;
     string scTimeUnitsString = "SC_SEC";
     try
     {
         if ( obj.TestParameters.ContainsKey( timeLimitParamName ) )
         {
             number = Double.Parse( obj.TestParameters[ timeLimitParamName ].Attributes.Value );
             switch (obj.TestParameters[timeLimitParamName].AllReferred.Name)
             {
                 // As of 2014, the smallest time unit in GME's QUDT unit library is the Microsecond.
                 case "Femptosecond":
                     scTimeUnitsString = "SC_FS";
                     break;
                 case "Picosecond":
                     scTimeUnitsString = "SC_PS";
                     break;
                 case "Nanosecond":
                     scTimeUnitsString = "SC_NS";
                     break;
                 case "Microsecond":
                     scTimeUnitsString = "SC_US";
                     break;
                 case "Millisecond":
                     scTimeUnitsString = "SC_MS";
                     break;
                 case "Second":
                     scTimeUnitsString = "SC_SEC";
                     break;
                 default:
                     scTimeUnitsString = "SC_SEC";
                     break;
             }   
         }
         rVal = String.Format("\tsc_start( {0}, {1} );\n", number, scTimeUnitsString);
     }
     catch
     {
         rVal = String.Format("\t// Unable to parse the {0} parameter.\n", timeLimitParamName) + rVal;
     }
     return rVal;
 }
Exemplo n.º 12
0
 private static void CopyCopyFiles(TestBench selectedTestBench, string projectDirectory, string outputDirectory)
 {
     foreach (var param in selectedTestBench.Children.ParameterCollection)
     {
         if (!param.AllDstConnections.Any() && !param.AllSrcConnections.Any())
         {
             if (param.Name == "CopyFile" && param.Attributes.Value != "")
             {
                 var fileNameOnly = Path.GetFileName(param.Attributes.Value);
                 if (fileNameOnly != null)
                 {
                     if (File.Exists(Path.Combine(outputDirectory, fileNameOnly)))
                     {
                         GMEConsole.Warning.WriteLine(
                             "Attempted to copy file {0} which already exists in output directory", fileNameOnly);
                     }
                     else
                     {
                         File.Copy(Path.Combine(projectDirectory, param.Attributes.Value), Path.Combine(outputDirectory, fileNameOnly));
                     }
                 }
             }
             else if (param.Name == "UserLibrary" && param.Attributes.Value != "")
             {
                 var fileNameOnly = Path.GetFileName(param.Attributes.Value);
                 if (fileNameOnly != null)
                 {
                     if (File.Exists(Path.Combine(outputDirectory, fileNameOnly)))
                     {
                         GMEConsole.Warning.WriteLine(
                             "Attempted to copy file {0} which already exists in output directory", fileNameOnly);
                     }
                     else
                     {
                         File.Copy(Path.Combine(projectDirectory, param.Attributes.Value), Path.Combine(outputDirectory, fileNameOnly));
                     }
                 }
             }
             else
             {
             }
         }
     }
 }
Exemplo n.º 13
0
        public async override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
        {
            base.PrepareForSegue(segue, sender);

            var dest         = (UINavigationController)segue.DestinationViewController;
            var tbController = (TestBenchViewController)dest.ViewControllers[0];

            if (segue.Identifier == "newTestBench")
            {
                tbController.ViewModel = new TestBenchViewModel(await TestBench.CreateDefaultAsync());
            }

            if (segue.Identifier == "editTestBench")
            {
                var name      = ViewModel.Items[CollectionView.GetIndexPathsForSelectedItems()[0].Row].TitleText;
                var testBench = await TestBench.CreateAsync(name);

                tbController.ViewModel = new TestBenchViewModel(testBench);
            }
        }
Exemplo n.º 14
0
        public SimulinkModel(TestBench testBench) : this()
        {
            //Iterate through TB to find blocks
            testBench.TraverseDFS(children => children, (child, i) =>
            {
                if (child is ISIS.GME.Dsml.CyPhyML.Interfaces.SimulinkModel)
                {
                    var block = SimulinkBlock.FromDomainModel((ISIS.GME.Dsml.CyPhyML.Interfaces.SimulinkModel)child);
                    if (block != null)
                    {
                        SimulinkGenerator.GMEConsole.Info.Write("Added block {0} ({1})", block.Name, block.BlockType);
                        Blocks.Add(block);
                    }
                }
            });

            foreach (var param in testBench.Children.ParameterCollection)
            {
                if (!param.AllDstConnections.Any() && !param.AllSrcConnections.Any())
                {
                    if (param.Name == "CopyFile")
                    {
                        //Ignore
                    }
                    else if (param.Name == "UserLibrary" && param.Attributes.Value != "")
                    {
                        var baseName = Path.GetFileNameWithoutExtension(param.Attributes.Value);

                        UserLibraries.Add(baseName);
                    }
                    else
                    {
                        if (param.Attributes.Value != "")
                        {
                            SimulationParams[param.Name] = param.Attributes.Value;
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
        public void ElapsedTimeCountsDownForMultipleTestConditions()
        {
            // initialize the simulated test bench
            var engine     = new SimulatorEngine(new Stopwatch());
            var torqueCell = new SimulatedTorqueCell(engine);
            var servoDrive = new SimulatedServoDrive(engine);

            TestBench.Initialize(torqueCell, servoDrive);

            // create a fatigue test and add a condition.
            var fatigueTest = new FatigueTest();

            engine.CurrentCondition = SingleFatigueTestCondition();
            fatigueTest.TestConditions.Add(engine.CurrentCondition);
            fatigueTest.TestConditions.AddRange(MultipleFatigueTestConditions());

            // load the test.
            TestBench.Singleton.LoadTest(fatigueTest);
            TestBench.Singleton.BeginCurrentTest();

            TimeSpan start = new TimeSpan(0, 0, 0);

            for (int i = 0; i < 1000; i++)
            {
                if (i == 0)
                {
                    start = fatigueTest.EstimatedCompletionTime;
                }
                torqueCell.RefreshTorque();
                servoDrive.StoreParameter(ServoDriveEnums.RegisterAddress.TorqueValue, (int)torqueCell.Torque);
                servoDrive.RefreshPosition();
                System.Threading.Thread.Sleep(10);
            }
            TimeSpan finish = fatigueTest.EstimatedCompletionTime;

            Console.WriteLine($"The estimated completion for the duty cycle is {finish.Days}:{finish.Hours}:{finish.Minutes}:{finish.Seconds}");
            var totalSeconds = start.Subtract(finish).TotalSeconds;

            Assert.GreaterOrEqual(totalSeconds, 10);
        }
        private void CommonTraversal(TestBench TestBench_obj)
        {
            // 1. A first traversal maps CyPhy objects to a corresponding but significantly lighter weight object network that only includes a 
            //     small set of concepts/classes : TestBench, ComponentAssembly, Component, Parameter, Port, Connection
            // 2. Second and third traversal passes compute the layout of the graph in schematic
            // 3. Forth traversal wires the object network
            //      the object network is hierarchical, but the wiring is direct and skips hierarchy. The dependency on CyPhy is largely localized to the 
            //      traversal/visitor code (CyPhyVisitors.cs)
            
            TestBench_obj.accept(new CyPhyBuildVisitor(this.mainParameters.ProjectDirectory, this.mode)
            {
                Logger = Logger
            });

            if (mode == Mode.EDA)
            {
                TestBench_obj.accept(new CyPhyLayoutVisitor() { Logger = Logger });
                TestBench_obj.accept(new CyPhyLayout2Visitor() { Logger = Logger });
            }

            TestBench_obj.accept(new CyPhyConnectVisitor(this.mode) { Logger = Logger });
        }
        public override void visit(TestBench obj)
        {
            Logger.WriteDebug("CyPhyBuildVisitor::visit({0})", obj.Impl.Path);

            var testBench = obj.Impl;
            var ca = testBench.Children.ComponentAssemblyCollection.FirstOrDefault();
            if (ca == null)
            {
                Logger.WriteFailed("No valid component assembly in testbench {0}", obj.Name);
                return;
            }
            var componentAssembly_obj = new ComponentAssembly(ca);
            obj.ComponentAssemblies.Add(componentAssembly_obj);

            var tcs = testBench.Children.TestComponentCollection;
            foreach (var tc in tcs)
            {
                var component_obj = new Component(tc);
                obj.TestComponents.Add(component_obj);
                CyPhyBuildVisitor.Components.Add(tc.ID, component_obj);   // Add to global component list, are these instance ID-s or component type ID-s?
            }

            foreach (var param in testBench.Children.ParameterCollection)
            {
                var param_obj = new Parameter()
                {
                    Name = param.Name,
                    Value = param.Attributes.Value
                };
                obj.Parameters.Add(param_obj);
            }

            // solver parameters - currently using Dymola Solver object
            var solver = testBench.Children.SolverSettingsCollection.FirstOrDefault();
            if (solver != null)
                obj.SolverParameters.Add("SpiceAnalysis", solver.Attributes.ToolSpecificAnnotations);
        }
        public Result GenerateCode()
        {
            Result result = new Result();

            // map the root testbench obj
            var testbench = TonkaClasses.TestBench.Cast(this.mainParameters.CurrentFCO);
            if (testbench == null)
            {
                Logger.WriteError("Invalid context of invocation <{0}>, invoke the interpreter from a Testbench model", 
                    this.mainParameters.CurrentFCO.Name);
                return result;
            }
            var TestBench_obj = new TestBench(testbench);
            BasePath = testbench.Path;

            CommonTraversal(TestBench_obj);

            GenerateReferenceDesignatorMappingTable(TestBench_obj);

            switch (mode)
            {
                case Mode.EDA:
                    var eagle = GenerateSchematicCode(TestBench_obj);
                    GenerateLayoutCode(eagle, TestBench_obj);
                    CopyBoardFiles(TestBench_obj);     // copy DRU/board template file if the testbench has it specified
                    GenerateChipFitCommandFile();
                    GenerateShowChipFitResultsCommandFile();
                    GeneratePlacementCommandFile();
                    GeneratePlaceOnlyCommandFile();
                    result.runCommandArgs = GenerateCommandArgs(TestBench_obj);
                    break;
                case Mode.SPICE_SI:
                    // parse and map the nets to ports
                    signalIntegrityLayout = new Layout.LayoutParser("layout.json", Logger)
                    {
                        mode = this.mode
                    };
                    signalIntegrityLayout.BuildMaps();

                    // spice code generator uses the mapped traces 
                    // to generate subcircuits for traces and inserts them appropriately
                    GenerateSpiceCode(TestBench_obj);
                    GenerateSpiceCommandFile(TestBench_obj);
                    break;
                case Mode.SPICE:
                    GenerateSpiceCode(TestBench_obj);
                    GenerateSpiceCommandFile(TestBench_obj);
                    GenerateSpiceViewerLauncher();
                    break;
                default:
                    throw new NotSupportedException(String.Format("Mode {0} is not supported", mode.ToString()));
            }

            return result;
        }
        private string GenerateCommandArgs(TestBench Testbench_obj)
        {
            string commandArgs = "";
            var icg = Testbench_obj.Parameters.Where(p => p.Name.Equals("interChipSpace")).FirstOrDefault();       // in mm
            var eg = Testbench_obj.Parameters.Where(p => p.Name.Equals("boardEdgeSpace")).FirstOrDefault();    // in mm

            if (icg != null)
            {
                commandArgs += " -i " + icg.Value;
            }
            if (eg != null)
            {
                commandArgs += " -e " + eg.Value;
            }

            return commandArgs;
        }
        private void CopyBoardFile(TestBench Testbench_obj, string param)
        {
            var par = Testbench_obj.Parameters.Where(p => p.Name.Equals(param)).FirstOrDefault();
            if (par == null)
                return;
            var pfn = par.Value; // check file name in par.value
            try
            {
                pfn = Path.GetFileName(par.Value);
            }
            catch (ArgumentException ex)
            {
                Logger.WriteError("Error extracting {0} filename: {1}", param, ex.Message);
                return;
            }

            var source = Path.Combine(this.mainParameters.ProjectDirectory, par.Value);
            var dest = Path.Combine(this.mainParameters.OutputDirectory, pfn);
            try
            {
                System.IO.File.Copy(source, dest);
            }
            catch (FileNotFoundException ex)
            {
                Logger.WriteError("Error copying {0} file: {1}", param, ex.Message);
            }
            catch (DirectoryNotFoundException ex2)
            {
                Logger.WriteError("Error copying {0} file: {1}", param, ex2.Message);
            }

        }
 private void CopyBoardFiles(TestBench Testbench_obj)
 {
     CopyBoardFile(Testbench_obj, "designRules");
     CopyBoardFile(Testbench_obj, "boardTemplate");
 }
Exemplo n.º 22
0
        public static TestBench Convert(ISIS.GME.Dsml.CyPhyML.Interfaces.TestBench tb)
        {
            if (tb == null)
            {
                throw new ArgumentNullException("tb");
            }

            // TODO: Generate ID
            //var componentConnectorTargetMapping = new Dictionary<CyPhy.Connector, ComponentConnectorInstance>();
            var componentConnectorTargetMapping = new Dictionary <CyPhy.Connector, object>();

            //var componentValueflowTargetMapping = new Dictionary<CyPhy.ValueFlowTarget, ContainerPrimitivePropertyInstance>();
            // Note: its is object because it contains: ContainerPrimitivePropertyInstance AND ComponentPrimitivePropertyInstance (TestComponent)
            var componentValueflowTargetMapping = new Dictionary <CyPhy.ValueFlowTarget, object>();

            var vftIdCache = new Dictionary <CyPhy.ValueFlowTarget, String>();

            var avmTestBench = new TestBench {
                Name = tb.Name
            };

            #region Process ComponentAssembly | DesignContainer

            var systemUnderTest = tb.Children.TopLevelSystemUnderTestCollection.FirstOrDefault();
            if (systemUnderTest != null && systemUnderTest.Referred != null)
            {
                var wrapper = new TestBenchPrimitiveWrapper(systemUnderTest.AllReferred);
                if (wrapper.Primitive != null)
                {
                    var avmTopLevelSystemUnderTest = new TopLevelSystemUnderTest()
                    {
                        // Note: DesignContainers have no ConfigurationUniqueID
                        DesignID = wrapper.ConfigurationUniqueID,

                        // TODO: Check if null
                        IDinSourceModel = wrapper.ID.ToString()
                    };

                    SetLayoutData(avmTopLevelSystemUnderTest, systemUnderTest.Impl);

                    #region Process TopLevelSystemUnderTest parameters

                    foreach (var parameter in wrapper.ParameterCollection)
                    {
                        DataTypeEnum xDataType;
                        if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType))
                        {
                            continue;
                        }

                        /*
                         * var avmPrimitivePropertyInstance = new ContainerPrimitivePropertyInstance()
                         * {
                         *  IDinSourceModel = parameter.Attributes.ID.ToString(),
                         *  Value = new Value
                         *      {
                         *          DataType = xDataType,
                         *          DataTypeSpecified = true,
                         *          DimensionType = DimensionTypeEnum.Scalar,
                         *          DimensionTypeSpecified = true,
                         *          Dimensions = parameter.Attributes.Dimension,
                         *          ID = Guid.NewGuid().ToString("D"),
                         *          //parameter.Guid.ToString("D")
                         *      }
                         * };
                         *
                         * //SetLayoutData(avmPrimitivePropertyInstance, parameter.Impl);
                         *
                         * componentValueflowTargetMapping[parameter] = avmPrimitivePropertyInstance;
                         * vftIdCache[parameter] = avmPrimitivePropertyInstance.Value.ID;
                         * avmTopLevelSystemUnderTest.PropertyInstance.Add(avmPrimitivePropertyInstance);
                         */
                    }

                    #endregion

                    #region Process TopLevelSystemUnderTest properties

                    foreach (var property in wrapper.PropertyCollection)
                    {
                        DataTypeEnum xDataType;
                        if (!ConvertCyPhyDataTypeEnum(property.Attributes.DataType, out xDataType))
                        {
                            continue;
                        }

                        /*
                         * var avmPrimitivePropertyInstance = new ContainerPrimitivePropertyInstance()
                         * {
                         *  IDinSourceModel = property.Attributes.ID.ToString(),
                         *  Value = new Value
                         *  {
                         *      DataType = xDataType,
                         *      DataTypeSpecified = true,
                         *      DimensionType = DimensionTypeEnum.Scalar,
                         *      DimensionTypeSpecified = true,
                         *      Dimensions = property.Attributes.Dimension,
                         *      ID = Guid.NewGuid().ToString("D"), //property.Guid.ToString("D")
                         *  }
                         * };
                         *
                         * //SetLayoutData(avmPrimitivePropertyInstance, property.Impl);
                         *
                         * avmTopLevelSystemUnderTest.PropertyInstance.Add(avmPrimitivePropertyInstance);
                         * componentValueflowTargetMapping[property] = avmPrimitivePropertyInstance;
                         * vftIdCache[property] = avmPrimitivePropertyInstance.Value.ID;
                         */
                    }

                    #endregion

                    #region Process TopLevelSystemUnderTest ModelicaConnector


                    foreach (var mc in wrapper.ModelicaConnectorCollection)
                    {
                        /*
                         * var avmPortInstance = new ContainerPortInstance
                         * {
                         *  ID = string.IsNullOrEmpty(mc.Attributes.ID) ? GetOrSetID(mc) : mc.Attributes.ID,
                         *  NameInSourceModel = mc.Name,
                         * };
                         *
                         * modelicaConnectorCache[mc] = avmPortInstance;
                         * avmTopLevelSystemUnderTest.PortInstance.Add(avmPortInstance);
                         */
                    }

                    #endregion

                    // TODO: Temprary solution for Zsolt no difference between ModelicaConnector and Connector in the atm file.
                    // => Impossible to import
                    #region Process TopLevelSystemUnderTest Connectors

                    foreach (var cc in wrapper.ConnectorCollection)
                    {
                        // Now it is ContainerPortInstance => Should be changed in the future.

                        /*
                         * var avmPortInstance = new ContainerPortInstance
                         * {
                         *  ID = EnsureComponentIdAttribute(cc),
                         *  NameInSourceModel = cc.Name,
                         * };
                         *
                         * componentConnectorTargetMapping[cc] = avmPortInstance;
                         * avmTopLevelSystemUnderTest.PortInstance.Add(avmPortInstance);
                         */
                    }

                    #endregion

                    avmTestBench.TopLevelSystemUnderTest = avmTopLevelSystemUnderTest;
                }
            }


            #endregion

            #region Process TestComponents

            foreach (var testComponent in tb.Children.TestComponentCollection)
            {
                var avmComponentInstance = new avm.ComponentInstance()
                {
                    Name        = testComponent.Name,
                    ID          = EnsureComponentIdAttribute(testComponent).ToString(),
                    ComponentID = testComponent.Guid.ToString("D")
                };

                #region Component connectors

                foreach (var connector in testComponent.Children.ConnectorCollection)
                {
                    var connectorId = EnsureComponentIdAttribute(connector);
                    var avmComponentConnectorInstance = new avm.ComponentConnectorInstance
                    {
                        IDinComponentModel = connector.Attributes.ID,
                        ID = avmComponentInstance.ID + '-' + connectorId,
                    };

                    avmComponentInstance.ConnectorInstance.Add(avmComponentConnectorInstance);

                    if (!componentConnectorTargetMapping.ContainsKey(connector))
                    {
                        componentConnectorTargetMapping[connector] = avmComponentConnectorInstance;
                    }
                }

                #endregion

                #region Process testComponent parameters

                foreach (var parameter in testComponent.Children.ParameterCollection)
                {
                    DataTypeEnum xDataType;
                    if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType))
                    {
                        continue;
                    }

                    var avmPrimitivePropertyInstance = new ComponentPrimitivePropertyInstance()
                    {
                        IDinComponentModel = parameter.Attributes.ID.ToString(),
                        Value = new Value
                        {
                            DataType               = xDataType,
                            DataTypeSpecified      = true,
                            DimensionType          = DimensionTypeEnum.Scalar,
                            DimensionTypeSpecified = true,
                            Dimensions             = parameter.Attributes.Dimension,
                            ID = Guid.NewGuid().ToString("D"),
                            //parameter.Guid.ToString("D")
                        }
                    };

                    //SetLayoutData(avmPrimitivePropertyInstance, parameter.Impl);

                    componentValueflowTargetMapping[parameter] = avmPrimitivePropertyInstance;
                    vftIdCache[parameter] = avmPrimitivePropertyInstance.Value.ID;
                    avmComponentInstance.PrimitivePropertyInstance.Add(avmPrimitivePropertyInstance);
                }

                #endregion

                #region Process testComponent properties

                foreach (var property in testComponent.Children.PropertyCollection)
                {
                    DataTypeEnum xDataType;
                    if (!ConvertCyPhyDataTypeEnum(property.Attributes.DataType, out xDataType))
                    {
                        continue;
                    }

                    var avmPrimitivePropertyInstance = new ComponentPrimitivePropertyInstance()
                    {
                        IDinComponentModel = property.Attributes.ID.ToString(),
                        Value = new Value
                        {
                            DataType               = xDataType,
                            DataTypeSpecified      = true,
                            DimensionType          = DimensionTypeEnum.Scalar,
                            DimensionTypeSpecified = true,
                            Dimensions             = property.Attributes.Dimension,
                            ID = Guid.NewGuid().ToString("D"), //property.Guid.ToString("D")
                        }
                    };

                    //SetLayoutData(avmPrimitivePropertyInstance, property.Impl);

                    avmComponentInstance.PrimitivePropertyInstance.Add(avmPrimitivePropertyInstance);
                    componentValueflowTargetMapping[property] = avmPrimitivePropertyInstance;
                    vftIdCache[property] = avmPrimitivePropertyInstance.Value.ID;
                }

                #endregion

                SetLayoutData(avmComponentInstance, testComponent.Impl);
                avmTestBench.TestComponent.Add(avmComponentInstance);
            }

            // TODO: not use dynamic, it is just a walkaround while Adam is on vacation
            #region Process ConnectorCompositions

            foreach (var cc in tb.Children.ConnectorCompositionCollection)
            {
                var src = cc.SrcEnds.Connector;
                var dst = cc.DstEnds.Connector;

                if (src != null && dst != null)
                {
                    dynamic avmSrc;
                    dynamic avmDst;
                    if (componentConnectorTargetMapping.ContainsKey(src) && componentConnectorTargetMapping.ContainsKey(dst))
                    {
                        avmSrc = componentConnectorTargetMapping[src];
                        avmDst = componentConnectorTargetMapping[dst];

                        try
                        {
                            avmSrc.ConnectorComposition.Add(avmDst.ID);
                        }
                        catch (RuntimeBinderException e)
                        {
                            avmSrc.PortMap.Add(avmDst.ID);
                        }
                    }
                }
            }

            #endregion

            #endregion

            #region Process Testbench parameters

            foreach (var parameter in tb.Children.ParameterCollection)
            {
                DataTypeEnum xDataType;
                if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType))
                {
                    continue;
                }

                var avmParameter = new Parameter
                {
                    ID    = parameter.Attributes.ID,
                    Name  = parameter.Name,
                    Notes = parameter.Attributes.Description,
                    Value = new Value
                    {
                        DataType               = xDataType,
                        DataTypeSpecified      = true,
                        DimensionType          = DimensionTypeEnum.Scalar,
                        DimensionTypeSpecified = true,
                        Dimensions             = parameter.Attributes.Dimension,
                        ID = Guid.NewGuid().ToString("D"),
                        //parameter.Guid.ToString("D")
                    }
                };

                SetLayoutData(avmParameter, parameter.Impl);

                #region Set value expressions / Derived values

                if (parameter.SrcConnections.ValueFlowCollection.Any())
                {
                    var vft = parameter.SrcConnections.ValueFlowCollection.First().SrcEnds.ValueFlowTarget;

                    String idVft = null;
                    // ContainerPrimitivePropertyInstance cppi = null;
                    dynamic cppi;
                    if (componentValueflowTargetMapping.TryGetValue(vft, out cppi))
                    {
                        idVft = cppi.Value.ID;
                    }
                    else
                    {
                        //idVft = GetOrSetID(vft);
                    }

                    avmParameter.Value.ValueExpression = new DerivedValue {
                        ValueSource = idVft
                    };
                }
                else
                {
                    // FixedValue or ParametricValue????
                    //var avmFixedValue = new FixedValue() {
                    //    Value = parameter.Attributes.Value
                    //};

                    var rangeParts = (parameter.Attributes.Range == null || !parameter.Attributes.Range.Contains("..")) ?
                                     new[] { "", "" } :
                    parameter.Attributes.Range.Split(new[] { ".." }, StringSplitOptions.RemoveEmptyEntries);

                    if (rangeParts.Count() != 2)
                    {
                        rangeParts = new[] { "", "" }
                    }
                    ;

                    var avmParametricValue = new ParametricValue
                    {
                        AssignedValue = new FixedValue {
                            Value = parameter.Attributes.Value
                        },
                        Default = new FixedValue {
                            Value = parameter.Attributes.DefaultValue
                        },
                        Maximum = new FixedValue {
                            Value = rangeParts[1]
                        },
                        Minimum = new FixedValue {
                            Value = rangeParts[0]
                        },
                    };

                    avmParameter.Value.ValueExpression = avmParametricValue;
                    vftIdCache[parameter] = avmParameter.Value.ID;
                }

                #endregion

                avmTestBench.Parameter.Add(avmParameter);
            }

            #endregion

            #region Process Testbench metrics

            foreach (var metric in tb.Children.MetricCollection)
            {
                var avmMetric = new Metric
                {
                    Name  = metric.Name,
                    Notes = metric.Attributes.Description
                };

                SetLayoutData(avmMetric, metric.Impl);

                #region Derived values

                // Metric is derived only
                if (metric.SrcConnections.ValueFlowCollection.Any())
                {
                    var vft = metric.SrcConnections.ValueFlowCollection.First().SrcEnds.ValueFlowTarget;

                    String idVft = null;
                    // ContainerPrimitivePropertyInstance cppi = null;
                    dynamic cppi;
                    if (componentValueflowTargetMapping.TryGetValue(vft, out cppi))
                    {
                        idVft = cppi.Value.ID;
                    }
                    else
                    {
                        //idVft = GetOrSetID(vft);
                    }

                    avmMetric.Value.ValueExpression = new DerivedValue {
                        ValueSource = idVft
                    };
                }

                #endregion

                avmTestBench.Metric.Add(avmMetric);
            }

            #endregion

            #region Process Testbench Environments (modelica models)

            foreach (var env in tb.Children.EnvironmentCollection)
            {
                var avmModelicaModel = new avm.modelica.ModelicaModel
                {
                    Name         = env.Name,
                    Author       = env.Attributes.Author,
                    Class        = env.Attributes.Class,
                    Notes        = env.Attributes.Notes,
                    UsesResource = env.Attributes.FilePathWithinResource,
                };

                #region Process modelica connectors

                foreach (var mc in env.Children.ModelicaConnectorCollection)
                {
                    var avmModelicaConnector = new avm.modelica.Connector
                    {
                        Name       = mc.Name,
                        Class      = mc.Attributes.Class,
                        Definition = mc.Attributes.Definition,
                        Notes      = mc.Attributes.DefinitionNotes,
                        ID         = string.IsNullOrEmpty(mc.Attributes.ID) ? GetOrSetID(mc) : mc.Attributes.ID,
                        //= mc.Attributes.InstanceNotes,
                        Locator = mc.Attributes.Locator,
                    };

                    avmModelicaModel.Connector.Add(avmModelicaConnector);
                    SetLayoutData(avmModelicaConnector, mc.Impl);
                }

                #endregion

                avmTestBench.TestStructure.Add(avmModelicaModel);
                SetLayoutData(avmModelicaModel, env.Impl);
            }

            #endregion

            #region Process Valueflows/set valueexpressions

            // Note: dynamic because of the Testcomponent Properties/Parameters
            foreach (var vf in tb.Children.ValueFlowCollection)
            {
                var srcValueFlow = vf.SrcEnds.ValueFlowTarget;
                var dstValueFlow = vf.DstEnds.ValueFlowTarget;

                if (componentValueflowTargetMapping.ContainsKey(dstValueFlow))
                {
                    dynamic dstPair = componentValueflowTargetMapping[dstValueFlow];
                    dstPair.Value.ValueExpression = new avm.DerivedValue
                    {
                        ValueSource = vftIdCache[srcValueFlow]
                    };
                }
            }

            #endregion

            #region Process PortCompositions

            foreach (var pc in tb.Children.PortCompositionCollection)
            {
                var src = pc.SrcEnds.ModelicaConnector;
                var dst = pc.DstEnds.ModelicaConnector;

                /*
                 * if (src != null & dst != null)
                 * {
                 *  ContainerPortInstance avmSrc;
                 *  ContainerPortInstance avmDst;
                 *  if (modelicaConnectorCache.ContainsKey(src))
                 *  {
                 *      avmSrc = modelicaConnectorCache[src];
                 *      avmSrc.PortMap.Add(dst.Attributes.ID);
                 *  }
                 *  else if (modelicaConnectorCache.ContainsKey(dst))
                 *  {
                 *      avmDst = modelicaConnectorCache[dst];
                 *      avmDst.PortMap.Add(src.Attributes.ID);
                 *  }
                 * }
                 */
            }

            #endregion

            #region Process Workflows

            var workflowRef = tb.Children.WorkflowRefCollection.FirstOrDefault();

            if (workflowRef != null)
            {
                var referred = workflowRef.Referred;
                if (referred != null && referred != null)
                {
                    var workflow = referred.Workflow;

                    var avmWorkflow = new Workflow
                    {
                        Name = workflow.Name,
                    };

                    avmTestBench.Workflow = avmWorkflow;
                    SetLayoutData(avmWorkflow, workflowRef.Impl);

                    var allTasks = workflow.Children.TaskBaseCollection.ToList();

                    // Get the first task
                    var currentTask = allTasks.FirstOrDefault(x => !x.SrcConnections.FlowCollection.Any());
                    if (currentTask != null)
                    {
                        do
                        {
                            // Create avm workflow tasks
                            if (currentTask is CyPhy.Task)
                            {
                                var cyphyTask = (CyPhy.Task)currentTask;
                                var avmTask   = new InterpreterTask
                                {
                                    Name       = cyphyTask.Name,
                                    COMName    = cyphyTask.Attributes.COMName,
                                    Parameters = cyphyTask.Attributes.Parameters
                                };

                                avmWorkflow.Task.Add(avmTask);
                                SetLayoutData(avmTask, cyphyTask.Impl);
                            }
                            else if (currentTask is CyPhy.ExecutionTask)
                            {
                                var cyphyTask = (CyPhy.ExecutionTask)currentTask;
                                var avmTask   = new ExecutionTask
                                {
                                    Name        = cyphyTask.Name,
                                    Description = cyphyTask.Attributes.Description,
                                    Invocation  = cyphyTask.Attributes.Invocation,
                                    //TODO: Ask adam about these:
                                    // = cyphyTask.Attributes.Parameters
                                    // = cyphyTask.Attributes.PostProcess
                                    // = cyphyTask.Attributes.PreProcess
                                };

                                SetLayoutData(avmTask, cyphyTask.Impl);
                                avmWorkflow.Task.Add(avmTask);
                            }
                            else
                            {
                                // ToDo: Give a warning
                                break;
                            }

                            // Next edge
                            var nextFlow = currentTask.DstConnections.FlowCollection.FirstOrDefault();

                            // No more outgoing edge
                            if (nextFlow == null)
                            {
                                break;
                            }
                            currentTask = nextFlow.DstEnds.TaskBase;

                            // No element at the end of the edge
                            // ToDo: Give a warning
                        } while (currentTask != null);
                    }
                }
            }

            #endregion

            #region Process Settings

            foreach (var settings in tb.Children.SolverSettingsCollection)
            {
                var intervalMethod          = AvmModelicaIntervalMethodMapping.FirstOrDefault(x => x.Item1 == settings.Attributes.IntervalMethod);
                var jobManagerToolSelection = AvmModelicaJobManagerToolSelectionMapping.FirstOrDefault(x => x.Item1 == settings.Attributes.JobManagerToolSelection);

                var avmSettings = new avm.modelica.SolverSettings
                {
                    IntervalLength          = settings.Attributes.IntervalLength,
                    IntervalLengthSpecified = true,

                    // TODO: Give warning
                    IntervalMethod = intervalMethod != null?intervalMethod.Item2:avm.modelica.IntervalMethod.IntervalLength,

                    // TODO: Give warning
                    JobManagerToolSelection = jobManagerToolSelection != null?jobManagerToolSelection.Item2:avm.modelica.JobManagerToolSelection.Dymola_latest,

                    JobManagerToolSelectionSpecified = true,
                    NumberOfIntervals          = settings.Attributes.NumberOfIntervals,
                    NumberOfIntervalsSpecified = true,
                    Solver                  = settings.Attributes.Solver.ToString(),
                    StartTime               = settings.Attributes.StartTime,
                    StartTimeSpecified      = true,
                    StopTime                = settings.Attributes.StartTime,
                    StopTimeSpecified       = true,
                    Tolerance               = settings.Attributes.Tolerance,
                    ToleranceSpecified      = true,
                    ToolSpecificAnnotations = settings.Attributes.ToolSpecificAnnotations
                };

                avmTestBench.Settings.Add(avmSettings);
            }

            #endregion

            return(avmTestBench);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Starts the generation of modelica code. Only method invocation that is needed on an instance of this class.
        /// </summary>
        public void GenerateModelicaCode()
        {
            var project = this.MainParameters.Project;
            var testBench = CyPhyClasses.TestBench.Cast(this.MainParameters.CurrentFCO);
            this.fidelitySettings = GetFidelitySettingsFromTestBench(testBench);
            this.testBench_mo = new TestBench(testBench);
            this.TagComponentsAndComponentAssembliesWithIsDynamicModel();

            this.treeComponents = new Dictionary<string, Component>();

            var projectRootFolder = CyPhyClasses.RootFolder.GetRootFolder(project);
            this.BuildUpAllComponets(projectRootFolder);

            this.SolverSettings = new Modelica.SolverSettings(testBench.Children.SolverSettingsCollection.FirstOrDefault());
            this.testBench_mo.SolverSettings = this.SolverSettings;
            
            this.Logger.WriteDebug("Solver settings being used:");
            this.Logger.WriteDebug("- [Dymola] Solver: {0}", this.SolverSettings.DymolaSolver);
            this.Logger.WriteDebug("- [OpenModelica] Solver: {0}", this.SolverSettings.OpenModelicaSolver);
            this.Logger.WriteDebug("- Tool selection for JobManager: {0}", this.SolverSettings.ToolSelection);
            this.Logger.WriteDebug("- Start time: {0}", this.SolverSettings.StartTime);
            this.Logger.WriteDebug("- Stop time: {0}", this.SolverSettings.StopTime);

            this.BuildUpTestBench();

            this.WriteModelicaCode();
        }
        private void GenerateSpiceCommandFile(TestBench Testbench_obj)
        {
            var spiceBat = new StreamWriter(Path.Combine(this.mainParameters.OutputDirectory, "runspice.bat"));
            spiceBat.Write(CyPhy2Schematic.Properties.Resources.runspice);

            // find a voltage source test component
            var voltageSrc = Testbench_obj.Impl.Children
                                               .TestComponentCollection
                                               .FirstOrDefault(c => c.Children.SPICEModelCollection
                                                                              .Select(x => x.Attributes.Class)
                                                                              .Contains("V"));
            if (voltageSrc != null)
            {
                // add a call to spice post process
                spiceBat.Write("if exist \"schema.raw\" (\n");
                spiceBat.Write("\t\"%META_PATH%\\bin\\python27\\scripts\\python.exe\" -m SpiceVisualizer.post_process -m {0} schema.raw\n", voltageSrc.Name);
                spiceBat.Write(")\n");
            }
            spiceBat.Close();
        }
Exemplo n.º 25
0
        private void bgWorkerTCP_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //Status : 2 = End of Init; 3 = End of HARD.xml; 4 = End of EACB.xml; 5 = End of StartEqt
            TestBench testBench = (TestBench)e.UserState;

            if (testBench.ID == "PUP") Invoke(new Action(() => { myTB_PUP = testBench; }));
            if (testBench.ID == "VE1") Invoke(new Action(() => { myTB_VE1 = testBench; }));
            if (testBench.ID == "VIU") Invoke(new Action(() => { myTB_VIU = testBench; }));
            if (testBench.ID == "VC1") Invoke(new Action(() => { myTB_VC1 = testBench; }));
            if (testBench.ID == "VC2") Invoke(new Action(() => { myTB_VC2 = testBench; }));
            if (testBench.ID == "VI2") Invoke(new Action(() => { myTB_VI2 = testBench; }));
            if (testBench.ID == "VE2") Invoke(new Action(() => { myTB_VE2 = testBench; }));

            switch (e.ProgressPercentage)
            {
                case 0:
                    break;
                case 1:
                    Invoke(new Action(() => { testBench.labelConn.ForeColor = myColorGreen; }));
                    Invoke(new Action(() => { testBench.labelHard.ForeColor = myColorDefault; }));
                    Invoke(new Action(() => { testBench.labelEacb.ForeColor = myColorDefault; }));
                    Invoke(new Action(() => { testBench.labelStartEqt.ForeColor = myColorDefault; }));
                    Invoke(new Action(() => { testBench.labelgroupBox.ForeColor = myColorDefault; }));
                    Invoke(new Action(() => { testBench.buttonReconn.Enabled = false; }));
                    Invoke(new Action(() => { testBench.buttonReload.Enabled = false; }));
                    Invoke(new Action(() => { testBench.buttonReinit.Enabled = false; }));
                    break;
                case -1:
                    Invoke(new Action(() => { testBench.labelConn.ForeColor = myColorRed; }));
                    Update_RichTextBox(myColorRed, testBench.richtextbox, "## Probleme de connexion. Vérifier que TB_RP_Server est démarré sur le PC distant (" + testBench.IP + "). Utiliser le bouton 'Reconnexion' pour retenter, puis 'Reload XML'.");
                    Invoke(new Action(() => { testBench.buttonReconn.Enabled = true; }));
                    break;
                case 2 :
                    Invoke(new Action(() => { testBench.buttonReconn.Enabled = true; }));
                    Invoke(new Action(() => { testBench.buttonReload.Enabled = true; }));
                    break;
                case 3:
                    Invoke(new Action(() => { testBench.labelHard.ForeColor = myColorGreen; }));
                    break;
                case -3:
                    Invoke(new Action(() => { testBench.labelHard.ForeColor = myColorRed; }));
                    break;
                case 4:
                    Invoke(new Action(() => { testBench.labelEacb.ForeColor = myColorGreen; }));
                    Invoke(new Action(() => { testBench.labelStartEqt.ForeColor = myColorOrange; }));
                    break;
                case -4:
                    Invoke(new Action(() => { testBench.labelEacb.ForeColor = myColorRed; }));
                    break;
                case 5:
                    Invoke(new Action(() => { testBench.labelStartEqt.ForeColor = myColorGreen; }));
                    Invoke(new Action(() => { testBench.buttonReload.Enabled = true; }));
                    Update_RichTextBox(myColorGreen, testBench.richtextbox, "== Configuration terminée.");
                    Invoke(new Action(() => { testBench.labelgroupBox.ForeColor = myColorGreen; }));
                    break;
                case -5:
                    Invoke(new Action(() => { testBench.labelStartEqt.ForeColor = myColorRed; }));
                    Invoke(new Action(() => { testBench.buttonReload.Enabled = true; }));
                    break;
                default:
                    break;
            }
            if (e.ProgressPercentage < 0)
            {
                if (testBench.labelgroupBox.ForeColor != myColorRed) testBench.labelgroupBox.ForeColor = myColorRed;
            }
        }
        private void GenerateSpiceCode(TestBench TestBench_obj)
        {
            var circuit = new Spice.Circuit() { name = TestBench_obj.Name };
            var siginfo = new Spice.SignalContainer() { name = TestBench_obj.Name };
            // now traverse the object network with Spice Visitor to build the spice and siginfo object network
            TestBench_obj.accept(new SpiceVisitor() { circuit_obj = circuit, siginfo_obj = siginfo, mode = this.mode });
            String spiceFile = Path.Combine(this.mainParameters.OutputDirectory, "schema.cir");
            circuit.Serialize(spiceFile);
            String siginfoFile = Path.Combine(this.mainParameters.OutputDirectory, "siginfo.json");
            siginfo.Serialize(siginfoFile);

        }
        public override void visit(TestBench obj)
        {
            if (CodeGenerator.verbose) CodeGenerator.GMEConsole.Info.WriteLine("Generate TestBench: {0}", obj.Name);

            includeLines.AppendFormat("// TestBench generated by SystemC Composer from: {0} ({1})\n", obj.Impl.Impl.Project.ParadigmConnStr, obj.Name);
            includeLines.Append("// Copyright (c) 2014 MetaMorph, Inc.\n\n");
            includeLines.Append("#include <stdlib.h>\n");
            includeLines.Append("#include <time.h>\n");
            includeLines.Append("#include <systemc.h>\n\n");

            prologLines.Append("int sc_main(int argc, char *argv[]) {\n");

            traceLines.Append("\tsc_trace_file *vcd_log = sc_create_vcd_trace_file(\"SystemCTestBench\");\n");

            epilogLines.Append("\tsrand((unsigned int)(time(NULL) & 0xffffffff));\n");
            epilogLines.Append( getScStartString( obj ) );
            epilogLines.Append("\tsc_close_vcd_trace_file(vcd_log);\n\n");
            if (obj.TestComponents.Count == 1)
            {
                epilogLines.AppendFormat("\treturn i_{0}.error_cnt;\n", obj.TestComponents.FirstOrDefault().Name);
            }
            else
            {
                epilogLines.AppendFormat("\treturn 0; // More then one test component is used.\n");
            }
            epilogLines.Append("}\n");
        }
        private void GenerateReferenceDesignatorMappingTable(TestBench Testbench_obj)
        {
            using (var sw = new StreamWriter(Path.Combine(this.mainParameters.OutputDirectory, "reference_designator_mapping_table.html")))
            {

                // Get all nested assemblies using an interative approach.
                var assemblies = new List<ComponentAssembly>();
                assemblies.AddRange(Testbench_obj.ComponentAssemblies);
                for (int i = 0; i < assemblies.Count; i++ )
                {
                    var assembly = assemblies[i];
                    assemblies.AddRange(assembly.ComponentAssemblyInstances);
                }

                // Get all instances from everywhere.
                var componentInstances = assemblies.SelectMany(a => a.ComponentInstances).ToList();
                componentInstances.AddRange(Testbench_obj.TestComponents);

                // Build mapping table
                List<XrefItem> xrefTable = new List<XrefItem>();
                foreach (var ci in componentInstances)
                {
                    String path = ci.Impl.Path;
                    String refDes = ci.Name;
                    XrefItem row = new XrefItem() { ReferenceDesignator = refDes, GmePath = path };
                    xrefTable.Add(row);
                }

                // Convert it to HTML
                string html = Xref2Html.makeHtmlFile(
                    "",
                    xrefTable,
                    "");

                // Write mapping table to file
                sw.Write(html);
            }
        }
Exemplo n.º 29
0
 public static void SetUpBeforeClass()
 {
     s_analogIo = TestBench.GetAnalogCrossConnectFixture();
 }
        public void GenerateSystemCCode()
        {
            // map the root testbench obj
            var testbench = CyPhyClasses.TestBench.Cast(this.mainParameters.CurrentFCO);
            if (testbench == null)
            {
                GMEConsole.Error.WriteLine("Invalid context of invocation <{0}>, invoke the interpreter from a Testbench model", 
                    this.mainParameters.CurrentFCO.Name);
                return;
            }
            var TestBench_obj = new TestBench(testbench);
            BasePath = testbench.Path;

            // Notes: The interepreter works in two (and half) traversal passes
            // 1. A first traversal maps CyPhy objects to a corresponding but significantly lighter weight object network that only includes a 
            //     small set of concepts/classes : TestBench, ComponentAssembly, Component, Parameter, Port, Connection
            //     This traversal first builds the object network and then wires it up 
            //      the object network is hierarchical, but the wiring is direct and skips hierarchy. The dependency on CyPhy is largely localized to the 
            //      traversal/visitor code (CyPhyVisitors.cs)
            TestBench_obj.accept(new CyPhyBuildVisitor(this.mainParameters.ProjectDirectory));
            TestBench_obj.accept(new CyPhyConnectVisitor());

            // 2. The second traversal walks the lighter weight (largely CyPhy independent) object network and maps to the eagle XML object network
            //      the classes of this object network are automatically derived from the eagle XSD using the XSD2Code tool in the META repo
            //      an important step of this traversal is the routing which is implemented currently as a simple rats nest routing, but could be improved later
            //        the traversal and visitor code is localized in (SystemCTraversal.cs)
            var systemCVisitor = new SystemCVisitor(this.mainParameters.OutputDirectory);
            TestBench_obj.accept(systemCVisitor);

            // 2.5  Finally generate the source file (and project) based on the object graph

            // Unpack SystemC skeleton project and libraries
            try
            {
                var thisAssembly = System.Reflection.Assembly.GetExecutingAssembly();
                System.IO.Stream zipStream =
                    thisAssembly.GetManifestResourceStream("CyPhy2SystemC.SystemCTestBench.zip");
                ZipFile zip = ZipFile.Read(zipStream);
                zip.ExtractAll(this.mainParameters.OutputDirectory);

                string vcProjPath = Path.Combine(this.mainParameters.OutputDirectory, "SystemCTestBench.vcxproj");
                var vcProj = new Project(vcProjPath);

                // Find and copy additional sources into the project directory
                // Also add sources to the Visual Studio project file
                foreach (var source in systemCVisitor.Sources) {
                    if (source.Type == SourceFile.SourceType.Header) {
                        string incPath = Path.Combine("include", "TonkaSCLib", source.Path);
                        if (File.Exists(Path.Combine(this.mainParameters.OutputDirectory, source.Path)))
                        {
                            vcProj.AddItem("ClInclude", source.Path);
                        }
                        else if (File.Exists(Path.Combine(this.mainParameters.OutputDirectory, incPath))) {
                            vcProj.AddItem("ClInclude", incPath);
                        }
                        else if (File.Exists(Path.Combine(this.mainParameters.ProjectDirectory, source.Path)))
                        {
                            incPath = Path.Combine("include", source.Path);
                            string srcPath = Path.Combine(this.mainParameters.ProjectDirectory, source.Path);
                            string dstPath = Path.Combine(this.mainParameters.OutputDirectory, incPath);
                            string dstDir = Path.GetDirectoryName(dstPath);
                            if (!Directory.Exists(dstDir))
                            {
                                Directory.CreateDirectory(dstDir);
                            }
                            File.Copy(srcPath, dstPath);


                            vcProj.AddItem("ClInclude", incPath);
                        }
                        else
                        {
                            GMEConsole.Error.WriteLine("Unable to find SystemC header file: " + source.Path);
                        }
                    }

                    if (source.Type == SourceFile.SourceType.Implemnation ||
                        source.Type == SourceFile.SourceType.Arduino)
                    {
                        Action addItem = delegate ()
                        {
                            if (source.Type == SourceFile.SourceType.Implemnation)
                            {
                                vcProj.AddItem("ClCompile", source.Path);
                            }
                            if (source.Type == SourceFile.SourceType.Arduino)
                            {
                                vcProj.AddItem("Arduino", source.Path);
                            }
                        };

                        string srcPath = Path.Combine(this.mainParameters.ProjectDirectory, source.Path);
                        string dstPath = Path.Combine(this.mainParameters.OutputDirectory, source.Path);
                        if (File.Exists(Path.Combine(this.mainParameters.OutputDirectory, dstPath)))
                        {
                            addItem();
                        }
                        else if (File.Exists(srcPath))
                        {
                            string dstDir = Path.GetDirectoryName(dstPath);
                            if (!Directory.Exists(dstDir))
                            {
                                Directory.CreateDirectory(dstDir);
                            }
                            File.Copy(srcPath, dstPath);

                            addItem();
                        }
                        else
                        {
                            GMEConsole.Error.WriteLine("Unable to find SystemC source file: " + source.Path);
                        }
                    }
                }

                vcProj.Save(vcProjPath);
                vcProj = null;

            }
            catch (Exception e)
            {
                GMEConsole.Error.WriteLine("Unable to extract SystemC libraries and template project: " + e.Message + "<br>Inner: " + e.InnerException + "<br>Stack: " + e.StackTrace);
            }


            System.IO.Directory.CreateDirectory(this.mainParameters.OutputDirectory);
            String outFile = this.mainParameters.OutputDirectory + "/test_main.cpp";
            try
            {
                systemCVisitor.WriteFile(outFile);
            }
            catch (Exception ex)
            {
                GMEConsole.Error.WriteLine("Error generating SystemC source code: " + outFile + "<br> Exception: " + ex.Message + "<br> Trace: " + ex.StackTrace);
            }
        }
        private Eagle.eagle GenerateSchematicCode(TestBench TestBench_obj)
        {
            // load schematic library
            Eagle.eagle eagle = null;
            try
            {
                eagle = Eagle.eagle.Deserialize(CyPhy2Schematic.Properties.Resources.schematicTemplate);
                Logger.WriteInfo("Parsed Eagle Library schema version: " + eagle.version);
            }
            catch (Exception e)
            {
                eagle = new Eagle.eagle();  // create an empty eagle object network
                Logger.WriteError("Error parsing XML: " + e.Message + "<br>Inner: " + e.InnerException + "<br>Stack: " + e.StackTrace);
            }
            // 2. The second traversal walks the lighter weight (largely CyPhy independent) object network and maps to the eagle XML object network
            //    the classes of this object network are automatically derived from the eagle XSD using the XSD2Code tool in the META repo
            //    an important step of this traversal is the routing which is implemented currently as a simple rats nest routing, 
            //        the traversal and visitor code is localized in (SchematicTraversal.cs)
            TestBench_obj.accept(new EdaVisitor() 
            { 
                eagle_obj = eagle, 
                Logger = Logger
            });

            // 2.5  Finally a serializer (XSD generated code), walks the object network and generates the XML file
            System.IO.Directory.CreateDirectory(this.mainParameters.OutputDirectory);
            String outFile = Path.Combine(this.mainParameters.OutputDirectory, "schema.sch");
            try
            {
                eagle.SaveToFile(outFile);
            }
            catch (Exception ex)
            {
                Logger.WriteError("Error Saving Schema File: {0}<br> Exception: {1}<br> Trace: {2}", 
                    outFile, ex.Message, ex.StackTrace);
            }

            return eagle;
        }
Exemplo n.º 32
0
 public virtual void upVisit(TestBench obj)
 {
 }
Exemplo n.º 33
0
 public void Setup()
 {
     m_analogIo  = TestBench.GetAnalogCrossConnectFixture();
     m_potSource = new FakePotentiometerSource(m_analogIo.GetOutput(), 360);
     m_pot       = new AnalogPotentiometer(m_analogIo.GetInput(), 360.0, 0);
 }
        public override void visit(TestBench obj)
        {
            if (obj.SolverParameters.ContainsKey("SpiceAnalysis"))
            {
                circuit_obj.analysis = obj.SolverParameters["SpiceAnalysis"];
            }
            var tracesParam = obj.Parameters.Where(p => p.Name.Equals("Traces")).FirstOrDefault();
            if (tracesParam != null)
                SigIntegrityTraces = tracesParam.Value.Split(new char[] { ' ', ',' });

            // process all ground nets first before they get assigned another number
            var gnds = CollectGroundNodes(obj);
            var gports = gnds.SelectMany(g => g.Ports).ToList();
            foreach (var gp in gports)
            {
                visit(gp, "0");
            }
        }
Exemplo n.º 35
0
        public LayoutGenerator(Eagle.schematic sch_obj, TestBench tb_obj, GMELogger inLogger)
        {
            this.Logger = inLogger;
            this.pkgPartMap = new Dictionary<Package, Eagle.part>();
            this.partPkgMap = new Dictionary<Eagle.part, Package>();
            this.preroutedPkgMap = new Dictionary<ComponentAssembly, Package>();

            boardLayout = new LayoutJson.Layout();
            var bw = tb_obj.Parameters.Where(p => p.Name.Equals("boardWidth")).FirstOrDefault();
            var bh = tb_obj.Parameters.Where(p => p.Name.Equals("boardHeight")).FirstOrDefault();

            try
            {
                boardLayout.boardWidth = (bw != null) ? Convert.ToDouble(bw.Value) : 40.0;
                boardLayout.boardHeight = (bh != null) ? Convert.ToDouble(bh.Value) : 40.0;
            }
            catch (FormatException ex)
            {
                Logger.WriteWarning("Exception while reading board dimensions: {0}", ex.Message);
            }
            boardLayout.numLayers = 2;
            {
                // Look to see if there is a PCB component in the top level assembly 
                var compImpl = tb_obj.ComponentAssemblies.SelectMany(c => c.ComponentInstances).Select(i => i.Impl)
                    .Where(j => (j as Tonka.Component).Attributes.Classifications
                        .Contains("pcb_board")).FirstOrDefault();
                // Look to see if it has a resource labeled 'BoardTemplate'
                var comp = (compImpl != null) ? compImpl as Tonka.Component : null;
                var btRes = (comp != null) ? comp.Children.ResourceCollection.Where(r =>
                    r.Name.ToUpper().Contains("BOARDTEMPLATE")).FirstOrDefault() : null;
                if (btRes != null)
                {
                    var btPath = Path.Combine(comp.Attributes.Path, btRes.Attributes.Path);
                    boardLayout.boardTemplate = Path.GetFileName(btPath);
                }
            }

            // the prior code looks up for a boardTemplate file associated with a PCB component
            // the users can override it with a boardTemplate file specified as a testbench parameter
            {
                var bt = tb_obj.Parameters.Where(p => p.Name.Equals("boardTemplate")).FirstOrDefault();
                // if its a file path - we only want to pass the file name to board synthesis
                if (bt != null)
                    try
                    {
                        boardLayout.boardTemplate = Path.GetFileName(bt.Value);
                    }
                    catch (System.ArgumentException ex)
                    {
                        CodeGenerator.Logger.WriteError("Error extracting boardTemplate filename: {0}", ex.Message);
                    }
            }
            // the users also can specify a designRule file as a testbench parameter
            {
                var dr = tb_obj.Parameters.Where(p => p.Name.Equals("designRules")).FirstOrDefault();
                if (dr != null)
                    try
                    {
                        boardLayout.designRules = Path.GetFileName(dr.Value);
                    }
                    catch (System.ArgumentException ex)
                    {
                        CodeGenerator.Logger.WriteError("Error extracting designRules filename: {0}", ex.Message);
                    }
            }

            boardLayout.packages = new List<Package>();
            int pkg_idx = 0;

            // we want to handle prerouted assemblies as follows
            // 1) all parts that are part of the pre-routed assembly are tagged with a 'virtual' spaceClaim part
            // 2) we add their absolute location (in the subckt frame of refernece) in the output json
            // 3) we create virtual spaceClaim parts for pre-routed subcircuits

            // 4) all nets belonging to the pre-routed subcircuit are tagged with the spaceClaim part
            // 5) these nets are added to json with absolute location (same as parts above)

            foreach (var ca in tb_obj.ComponentAssemblies)
            {
                pkg_idx = HandlePreRoutedAsm(ca, pkg_idx);
            }

            // compute part dimensions from 
            foreach (var part in sch_obj.parts.part)
            {
                var dev = sch_obj.libraries.library.Where(l => l.name.Equals(part.library)).
                    SelectMany(l => l.devicesets.deviceset).Where(ds => ds.name.Equals(part.deviceset)).
                    SelectMany(ds => ds.devices.device).Where(d => d.name.Equals(part.device)).FirstOrDefault();
                var spkg = (dev != null)
                           ? sch_obj.libraries.library.Where(l => l.name.Equals(part.library))
                                    .SelectMany(l => l.packages.package).Where(p => p.name.Equals(dev.package))
                                    .FirstOrDefault()
                           : null;

                Package pkg = new Package();
                pkg.name = part.name;
                pkg.pkg_idx = pkg_idx++;

                if (dev == null || spkg == null)
                {
                    // emit warning
                    Logger.WriteWarning("Unable to get package size for part - layout/chipfit results may be inaccurate: {0}", part.name);
                }
                else
                {
                    pkg.package = spkg.name;        // note that the eagle package information may be incomplete - should really have curated version from CyPhy

                    #region ComputePackageSize

                    var minX = Double.MaxValue;
                    var minY = Double.MaxValue;
                    var maxX = Double.MinValue;
                    var maxY = Double.MinValue;

                    foreach (Eagle.wire wire in spkg.Items.Where(s => s is Eagle.wire))
                    {
                        if (wire == null) continue;

                        if (!LayersForBoundingBoxComputation.Any(wire.layer.Contains))
                            continue;

                        var x1 = Convert.ToDouble(wire.x1);
                        var x2 = Convert.ToDouble(wire.x2);
                        var y1 = Convert.ToDouble(wire.y1);
                        var y2 = Convert.ToDouble(wire.y2);
                        if (x1 < minX) minX = x1;
                        if (x2 < minX) minX = x2;
                        if (x1 > maxX) maxX = x1;
                        if (x2 > maxX) maxX = x2;
                        if (y1 < minY) minY = y1;
                        if (y2 < minY) minY = y2;
                        if (y1 > maxY) maxY = y1;
                        if (y2 > maxY) maxY = y2;
                    }
                    foreach (Eagle.pad pad in spkg.Items.Where(s => s is Eagle.pad))
                    {
                        if (pad == null) continue;
                        var pad_num = pad.name;
                        var x = Convert.ToDouble(pad.x);
                        var y = Convert.ToDouble(pad.y);
                        var drill = Convert.ToDouble(pad.drill);
                        var dia = Convert.ToDouble(pad.diameter);
                        var shape = pad.shape;  // enum padShape {round, octagon, @long, offset}
                        var rot = pad.rot;      // { R90, R180, R270, ...}  
                        var r = 0.0;
                        if (dia == 0.0)  // JS: Workaround for no diameter present, estimate dia to be 2x drill size 
                        {
                            dia = drill * 2.0;
                        }

                        if (shape == Eagle.padShape.@long)
                        {
                            // TODO: consider PAD rotation; for now, consider long pads are 2x diameter.

                            dia *= 2.0;  // diameter value from package desc is for the "short" side, for max calc, consider long side is 2x (by inspection)
                        }
                        r = dia / 2.0;

                        if ((x - r) < minX) minX = x - r;
                        if ((x + r) > maxX) maxX = x + r;
                        if ((y - r) < minY) minY = y - r;
                        if ((y + r) > maxY) maxY = y + r;
                    }
                    foreach (Eagle.circle circle in spkg.Items.Where(s => s is Eagle.circle))
                    {
                        if (circle == null) continue;
                        var x = Convert.ToDouble(circle.x);
                        var y = Convert.ToDouble(circle.y);
                        var r = Convert.ToDouble(circle.radius);
                        if ((x - r) < minX) minX = x - r;
                        if ((x + r) > maxX) maxX = x + r;
                        if ((y - r) < minY) minY = y - r;
                        if ((y + r) > maxY) maxY = y + r;
                    }
                    foreach (Eagle.smd smd in spkg.Items.Where(s => s is Eagle.smd))
                    {
                        if (smd == null) continue;
                        // SKN: after intense research on eagle, it seems that the way SMD pads are placed is as follows
                        // dx - dy tells the length of the pad, while the x is the center point of the SMD pad

                        var x = Convert.ToDouble(smd.x);
                        var y = Convert.ToDouble(smd.y);
                        var ddx = Convert.ToDouble(smd.dx);
                        var ddy = Convert.ToDouble(smd.dy);
                        var dx = ddx;  // should be /2??
                        var dy = ddy;
                        if (smd.rot.Equals("R90") || smd.rot.Equals("R270"))
                        {       // flip dx and dy if there is rotation
                            dx = ddy;
                            dy = ddx;
                        }
                        var x1 = x - dx / 2.0;
                        var x2 = x + dx / 2.0;
                        var y1 = y - dy / 2.0;
                        var y2 = y + dy / 2.0;
                        if (x1 < minX) minX = x1;
                        if (x2 > maxX) maxX = x2;
                        if (y1 < minY) minY = y1;
                        if (y2 > maxY) maxY = y2;
                    }
                    pkg.width = maxX - minX;
                    pkg.height = maxY - minY;
                    pkg.originX = Math.Floor(10.0 * (maxX + minX) / 2.0) / 10.0;
                    pkg.originY = Math.Floor(10.0 * (maxY + minY) / 2.0) / 10.0;

                    #endregion

                    // emit component ID for locating components in CAD assembly
                    if (CodeGenerator.partComponentMap.ContainsKey(part))
                    {
                        var comp_obj = CodeGenerator.partComponentMap[part];
                        var comp = comp_obj.Impl as Tonka.Component;

                        // emit component ID for locating components in CAD assembly
                        pkg.ComponentID = comp.Attributes.InstanceGUID;

                        Boolean isMultiLayer = comp.Children.EDAModelCollection.
                            Any(e => e.Attributes.HasMultiLayerFootprint);
                        if (isMultiLayer)
                            pkg.multiLayer = true;

                        #region ExactConstraints
                        // exact constraints related to this part
                        var exactCons =
                            from conn in comp.SrcConnections.ApplyExactLayoutConstraintCollection
                            select conn.SrcEnds.ExactLayoutConstraint;

                        foreach (var c in exactCons)
                        {
                            var pcons = new ExactConstraint();
                            pcons.type = "exact";
                            if (!c.Attributes.X.Equals(""))
                                pcons.x = Convert.ToDouble(c.Attributes.X);
                            if (!c.Attributes.Y.Equals(""))
                                pcons.y = Convert.ToDouble(c.Attributes.Y);
                            if (!c.Attributes.Layer.Equals(""))
                                pcons.layer = Convert.ToInt32(c.Attributes.Layer);
                            if (!c.Attributes.Rotation.Equals(""))
                                pcons.rotation = Convert.ToInt32(c.Attributes.Rotation);
                            if (pkg.constraints == null)
                                pkg.constraints = new List<Constraint>();
                            pkg.constraints.Add(pcons);
                        }
                        #endregion

                        #region RangeConstraints
                        // range constraints related to this part
                        var rangeCons =
                            from conn in comp.SrcConnections.ApplyRangeLayoutConstraintCollection
                            select conn.SrcEnds.RangeLayoutConstraint;
                        foreach (var c in rangeCons)
                        {
                            var pcons = new RangeConstraint();
                            pcons.type = "range";
                            if (!c.Attributes.XRange.Equals(""))
                                pcons.x = c.Attributes.XRange;
                            if (!c.Attributes.YRange.Equals(""))
                                pcons.y = c.Attributes.YRange;
                            if (!c.Attributes.LayerRange.Equals(""))
                                pcons.layer = c.Attributes.LayerRange;
                            if (pkg.constraints == null)
                                pkg.constraints = new List<Constraint>();
                            pkg.constraints.Add(pcons);
                        }
                        #endregion

                        #region PreRoutedAssemblyPart
                        // now handle if this component is part of a pre-routed sub-ckt
                        if (CodeGenerator.preRouted.ContainsKey(comp_obj.Parent))
                        {
                            var layoutParser = CodeGenerator.preRouted[comp_obj.Parent];
                            var prePkg = layoutParser.componentPackageMap[comp_obj];
                            pkg.x = prePkg.x;
                            pkg.y = prePkg.y;
                            pkg.rotation = prePkg.rotation;
                            pkg.RelComponentID = (comp_obj.Parent.Impl.Impl as GME.MGA.MgaFCO)
                                .RegistryValue["Elaborator/InstanceGUID_Chain"];
                            pkg.doNotPlace = true;
                        }
                        #endregion
                    }
                }
                pkgPartMap.Add(pkg, part);  // add to map
                partPkgMap.Add(part, pkg);
                boardLayout.packages.Add(pkg);
            }



            #region AddSignalsToBoardLayout
            boardLayout.signals = new List<Signal>();
            foreach (var net in sch_obj.sheets.sheet.FirstOrDefault().nets.net)
            {
                // dump pre-routed signals to board file
                var sig = new Signal();
                sig.name = net.name;
                sig.pins = new List<Pin>();

                Signal preRouted = null;
                string preRoutedAsmID = null; // ID of the parent pre-routed assembly
                string preRoutedAsm = null; // name the parent pre-routed assembly
                bool onlyOnePreroute = true;

                foreach (var seg in net.segment.SelectMany(s => s.Items).Where(s => s is Eagle.pinref))
                {
                    bool isPrerouted = false;

                    var pr = seg as Eagle.pinref;
                    var pin = new Pin();
                    pin.name = pr.pin;
                    pin.gate = pr.gate;
                    pin.package = pr.part.ToUpper();

                    // find package and pad
                    var part = sch_obj.parts.part.Where(p => p.name.Equals(pr.part)).FirstOrDefault();

                    var dev = (part != null) ?
                        sch_obj.libraries.library.Where(l => l.name.Equals(part.library)).
                        SelectMany(l => l.devicesets.deviceset).Where(ds => ds.name.Equals(part.deviceset)).
                        SelectMany(ds => ds.devices.device).Where(d => d.name.Equals(part.device)).FirstOrDefault()
                        : null;
                    var pad = (dev != null) ?
                        dev.connects.connect.Where(c => c.gate.Equals(pr.gate) && c.pin.Equals(pr.pin)).Select(c => c.pad).FirstOrDefault()
                        : null;
                    if (pad != null)
                        pin.pad = pad;

                    // check for preroutes - all pins in this signal should be in the prerouted net, otherwise reject it
                    if (part != null && CodeGenerator.partComponentMap.ContainsKey(part))
                    {
                        var comp_obj = CodeGenerator.partComponentMap[part];
                        if (CodeGenerator.preRouted.ContainsKey(comp_obj.Parent)) // is the parent assembly prerouted
                        {
                            Logger.WriteDebug("Net {0} in Prerouted Asm {1}", net.name, comp_obj.Parent.Name);

                            var layoutParser = CodeGenerator.preRouted[comp_obj.Parent];
                            // find the name/gate matching port in schematic domain model
                            var sch = comp_obj.Impl.Children.SchematicModelCollection.FirstOrDefault();

                            var port = (sch != null) ?
                                sch.Children.SchematicModelPortCollection.
                                Where(p => p.Attributes.EDAGate == pin.gate && p.Name == pin.name).
                                FirstOrDefault()
                                : null;

                            // find the buildPort
                            var buildPort = port != null && CyPhyBuildVisitor.Ports.ContainsKey(port.ID) ?
                                CyPhyBuildVisitor.Ports[port.ID] : null;


                            if (buildPort != null && layoutParser.portTraceMap.ContainsKey(buildPort))
                            {
                                isPrerouted = true;
                                Logger.WriteDebug("Found build Port and Associated Trace");

                                if (preRouted == null)
                                {
                                    preRouted = layoutParser.portTraceMap[buildPort];
                                    preRoutedAsmID = (comp_obj.Parent.Impl.Impl as GME.MGA.MgaFCO)
                                        .RegistryValue["Elaborator/InstanceGUID_Chain"];
                                    preRoutedAsm = comp_obj.Parent.Name;
                                }
                                else if (preRouted != layoutParser.portTraceMap[buildPort])
                                    isPrerouted = false;
                            }
                        }
                    }

                    onlyOnePreroute = onlyOnePreroute && isPrerouted;

                    // add pin to list of pins for this signal
                    sig.pins.Add(pin);
                }

                // if pre-routed then copy wires 
                if (onlyOnePreroute && preRouted != null)
                {
                    Logger.WriteInfo("Prerouted net {0}, from assembly {1}, originally as {2}", net.name, preRoutedAsm, preRouted.name);
                    sig.wires = new List<Wire>();
                    sig.vias = new List<Via>();
                    sig.RelComponentID = preRoutedAsmID;
                    foreach (var w in preRouted.wires)
                        sig.wires.Add(w);
                    foreach (var v in preRouted.vias)
                        sig.vias.Add(v);
                }

                boardLayout.signals.Add(sig);
            }
            #endregion

            #region AddRelativeConstraintsToBoardLayout
            // now process relative constraints - they require that all parts be mapped to packages already
            for (int i = 0; i < boardLayout.packages.Count; i++)
            {
                var pkg = boardLayout.packages[i];
                if (!pkgPartMap.ContainsKey(pkg))
                    continue;

                var part = pkgPartMap[pkg];
                var comp = CodeGenerator.partComponentMap.ContainsKey(part) ?
                    CodeGenerator.partComponentMap[part] : null;
                var impl = comp != null ? comp.Impl as Tonka.Component : null;
                var relCons =
                    from conn in impl.SrcConnections.ApplyRelativeLayoutConstraintCollection
                    select conn.SrcEnds.RelativeLayoutConstraint;

                foreach (var c in relCons)
                {
                    var pcons = new RelativeConstraint();
                    pcons.type = "relative-pkg";
                    if (!c.Attributes.XOffset.Equals(""))
                        pcons.x = Convert.ToDouble(c.Attributes.XOffset);
                    if (!c.Attributes.YOffset.Equals(""))
                        pcons.y = Convert.ToDouble(c.Attributes.YOffset);
                    // find origin comp
                    var origCompImpl = (from conn in c.SrcConnections.RelativeLayoutConstraintOriginCollection
                                        select conn.SrcEnds.Component).FirstOrDefault();
                    var origComp =
                        ((origCompImpl != null) && CyPhyBuildVisitor.Components.ContainsKey(origCompImpl.ID)) ?
                        CyPhyBuildVisitor.Components[origCompImpl.ID] :
                        null;
                    var origPart =
                        ((origComp != null) && CodeGenerator.componentPartMap.ContainsKey(origComp)) ?
                        CodeGenerator.componentPartMap[origComp] :
                        null;
                    var origPkg = ((origPart != null) && partPkgMap.ContainsKey(origPart)) ?
                        partPkgMap[origPart] :
                        null;
                    pcons.pkg_idx = origPkg.pkg_idx.Value;
                    if (pkg.constraints == null)
                        pkg.constraints = new List<Constraint>();
                    pkg.constraints.Add(pcons);
                    boardLayout.packages[i] = pkg;
                }

            }
            #endregion

        }
 public override void visit(TestBench obj)
 {
     // Create a sheet for the testbench
     var sheet_obj = new Eagle.sheet();
     schematic_obj.sheets.sheet.Add(sheet_obj);
 }