Exemple #1
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);
        }
        public static CyPhy.TestBenchType Convert(avm.TestBench avmTestBench, IMgaProject project)
        {
            if (avmTestBench == null)
            {
                throw new ArgumentNullException("avmTestBench");
            }

            var rootFolder      = CyPhyClasses.RootFolder.GetRootFolder((MgaProject)project);
            var testBenchFolder = rootFolder.Children.TestingCollection.Where(d => d.Name == "TestBenches").FirstOrDefault();

            #region Create TestBenchesFolder

            if (testBenchFolder == null)
            {
                testBenchFolder      = CyPhyClasses.Testing.Create(rootFolder);
                testBenchFolder.Name = "TestBenches";
            }

            #endregion

            #region Create TestBench

            var cyphyTestBench = CyPhyClasses.TestBench.Create(testBenchFolder);
            cyphyTestBench.Name = avmTestBench.Name;


            #endregion

            #region Create TopLevelSystemUnderTest

            var avmSystemUnderTest = avmTestBench.TopLevelSystemUnderTest;
            CyPhy.TopLevelSystemUnderTest cyphySystemUnderTest         = null;
            TestBenchPrimitiveWrapper     cyphySystemUnderTestReferred = null;
            if (avmSystemUnderTest != null)
            {
                cyphySystemUnderTest = CyPhyClasses.TopLevelSystemUnderTest.Create(cyphyTestBench);
                SetLayoutData(avmSystemUnderTest, cyphySystemUnderTest.Impl);
                if (!string.IsNullOrEmpty(avmSystemUnderTest.DesignID))
                {
                    // Looking for the referred component assembly
                    var allComponentAssembly = GetAllComponentAssemblies(rootFolder.Children.ComponentAssembliesCollection);
                    var componentAssembly    = allComponentAssembly.FirstOrDefault(x => x.Attributes.ConfigurationUniqueID == avmSystemUnderTest.DesignID);
                    if (componentAssembly != null)
                    {
                        cyphySystemUnderTest.GenericReferred = componentAssembly;
                        cyphySystemUnderTest.Name            = componentAssembly.Name;
                        cyphySystemUnderTestReferred         = new TestBenchPrimitiveWrapper(componentAssembly);
                    }
                }
            }

            #endregion

            #region Create Parameters

            var parameterCache = new List <Tuple <avm.Parameter, CyPhy.Parameter> >();
            foreach (var avmParameter in avmTestBench.Parameter)
            {
                var cyphyTestBenchParameter = CyPhyClasses.Parameter.Create(cyphyTestBench);
                cyphyTestBenchParameter.Name = avmParameter.Name;
                cyphyTestBenchParameter.Attributes.Description = avmParameter.Notes;
                cyphyTestBenchParameter.Attributes.ID          = avmParameter.ID;
                SetLayoutData(avmParameter, cyphyTestBenchParameter.Impl);

                parameterCache.Add(new Tuple <avm.Parameter, CyPhy.Parameter>(avmParameter, cyphyTestBenchParameter));

                #region Set attribute values

                var avmValue = avmParameter.Value;
                if (avmValue != null)
                {
                    CyPhyClasses.Parameter.AttributesClass.DataType_enum cyphyDataType;

                    // TODO: else give a warning
                    if (ConvertCyPhyDataTypeEnum(avmValue.DataType, out cyphyDataType))
                    {
                        cyphyTestBenchParameter.Attributes.DataType = cyphyDataType;
                    }

                    cyphyTestBenchParameter.Attributes.Dimension = avmValue.Dimensions;

                    var avmValueExpression = avmValue.ValueExpression;
                    if (avmValueExpression != null && avmValueExpression is avm.ParametricValue)
                    {
                        var avmParametricValue = (avm.ParametricValue)avmValueExpression;

                        var avmAssignedValue = avmParametricValue.AssignedValue as FixedValue;
                        var avmDefault       = avmParametricValue.Default as FixedValue;
                        var avmMaximum       = avmParametricValue.Maximum as FixedValue;
                        var avmMinimum       = avmParametricValue.Minimum as FixedValue;

                        if (avmAssignedValue != null && avmAssignedValue.Value != null)
                        {
                            cyphyTestBenchParameter.Attributes.Value = avmAssignedValue.Value;
                        }
                        if (avmDefault != null && avmDefault.Value != null)
                        {
                            cyphyTestBenchParameter.Attributes.DefaultValue = avmDefault.Value;
                        }

                        if (avmMinimum != null && !string.IsNullOrEmpty(avmMinimum.Value) && avmMaximum != null && !string.IsNullOrEmpty(avmMaximum.Value))
                        {
                            cyphyTestBenchParameter.Attributes.Range = String.Format("{0}..{1}", avmMinimum.Value, avmMaximum.Value);
                        }
                    }
                }

                #endregion
            }

            #endregion

            #region Create Metrics

            var metricCache = new List <Tuple <avm.Metric, CyPhy.Metric> >();
            foreach (var avmMetric in avmTestBench.Metric)
            {
                var cyphyTestBenchMetric = CyPhyClasses.Metric.Create(cyphyTestBench);

                cyphyTestBenchMetric.Name = avmMetric.Name;
                cyphyTestBenchMetric.Attributes.Description = avmMetric.Notes;
                SetLayoutData(avmMetric, cyphyTestBenchMetric.Impl);

                metricCache.Add(new Tuple <avm.Metric, CyPhy.Metric>(avmMetric, cyphyTestBenchMetric));
            }

            #endregion

            #region Create valueflows

            // Start with TopLevelSystemUnderTest
            if (avmSystemUnderTest != null && cyphySystemUnderTest != null)
            {
                /*
                 * // Parameters and properties
                 * foreach (var avmParameter in avmSystemUnderTest.PropertyInstance.Where(x=>x.Value!=null))
                 * {
                 *  // Target of valueflow
                 *  if (avmParameter.Value.ValueExpression is DerivedValue)
                 *  {
                 *      var derivedValue = (DerivedValue)avmParameter.Value.ValueExpression;
                 *      // Look for the parameter instance
                 *      dynamic cyphyValueflowSrc = cyphySystemUnderTestReferred.ParameterCollection.FirstOrDefault(x => x.Attributes.ID == avmParameter.IDinSourceModel);
                 *
                 *      // Maybe it is a property
                 *      if (cyphyValueflowSrc == null)
                 *      {
                 *          cyphyValueflowSrc = cyphySystemUnderTestReferred.PropertyCollection.FirstOrDefault(x => x.Attributes.ID == avmParameter.IDinSourceModel);
                 *      }
                 *
                 *      // TODO: Else warning
                 *      if (cyphyValueflowSrc != null)
                 *      {
                 *          var cachePair = parameterCache.FirstOrDefault(x=>x.Item1.Value.ID == derivedValue.ValueSource);
                 *          if (cachePair != null)
                 *          {
                 *              var cyphyValueflowDst = cachePair.Item2;
                 *              var srcRef = ((CyPhy.ValueFlowTarget)cyphyValueflowSrc).ParentContainer is CyPhyClasses.TestBench ? null : cyphySystemUnderTest;
                 *              var dstRef = ((CyPhy.ValueFlowTarget)cyphyValueflowDst).ParentContainer is CyPhyClasses.TestBench ? null : cyphySystemUnderTest;
                 *              // Doesnt work
                 *              CyPhyClasses.ValueFlow.Connect((CyPhy.ValueFlowTarget)cyphyValueflowSrc, (CyPhy.ValueFlowTarget)cyphyValueflowDst, srcRef, dstRef, cyphyTestBench);
                 *              //CyPhyClasses.ValueFlow.ConnectGeneric((CyPhy.ValueFlowTarget)cyphyValueflowDst, (CyPhy.ValueFlowTarget)cyphyValueflowSrc, null, null, cyphyTestBench);
                 *          }
                 *      }
                 *  }
                 * }
                 */
            }

            #endregion

            return(cyphyTestBench);
        }
        public static TestBench Convert(ISIS.GME.Dsml.CyPhyML.Interfaces.TestBench tb)
        {
            if (tb == null)
                throw new ArgumentNullException("tb");

            // TODO: Generate ID
            //var componentConnectorTargetMapping = new Dictionary<CyPhy.Connector, ComponentConnectorInstance>();
            var componentConnectorTargetMapping = new Dictionary<CyPhy.Connector, object>();
            
            //var componentValueflowTargetMapping = new Dictionary<CyPhy.ValueFlowTarget, ContainerPrimitivePropertyInstance>();
            // Note: its is object because it contains: ContainerPrimitivePropertyInstance AND ComponentPrimitivePropertyInstance (TestComponent)
            var componentValueflowTargetMapping = new Dictionary<CyPhy.ValueFlowTarget, object>();
            
            var vftIdCache = new Dictionary<CyPhy.ValueFlowTarget, String>();

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

            #region Process ComponentAssembly | DesignContainer

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

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

                    SetLayoutData(avmTopLevelSystemUnderTest, systemUnderTest.Impl);

                    #region Process TopLevelSystemUnderTest parameters

                    foreach (var parameter in wrapper.ParameterCollection)
                    {
                        DataTypeEnum xDataType;
                        if (!ConvertCyPhyDataTypeEnum(parameter.Attributes.DataType, out xDataType)) continue;
                        /*
                        var avmPrimitivePropertyInstance = new ContainerPrimitivePropertyInstance()
                        {
                            IDinSourceModel = parameter.Attributes.ID.ToString(),
                            Value = new Value
                                {
                                    DataType = xDataType,
                                    DataTypeSpecified = true,
                                    DimensionType = DimensionTypeEnum.Scalar,
                                    DimensionTypeSpecified = true,
                                    Dimensions = parameter.Attributes.Dimension,
                                    ID = Guid.NewGuid().ToString("D"),
                                    //parameter.Guid.ToString("D")
                                }
                        };

                        //SetLayoutData(avmPrimitivePropertyInstance, parameter.Impl);

                        componentValueflowTargetMapping[parameter] = avmPrimitivePropertyInstance;
                        vftIdCache[parameter] = avmPrimitivePropertyInstance.Value.ID;
                        avmTopLevelSystemUnderTest.PropertyInstance.Add(avmPrimitivePropertyInstance);
                        */
                    }

                    #endregion

                    #region Process TopLevelSystemUnderTest properties

                    foreach (var property in wrapper.PropertyCollection)
                    {
                        DataTypeEnum xDataType;
                        if (!ConvertCyPhyDataTypeEnum(property.Attributes.DataType, out xDataType)) continue;
                        /*
                        var avmPrimitivePropertyInstance = new ContainerPrimitivePropertyInstance()
                        {
                            IDinSourceModel = property.Attributes.ID.ToString(),
                            Value = new Value
                            {
                                DataType = xDataType,
                                DataTypeSpecified = true,
                                DimensionType = DimensionTypeEnum.Scalar,
                                DimensionTypeSpecified = true,
                                Dimensions = property.Attributes.Dimension,
                                ID = Guid.NewGuid().ToString("D"), //property.Guid.ToString("D")
                            }
                        };

                        //SetLayoutData(avmPrimitivePropertyInstance, property.Impl);

                        avmTopLevelSystemUnderTest.PropertyInstance.Add(avmPrimitivePropertyInstance);
                        componentValueflowTargetMapping[property] = avmPrimitivePropertyInstance;
                        vftIdCache[property] = avmPrimitivePropertyInstance.Value.ID;
                        */
                    }

                    #endregion

                    #region Process TopLevelSystemUnderTest ModelicaConnector

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

                        modelicaConnectorCache[mc] = avmPortInstance;
                        avmTopLevelSystemUnderTest.PortInstance.Add(avmPortInstance);
                         */
                    }

                    #endregion

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

                    foreach (var cc in wrapper.ConnectorCollection)
                    {
                        // Now it is ContainerPortInstance => Should be changed in the future.
                        /*
                        var avmPortInstance = new ContainerPortInstance
                        {
                            ID = EnsureComponentIdAttribute(cc),
                            NameInSourceModel = cc.Name,
                        };

                        componentConnectorTargetMapping[cc] = avmPortInstance;
                        avmTopLevelSystemUnderTest.PortInstance.Add(avmPortInstance);
                        */
                    }

                    #endregion

                    avmTestBench.TopLevelSystemUnderTest = avmTopLevelSystemUnderTest;

                   
                }
            }
            

            #endregion

            #region Process TestComponents

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

                #region Component connectors

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

                    avmComponentInstance.ConnectorInstance.Add(avmComponentConnectorInstance);

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

                #endregion

                #region Process testComponent parameters

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

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

                    //SetLayoutData(avmPrimitivePropertyInstance, parameter.Impl);

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

                #endregion

                #region Process testComponent properties

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

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

                    //SetLayoutData(avmPrimitivePropertyInstance, property.Impl);

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

                #endregion

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

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

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

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

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

            #endregion

            #endregion

            #region Process Testbench parameters

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

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

                SetLayoutData(avmParameter, parameter.Impl);

                #region Set value expressions / Derived values

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

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

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

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

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

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

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

                #endregion

                avmTestBench.Parameter.Add(avmParameter);
            }

            #endregion

            #region Process Testbench metrics

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

                SetLayoutData(avmMetric, metric.Impl);

                #region Derived values

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

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

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

                #endregion

                avmTestBench.Metric.Add(avmMetric);
            }

            #endregion

            #region Process Testbench Environments (modelica models)

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

                #region Process modelica connectors

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

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

                #endregion

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

            #endregion

            #region Process Valueflows/set valueexpressions

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

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

            #endregion

            #region Process PortCompositions

            foreach (var pc in tb.Children.PortCompositionCollection)
            {
                var src = pc.SrcEnds.ModelicaConnector;
                var dst = pc.DstEnds.ModelicaConnector;
                /*
                if (src != null & dst != null)
                {
                    ContainerPortInstance avmSrc;
                    ContainerPortInstance avmDst;
                    if (modelicaConnectorCache.ContainsKey(src))
                    {
                        avmSrc = modelicaConnectorCache[src];
                        avmSrc.PortMap.Add(dst.Attributes.ID);
                    }
                    else if (modelicaConnectorCache.ContainsKey(dst))
                    {
                        avmDst = modelicaConnectorCache[dst];
                        avmDst.PortMap.Add(src.Attributes.ID);
                    }
                }
                */
            }

            #endregion

            #region Process Workflows

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

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

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

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

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

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

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

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

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

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

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

            #endregion

            #region Process Settings

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

                var avmSettings = new avm.modelica.SolverSettings
                {
                    IntervalLength = settings.Attributes.IntervalLength,
                    IntervalLengthSpecified = true,
                    
                    // TODO: Give warning
                    IntervalMethod = intervalMethod!=null?intervalMethod.Item2:avm.modelica.IntervalMethod.IntervalLength,
                    
                    // TODO: Give warning
                    JobManagerToolSelection = jobManagerToolSelection!=null?jobManagerToolSelection.Item2:avm.modelica.JobManagerToolSelection.Dymola_latest,
                    
                    JobManagerToolSelectionSpecified = true,
                    NumberOfIntervals = settings.Attributes.NumberOfIntervals,
                    NumberOfIntervalsSpecified = true,
                    Solver = settings.Attributes.Solver.ToString(),
                    StartTime = settings.Attributes.StartTime,
                    StartTimeSpecified = true,
                    StopTime = settings.Attributes.StartTime,
                    StopTimeSpecified = true,
                    Tolerance = settings.Attributes.Tolerance,
                    ToleranceSpecified = true,
                    ToolSpecificAnnotations = settings.Attributes.ToolSpecificAnnotations
                };

                avmTestBench.Settings.Add(avmSettings);
            }

            #endregion

            return avmTestBench;
        }
        public static CyPhy.TestBenchType Convert(avm.TestBench avmTestBench, IMgaProject project)
        {
            if (avmTestBench == null)
                throw new ArgumentNullException("avmTestBench");

            var rootFolder = CyPhyClasses.RootFolder.GetRootFolder((MgaProject)project);
            var testBenchFolder = rootFolder.Children.TestingCollection.Where(d => d.Name == "TestBenches").FirstOrDefault();

            #region Create TestBenchesFolder
            
            if (testBenchFolder == null)
            {
                testBenchFolder = CyPhyClasses.Testing.Create(rootFolder);
                testBenchFolder.Name = "TestBenches";
            }

            #endregion

            #region Create TestBench

            var cyphyTestBench = CyPhyClasses.TestBench.Create(testBenchFolder);
            cyphyTestBench.Name = avmTestBench.Name;


            #endregion

            #region Create TopLevelSystemUnderTest

            var avmSystemUnderTest = avmTestBench.TopLevelSystemUnderTest;
            CyPhy.TopLevelSystemUnderTest cyphySystemUnderTest = null;
            TestBenchPrimitiveWrapper cyphySystemUnderTestReferred = null;
            if (avmSystemUnderTest != null)
            {
                cyphySystemUnderTest = CyPhyClasses.TopLevelSystemUnderTest.Create(cyphyTestBench);
                SetLayoutData(avmSystemUnderTest, cyphySystemUnderTest.Impl);
                if (!string.IsNullOrEmpty(avmSystemUnderTest.DesignID))
                {
                    // Looking for the referred component assembly
                    var allComponentAssembly = GetAllComponentAssemblies(rootFolder.Children.ComponentAssembliesCollection);
                    var componentAssembly = allComponentAssembly.FirstOrDefault(x=>x.Attributes.ConfigurationUniqueID == avmSystemUnderTest.DesignID);
                    if (componentAssembly != null)
                    {
                        cyphySystemUnderTest.GenericReferred = componentAssembly;
                        cyphySystemUnderTest.Name = componentAssembly.Name;
                        cyphySystemUnderTestReferred = new TestBenchPrimitiveWrapper(componentAssembly);
                    }
                }
            }

            #endregion

            #region Create Parameters

            var parameterCache = new List<Tuple<avm.Parameter, CyPhy.Parameter>>();
            foreach (var avmParameter in avmTestBench.Parameter)
            {
                var cyphyTestBenchParameter = CyPhyClasses.Parameter.Create(cyphyTestBench);
                cyphyTestBenchParameter.Name = avmParameter.Name;
                cyphyTestBenchParameter.Attributes.Description = avmParameter.Notes;
                cyphyTestBenchParameter.Attributes.ID = avmParameter.ID;
                SetLayoutData(avmParameter, cyphyTestBenchParameter.Impl);

                parameterCache.Add(new Tuple<avm.Parameter, CyPhy.Parameter>(avmParameter, cyphyTestBenchParameter));

                #region Set attribute values

                var avmValue = avmParameter.Value;
                if (avmValue != null)
                {
                    CyPhyClasses.Parameter.AttributesClass.DataType_enum cyphyDataType;

                    // TODO: else give a warning
                    if (ConvertCyPhyDataTypeEnum(avmValue.DataType, out cyphyDataType))
                    {
                        cyphyTestBenchParameter.Attributes.DataType = cyphyDataType;
                    }

                    cyphyTestBenchParameter.Attributes.Dimension = avmValue.Dimensions;

                    var avmValueExpression = avmValue.ValueExpression;
                    if (avmValueExpression != null && avmValueExpression is avm.ParametricValue)
                    {
                        var avmParametricValue = (avm.ParametricValue)avmValueExpression;
                        
                        var avmAssignedValue = avmParametricValue.AssignedValue as FixedValue;
                        var avmDefault = avmParametricValue.Default as FixedValue;
                        var avmMaximum = avmParametricValue.Maximum as FixedValue;
                        var avmMinimum = avmParametricValue.Minimum as FixedValue;

                        if (avmAssignedValue!=null && avmAssignedValue.Value!=null)
                            cyphyTestBenchParameter.Attributes.Value = avmAssignedValue.Value;
                        if (avmDefault!=null && avmDefault.Value!=null)
                            cyphyTestBenchParameter.Attributes.DefaultValue = avmDefault.Value;
                        
                        if (avmMinimum!=null && !string.IsNullOrEmpty(avmMinimum.Value) && avmMaximum!=null && !string.IsNullOrEmpty(avmMaximum.Value))
                            cyphyTestBenchParameter.Attributes.Range = String.Format("{0}..{1}",avmMinimum.Value,avmMaximum.Value);
                    }
                }

                #endregion
            }

            #endregion

            #region Create Metrics

            var metricCache = new List<Tuple<avm.Metric, CyPhy.Metric>>();
            foreach (var avmMetric in avmTestBench.Metric)
            {
                var cyphyTestBenchMetric = CyPhyClasses.Metric.Create(cyphyTestBench);

                cyphyTestBenchMetric.Name = avmMetric.Name;
                cyphyTestBenchMetric.Attributes.Description = avmMetric.Notes;
                SetLayoutData(avmMetric, cyphyTestBenchMetric.Impl);

                metricCache.Add(new Tuple<avm.Metric, CyPhy.Metric>(avmMetric, cyphyTestBenchMetric));
            }

            #endregion

            #region Create valueflows

            // Start with TopLevelSystemUnderTest
            if (avmSystemUnderTest != null && cyphySystemUnderTest != null)
            {
                /*
                // Parameters and properties
                foreach (var avmParameter in avmSystemUnderTest.PropertyInstance.Where(x=>x.Value!=null))
                {
                    // Target of valueflow
                    if (avmParameter.Value.ValueExpression is DerivedValue)
                    {
                        var derivedValue = (DerivedValue)avmParameter.Value.ValueExpression;
                        // Look for the parameter instance
                        dynamic cyphyValueflowSrc = cyphySystemUnderTestReferred.ParameterCollection.FirstOrDefault(x => x.Attributes.ID == avmParameter.IDinSourceModel);

                        // Maybe it is a property
                        if (cyphyValueflowSrc == null)
                        {
                            cyphyValueflowSrc = cyphySystemUnderTestReferred.PropertyCollection.FirstOrDefault(x => x.Attributes.ID == avmParameter.IDinSourceModel);
                        }

                        // TODO: Else warning
                        if (cyphyValueflowSrc != null)
                        {
                            var cachePair = parameterCache.FirstOrDefault(x=>x.Item1.Value.ID == derivedValue.ValueSource);
                            if (cachePair != null)
                            {
                                var cyphyValueflowDst = cachePair.Item2;
                                var srcRef = ((CyPhy.ValueFlowTarget)cyphyValueflowSrc).ParentContainer is CyPhyClasses.TestBench ? null : cyphySystemUnderTest;
                                var dstRef = ((CyPhy.ValueFlowTarget)cyphyValueflowDst).ParentContainer is CyPhyClasses.TestBench ? null : cyphySystemUnderTest;
                                // Doesnt work
                                CyPhyClasses.ValueFlow.Connect((CyPhy.ValueFlowTarget)cyphyValueflowSrc, (CyPhy.ValueFlowTarget)cyphyValueflowDst, srcRef, dstRef, cyphyTestBench);
                                //CyPhyClasses.ValueFlow.ConnectGeneric((CyPhy.ValueFlowTarget)cyphyValueflowDst, (CyPhy.ValueFlowTarget)cyphyValueflowSrc, null, null, cyphyTestBench);
                            }
                        }
                    }
                }
                 */ 
            }

            #endregion

            return cyphyTestBench;
        }