コード例 #1
0
ファイル: Perspective.cs プロジェクト: Kintaro/Hyperion
 public static ICamera CreateCamera(ParameterSet parameters, AnimatedTransform cameraToWorld, IFilm film)
 {
     double shutteropen = parameters.FindOneDouble ("shutteropen", 0.0);
     double shutterclose = parameters.FindOneDouble ("shutterclose", 1.0);
     double lensradius = parameters.FindOneDouble ("lensradius", 0.0);
     double focaldistance = parameters.FindOneDouble ("focaldistance", 1E+30);
     double frame = parameters.FindOneDouble ("frameaspectratio", (double)(film.xResolution) / (double)(film.yResolution));
     double[] screen = new double[4];
     if (frame > 1.0)
     {
         screen[0] = -frame;
         screen[1] = frame;
         screen[2] = -1.0;
         screen[3] = 1.0;
     } else
     {
         screen[0] = -1.0;
         screen[1] = 1.0;
         screen[2] = -1.0 / frame;
         screen[3] = 1.0 / frame;
     }
     int swi = 0;
     double[] sw = parameters.FindDouble ("screenwindow", ref swi);
     if (sw != null && swi == 4)
         screen = sw;
     double fov = parameters.FindOneDouble ("fov", 90.0);
     return new Perspective (cameraToWorld, screen, shutteropen, shutterclose, lensradius, focaldistance, fov, film);
 }
コード例 #2
0
ファイル: AIQB.cs プロジェクト: scotttorgeson/HeroesOfRock
        private void InitEnemyPools(ref ParameterSet Parm)
        {
            availableWeakAI = new LinkedList<AI>();
            availableRangedAI = new LinkedList<AI>();
            availableHeavyAI = new LinkedList<AI>();

            //add the number of enemies in the file

            Vector3 zero = Vector3.Zero;

            int num;
            if (Parm.HasParm("EnemyWeakPoolSize"))
                num = Parm.GetInt("EnemyWeakPoolSize");
            else num = 0;

            for(int i = 0; i < num; i++)
                PreLoad("EnemyWeak", ref zero, ref zero);

            if (Parm.HasParm("EnemyRangedPoolSize"))
                num = Parm.GetInt("EnemyRangedPoolSize");
            else num = 0;

            for (int i = 0; i < num; i++)
                PreLoad("EnemyRanged", ref zero, ref zero);

            if (Parm.HasParm("EnemyHeavyPoolSize"))
                num = Parm.GetInt("EnemyHeavyPoolSize");
            else num = 0;

            for(int i = 0; i < num; i++)
                PreLoad("EnemyHeavy", ref zero, ref zero);

            ShutdownAll();
        }
コード例 #3
0
 public override void Serialize(ref ParameterSet parm)
 {
     parm.AddParm("NewDir", newForwardDir);
     parm.AddParm("RotateRight", rotateRight);
     parm.AddParm("RotationTime", rotationTime);
     base.Serialize(ref parm);
 }
コード例 #4
0
        /// <summary>
        /// Gets the test cases generated by the CombiningStrategy.
        /// </summary>
        /// <returns>The test cases.</returns>
        public IEnumerable<ITestCaseData> GetTestCases(IEnumerable[] sources)
        {
            List<ITestCaseData> testCases = new List<ITestCaseData>();

            IEnumerator[] enumerators = new IEnumerator[sources.Length];
            for (int i = 0; i < sources.Length; i++)
                enumerators[i] = sources[i].GetEnumerator();

            for (; ; )
            {
                bool gotData = false;
                object[] testdata = new object[sources.Length];

                for (int i = 0; i < sources.Length; i++)
                    if (enumerators[i].MoveNext())
                    {
                        testdata[i] = enumerators[i].Current;
                        gotData = true;
                    }
                    else
                        testdata[i] = null;

                if (!gotData)
                    break;

                ParameterSet parms = new ParameterSet(testdata);
                testCases.Add(parms);
            }

            return testCases;
        }
コード例 #5
0
 public static RModelInstance GetRModelInstance(ParameterSet parm)
 {
     if (parm.HasParm("ModelType"))
         if (parm.GetString("ModelType") == "Skinned")
             return new SkinnedRModelInstance(parm);
     return new RModelInstance(parm);
 }
コード例 #6
0
        public override void Serialize(ref ParameterSet parm)
        {
            parm.AddParm("InputAction", inputAction.name);
            parm.AddParm("KillOnButtonPush", killOnButtonPush);

            base.Serialize(ref parm);
        }
コード例 #7
0
ファイル: ActorQB.cs プロジェクト: scotttorgeson/HeroesOfRock
 public Actor CreateActor(ParameterSet parm, string instanceName, ref Vector3 position, ref Vector3 rotation, Stage stage)
 {
     Actor newActor = new Actor(parm, instanceName, ref position, ref rotation, Stage.Content, stage);
     actors.AddLast(newActor);
     NotifyActorCreatedList(newActor);
     return newActor;
 }
コード例 #8
0
        public override void LoadContent(Microsoft.Xna.Framework.Content.ContentManager content, ParameterSet parm, Stage stage)
        {
            if (contentLoaded)
                return;

            bool initialized = false;

            model = BasicModelLoad(parm, out initialized);

            if (!initialized)
            {
                foreach (ModelMesh mesh in model.Meshes)
                {
                    foreach (ModelMeshPart part in mesh.MeshParts)
                    {
                        Water effect = new Water(content.Load<Effect>("Effects/v2/Water"));
                        if (stage.Parm.HasParm("WaterSpecularPower"))
                            effect.SpecularPower = stage.Parm.GetFloat("WaterSpecularPower");
                        if (stage.Parm.HasParm("WaterShininess"))
                            effect.Shininess = stage.Parm.GetFloat("WaterShininess");
                        if (stage.Parm.HasParm("WaterColor"))
                            effect.WaterColor = stage.Parm.GetVector4("WaterColor");
                        if (stage.Parm.HasParm("WaterBase"))
                            effect.WaterBase = stage.Parm.GetVector4("WaterBase");
                        part.Effect = effect;
                    }
                }
            }

            transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            base.LoadContent(content, parm, stage);
        }
コード例 #9
0
ファイル: DiffuseAreaLight.cs プロジェクト: Kintaro/Hyperion
 public static AreaLight CreateAreaLight(Transform lightToWorld, ParameterSet paramSet, IShape shape)
 {
     Spectrum L = paramSet.FindOneSpectrum ("L", new Spectrum (1.0));
     Spectrum sc = paramSet.FindOneSpectrum ("scale", new Spectrum (1.0));
     int nSamples = paramSet.FindOneInt ("nsamples", 1);
     return new DiffuseAreaLight (lightToWorld, L * sc, nSamples, shape);
 }
コード例 #10
0
        public MainForm()
        {
            InitializeComponent();
            agentParms = ParameterSet.FromFile("../../../../../Editor/listAgents.parm");

            openToolStripMenuItem.Enabled = true;
            saveToolStripMenuItem.Enabled = true;
            buttonPause.Enabled = false;
            buttonStop.Enabled = false;
            buttonStart.Enabled = true;

            actorEditButton.Enabled = false;
            actorRemoveButton.Enabled = false;
            this.stageControl = new StageControl(this);
            //this.stageControl.Size = new System.Drawing.Size(1280, 720);
            //this.stageControl.Location = new System.Drawing.Point(100, 50);
            this.stageControl.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right);
            this.stageControl.Dock = DockStyle.Fill;
            this.splitContainer1.Panel2.Controls.Add(stageControl);
            //this.Controls.Add(stageControl);

            //this.stageControl.PropertiesPanel = this.PropertiesPanel;

            foreach (string actorFile in System.IO.Directory.EnumerateFiles("../../../../HeroesOfRockContent/Actors/"))
            {
                this.actorListBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(actorFile));
            }
            propertiesChanged = false;
        }
コード例 #11
0
 public ParameterSetResult(NodeSequence arguments, ParameterSet parameterSet, object setInstance, IEnumerable<BindError> errors)
 {
     this.Arguments = arguments;
     this.ParameterSet = parameterSet;
     this.Object = setInstance;
     this.Errors = errors.ToArray();
 }
コード例 #12
0
        /// <summary>
        /// Gets the test cases generated by the CombiningStrategy.
        /// </summary>
        /// <returns>The test cases.</returns>
        public override IEnumerable<ITestCaseData> GetTestCases()
        {
            List<ITestCaseData> testCases = new List<ITestCaseData>();
            IEnumerator[] enumerators = new IEnumerator[Sources.Length];
            int index = -1;

            for (; ; )
            {
                while (++index < Sources.Length)
                {
                    enumerators[index] = Sources[index].GetEnumerator();
                    if (!enumerators[index].MoveNext())
						return testCases;
                }

                object[] testdata = new object[Sources.Length];

                for (int i = 0; i < Sources.Length; i++)
                    testdata[i] = enumerators[i].Current;

                ParameterSet parms = new ParameterSet(testdata);
				testCases.Add(parms);

                index = Sources.Length;

                while (--index >= 0 && !enumerators[index].MoveNext()) ;

                if (index < 0) break;
            }

			return testCases;
        }
コード例 #13
0
 public static void ParseParmSet(ref ParameterSet actorParm, ref ParameterSet worldParm)
 {
     if (worldParm.HasParm("DieOnTrigger"))
         actorParm.AddParm("DieOnTrigger", worldParm.GetBool("DieOnTrigger"));
     if (worldParm.HasParm("InputAction"))
         actorParm.AddParm("InputAction", worldParm.GetString("InputAction"));
 }
コード例 #14
0
ファイル: GraphicsState.cs プロジェクト: Kintaro/Hyperion
 public GraphicsState()
 {
     MaterialParameters = new ParameterSet ();
     AreaLightParameters = new ParameterSet ();
     Material = "Matte";
     ReverseOrientation = false;
 }
コード例 #15
0
ファイル: RModel.cs プロジェクト: scotttorgeson/HeroesOfRock
        public RModel(ParameterSet parm)
        {
            ModelInfo m;
            m.modelName = parm.GetString("ModelName");
            Name = m.modelName;

            ShadowDrawLists = new FastList<RModelInstance>[Sun.NUM_CASCADES];
            for (int i = 0; i < ShadowDrawLists.Length; i++)
                ShadowDrawLists[i] = new FastList<RModelInstance>();

            if (parm.HasParm("BumpMap"))
                IsBumpMapped = true;
            if (parm.HasParm("Shininess"))
                Shininess = parm.GetFloat("Shininess");
            if (parm.HasParm("SpecularPower"))
                SpecularPower = parm.GetFloat("SpecularPower");
            if (parm.HasParm("SpecularMap"))
                IsSpecularMapped = true;
            if (parm.HasParm("CastsShadows"))
                CastsShadows = parm.GetBool("CastsShadows");
            if (parm.HasParm("ReceivesShadows"))
                ReceivesShadows = parm.GetBool("ReceivesShadows");
            if (parm.HasParm("AlphaBlend"))
                AlphaBlend = parm.GetBool("AlphaBlend");

            m.textureName = "";
            if (parm.HasParm("Texture"))
                m.textureName = parm.GetString("Texture");

            modelDictionary.Add(m, this);
            Renderer.Instance.AddRModel(this);
        }
コード例 #16
0
        public listBoxForm(ParameterSet ps, Actor a, Manipulator m, MainForm ma)
        {
            InitializeComponent();
            int index = 0;

            selectedActor = a;
            parms = ps;
            man = m;
            main = ma;
            if (man != null)
                man.enableRayCast = false;

            if (selectedActor.Name.Contains("Trigger"))
                triggerFlag = true;

            string agents = "";
            if (selectedActor.Parm.HasParm("Agents"))
                agents = selectedActor.Parm.GetString("Agents");

            foreach (KeyValuePair<string, string> s in ps)
            {
                if (index++ != 0)
                {
                    this.listBox.Items.Add(s.Key);
                    foreach (string str in agents.Split(','))
                    {
                        if (str == s.Key)
                            listBox.SelectedIndices.Add(index - 2);
                    }
                }
            }
        }
コード例 #17
0
 // NoLB parameter set
 public AzureEndPointConfigInfo(ParameterSet paramset,
     ProtocolInfo endpointProtocol,
     int endpointLocalPort,
     int endpointPublicPort,
     string endpointName,
     NetworkAclObject aclObj = null,
     bool directServerReturn = false,
     string internalLoadBalancer = null,
     string serviceName = null,
     string loadBalancerDistribution = null,
     string VirtualIPName = null)
 {
     this.Initialize(
         endpointProtocol,
         endpointLocalPort,
         endpointPublicPort,
         endpointName, 
         string.Empty, 
         0, 
         ProtocolInfo.tcp, 
         string.Empty, 
         null, 
         null,
         paramset,
         aclObj,
         directServerReturn,
         internalLoadBalancer,
         serviceName,
         loadBalancerDistribution,
         VirtualIPName);
 }
コード例 #18
0
        /// <summary>
        /// Gets the test cases generated by the CombiningStrategy.
        /// </summary>
        /// <returns>The test cases.</returns>
        public override IEnumerable<ITestCaseData> GetTestCases()
        {
            List<ITestCaseData> testCases = new List<ITestCaseData>();

            for (; ; )
            {
                bool gotData = false;
                object[] testdata = new object[Sources.Length];

                for (int i = 0; i < Sources.Length; i++)
                    if (Enumerators[i].MoveNext())
                    {
                        testdata[i] = Enumerators[i].Current;
                        gotData = true;
                    }
                    else
                        testdata[i] = null;

                if (!gotData)
                    break;

                ParameterSet parms = new ParameterSet(testdata);
                testCases.Add(parms);
            }

            return testCases;
        }
コード例 #19
0
 public static new void ParseParmSet(ref ParameterSet actorParm, ref ParameterSet worldParm)
 {
     if (worldParm.HasParm("Strength"))
         actorParm.AddParm("Strength", worldParm.GetFloat("Strength"));
     if (worldParm.HasParm("Direction"))
         actorParm.AddParm("Direction", worldParm.GetVector3("Direction"));
 }
コード例 #20
0
ファイル: Api.cs プロジェクト: Kintaro/Hyperion
 public static void Camera(string name, ParameterSet parameterSet)
 {
     Api.RenderOptions.CameraName = name;
     Api.RenderOptions.CameraParameters = parameterSet;
     Api.RenderOptions.CameraToWorld = CurrentTransform.Inverse;
     NamedCoordinateSystems["camera"] = new TransformSet (Api.RenderOptions.CameraToWorld);
 }
コード例 #21
0
ファイル: Application.cs プロジェクト: guyzo/semantic-logging
        internal static int Main(string[] args)
        {
            if (args.Length == 0 && false == Environment.UserInteractive)
            {
                // Called by SCM
                ServiceBase.Run(new TraceEventServiceHost());
                return (int)ApplicationExitCode.Success;
            }

            var options = new ParameterOptions();
            var parameters = new ParameterSet
            {
                { "i|install", Resources.InstallArgDescription, (p, a) => options.Install(a) },
                { "u|uninstall", Resources.UninstallArgDescription, (p, a) => options.Uninstall() },
                { "s|start", Resources.StartArgDescription, (p, a) => options.Start(a) },
                { "c|console", Resources.ConsoleArgDescription, (p, a) => options.ConsoleMode() },
                { "h|help|?", Resources.HelpArgDescription, (p, a) => options.ShowHelp(p) },
                { "a|account", Resources.AccountArgDescription, ParameterOptions.AccountParameterKey }
            };

            options.ShowHeader();

            if (!parameters.Parse(args))
            {
                options.ShowHelp(parameters);
                return (int)ApplicationExitCode.InputError;
            }

            return (int)options.ExitCode;
        }
コード例 #22
0
ファイル: AIQB.cs プロジェクト: scotttorgeson/HeroesOfRock
 public override void PreLoadInit(ParameterSet Parm)
 {
     numEnemiesInLevel = 0;
     aliveEnemies = new LinkedList<AI>();
     spawners = new List<SpawnActorTriggerVolume>();
     rand = new Random();
 }
コード例 #23
0
 public Actor AddTrigger(ParameterSet parm, Vector3 position)
 {
     Vector3 zero = Vector3.Zero;
     Actor trigger = new Actor(parm, "Trigger", ref position, ref zero, Stage.Content, Stage.ActiveStage);
     triggers.AddLast(trigger);
     return trigger;
 }
コード例 #24
0
ファイル: Sphere.cs プロジェクト: Kintaro/Hyperion
 public static IShape CreateShape(Transform o2w, Transform w2o, bool reverseOrientation, ParameterSet parameters, Dictionary<string, ITexture<double>> floatTextures, Dictionary<string, ITexture<Spectrum>> spectrumTextures)
 {
     double radius = parameters.FindOneDouble ("radius", 1.0);
     double zmin = parameters.FindOneDouble ("zmin", -radius);
     double zmax = parameters.FindOneDouble ("zmax", radius);
     double phimax = parameters.FindOneDouble ("phimax", 360.0);
     return new Sphere (o2w, w2o, reverseOrientation, radius, zmin, zmax, phimax);
 }
コード例 #25
0
 public BuildContext(NodeSequence sequence, ParameterSet paramSet, object instance)
 {
     this.Sequence = sequence;
     this.Instance = instance;
     this.ParameterSet = paramSet;
     this.Errors = new List<BindError>();
     this.RemainingParameters = new List<Parameter>(paramSet.OrderBy(p => p.Position.HasValue ? p.Position.Value : int.MinValue));
 }
コード例 #26
0
        /// <summary>
        /// Read trigger specific parameters from the world parm and add them to the actor parm
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static new void ParseParmSet(ref ParameterSet actorParm, ref ParameterSet worldParm)
        {
            if (worldParm.HasParm("TextPosition"))
                actorParm.AddParm("TextPosition", worldParm.GetVector2("TextPosition"));

            if (worldParm.HasParm("Text"))
                actorParm.AddParm("Text", worldParm.GetString("Text"));
        }
コード例 #27
0
        public override void LoadContent(ContentManager content, ParameterSet parm, Stage stage)
        {
            // just load the model
            bool initialized = false;
            model = Renderer.Instance.LookupModel("Models/" + Name, out initialized);

             	        base.LoadContent(content, parm, stage);
        }
コード例 #28
0
ファイル: Disk.cs プロジェクト: Kintaro/Hyperion
 public static IShape CreateShape(Transform o2w, Transform w2o, bool reverseOrientation, ParameterSet parameters, Dictionary<string, ITexture<double>> floatTextures, Dictionary<string, ITexture<Spectrum>> spectrumTextures)
 {
     double height = parameters.FindOneDouble ("height", 0.0);
     double radius = parameters.FindOneDouble ("radius", 1);
     double inner_radius = parameters.FindOneDouble ("innerradius", 0);
     double phimax = parameters.FindOneDouble ("phimax", 360);
     return new Disk (o2w, w2o, reverseOrientation, height, radius, inner_radius, phimax);
 }
コード例 #29
0
ファイル: Mitchell.cs プロジェクト: Kintaro/Hyperion
 public static IFilter CreateFilter(ParameterSet ps)
 {
     double xw = ps.FindOneDouble ("xwidth", 2.0);
     double yw = ps.FindOneDouble ("ywidth", 2.0);
     double B = ps.FindOneDouble ("B", 1.0 / 3.0);
     double C = ps.FindOneDouble ("C", 1.0 / 3.0);
     return new Mitchell (B, C, xw, yw);
 }
コード例 #30
0
        public static new void ParseParmSet(ref ParameterSet actorParm, ref ParameterSet worldParm)
        {
            System.Diagnostics.Debug.Assert(worldParm.HasParm("InputAction"), "ButtonPushTriggerVolume requires an input action!");
            actorParm.AddParm("InputAction", worldParm.GetString("InputAction"));

            if (worldParm.HasParm("KillOnButtonPush"))
                actorParm.AddParm("KillOnButtonPush", worldParm.GetBool("KillOnButtonPush"));
        }
コード例 #31
0
        public Autodesk.Revit.UI.Result Execute(
            ExternalCommandData revit,
            ref string message,
            ElementSet elements)
        {
            try
            {
                // Get the active document and view
                UIDocument             revitDoc = revit.Application.ActiveUIDocument;
                Autodesk.Revit.DB.View view     = revitDoc.Document.ActiveView;
                foreach (Autodesk.Revit.DB.Element elem in revitDoc.Selection.Elements)
                {
                    //if( elem.GetType() == typeof( Autodesk.Revit.DB.Structure.Rebar ) )
                    if (elem is Rebar)
                    {
                        string str = "";
                        Autodesk.Revit.DB.Structure.Rebar rebar = (Autodesk.Revit.DB.Structure.Rebar)elem;
                        ParameterSet pars = rebar.Parameters;
                        foreach (Parameter param in pars)
                        {
                            string val  = "";
                            string name = param.Definition.Name;
                            Autodesk.Revit.DB.StorageType type = param.StorageType;
                            switch (type)
                            {
                            case Autodesk.Revit.DB.StorageType.Double:
                                val = param.AsDouble().ToString();
                                break;

                            case Autodesk.Revit.DB.StorageType.ElementId:
                                Autodesk.Revit.DB.ElementId id       = param.AsElementId();
                                Autodesk.Revit.DB.Element   paraElem = revitDoc.Document.GetElement(id);
                                if (paraElem != null)
                                {
                                    val = paraElem.Name;
                                }
                                break;

                            case Autodesk.Revit.DB.StorageType.Integer:
                                val = param.AsInteger().ToString();
                                break;

                            case Autodesk.Revit.DB.StorageType.String:
                                val = param.AsString();
                                break;

                            default:
                                break;
                            }
                            str = str + name + ": " + val + "\r\n";
                        }
                        TaskDialog.Show("Rebar parameters", str);
                        return(Autodesk.Revit.UI.Result.Succeeded);
                    }
                }
                message = "No rebar selected!";
                return(Autodesk.Revit.UI.Result.Failed);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
コード例 #32
0
 internal override void BuildInstance(InjectionContext context, ParameterSet parameters, out T instance)
 {
     DoBuildInstance(context, parameters, out instance);
 }
コード例 #33
0
 internal override void BuildInstance(InjectionContext context, ParameterSet parameters, out T instance)
 {
     instance = _lifetime.BuildInstance(context, this, parameters);
 }
コード例 #34
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message,
                                                ElementSet elements)
        {
            // set out default result to failure.
            Autodesk.Revit.UI.Result retRes = Autodesk.Revit.UI.Result.Failed;

            Autodesk.Revit.UI.UIApplication app = commandData.Application;

            // get the elements selected
            // The current selection can be retrieved from the active
            // document via the selection object
            SelElementSet seletion = app.ActiveUIDocument.Selection.Elements;

            // we need to make sure that only one element is selected.
            if (seletion.Size == 1)
            {
                // we need to get the first and only element in the selection. Do this by getting
                // an iterator. MoveNext and then get the current element.
                ElementSetIterator it = seletion.ForwardIterator();
                it.MoveNext();
                Element element = it.Current as Element;

                // Next we need to iterate through the parameters of the element,
                // as we iterating, we will store the strings that are to be displayed
                // for the parameters in a string list "parameterItems"
                List <string> parameterItems = new List <string>();
                ParameterSet  parameters     = element.Parameters;
                foreach (Parameter param in parameters)
                {
                    if (param == null)
                    {
                        continue;
                    }

                    // We will make a string that has the following format,
                    // name type value
                    // create a StringBuilder object to store the string of one parameter
                    // using the character '\t' to delimit parameter name, type and value
                    StringBuilder sb = new StringBuilder();

                    // the name of the parameter can be found from its definition.
                    sb.AppendFormat("{0}\t", param.Definition.Name);

                    // Revit parameters can be one of 5 different internal storage types:
                    // double, int, string, Autodesk.Revit.DB.ElementId and None.
                    // if it is double then use AsDouble to get the double value
                    // then int AsInteger, string AsString, None AsStringValue.
                    // Switch based on the storage type
                    switch (param.StorageType)
                    {
                    case Autodesk.Revit.DB.StorageType.Double:
                        // append the type and value
                        sb.AppendFormat("double\t{0}", param.AsDouble());
                        break;

                    case Autodesk.Revit.DB.StorageType.ElementId:
                        // for element ids, we will try and retrieve the element from the
                        // document if it can be found we will display its name.
                        sb.Append("Element\t");

                        // using ActiveDocument.GetElement(the element id) to
                        // retrieve the element from the active document
                        Autodesk.Revit.DB.ElementId elemId = new ElementId(param.AsElementId().IntegerValue);
                        Element elem = app.ActiveUIDocument.Document.GetElement(elemId);

                        // if there is an element then display its name,
                        // otherwise display the fact that it is not set
                        sb.Append(elem != null ? elem.Name : "Not set");
                        break;

                    case Autodesk.Revit.DB.StorageType.Integer:
                        // append the type and value
                        sb.AppendFormat("int\t{0}", param.AsInteger());
                        break;

                    case Autodesk.Revit.DB.StorageType.String:
                        // append the type and value
                        sb.AppendFormat("string\t{0}", param.AsString());
                        break;

                    case Autodesk.Revit.DB.StorageType.None:
                        // append the type and value
                        sb.AppendFormat("none\t{0}", param.AsValueString());
                        break;

                    default:
                        break;
                    }

                    // add the completed line to the string list
                    parameterItems.Add(sb.ToString());
                }

                // Create our dialog, passing it the parameters array for display.
                PropertiesForm propertiesForm = new PropertiesForm(parameterItems.ToArray());
                propertiesForm.StartPosition = FormStartPosition.CenterParent;
                propertiesForm.ShowDialog();
                retRes = Autodesk.Revit.UI.Result.Succeeded;
            }
            else
            {
                message = "Please select only one element";
            }
            return(retRes);
        }
コード例 #35
0
        /// <summary>
        /// Display the value of Unique ID parameter in a list box
        /// </summary>
        /// <returns></returns>
        public System.Collections.ArrayList SendValueToListBox()
        {
            ElementSet elements = new ElementSet();

            foreach (ElementId elementId in m_revit.ActiveUIDocument.Selection.GetElementIds())
            {
                elements.Insert(m_revit.ActiveUIDocument.Document.GetElement(elementId));
            }

            // all the elements of current document
            IEnumerator i = elements.GetEnumerator();

            ArrayList parameterValueArrangeBox = new ArrayList();

            // if the selections include beams and slabs, find out their Unique ID's value for display
            i.Reset();
            bool moreElements = i.MoveNext();

            while (moreElements)
            {
                // Get beams and slabs from selections
                Element component = i.Current as Autodesk.Revit.DB.Element;

                if (null == component)
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                if (null == component.Category)
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                if (("Structural Framing" != component.Category.Name) &&
                    ("Floors" != component.Category.Name))
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                // Get "Unique ID" parameter and display its value in a list box
                ParameterSet attributes = component.Parameters;

                foreach (object o in attributes)
                {
                    Parameter attribute = o as Parameter;

                    if ("Unique ID" == attribute.Definition.Name)
                    {
                        if (null == attribute.AsString())
                        {
                            break;
                        }

                        parameterValueArrangeBox.Add(attribute.AsString());
                        break;
                    }
                }
                moreElements = i.MoveNext();
            }
            return(parameterValueArrangeBox);
        }
コード例 #36
0
        public static List <Apartment> giantAnteater(Plot plot, ApartmentGeneratorBase ag, Target target, bool previewOn)
        {
            double mutationProbability = ag.GAParameterSet[0];
            double elitismPercentage   = ag.GAParameterSet[1];
            double initialBoost        = ag.GAParameterSet[2];
            int    population          = (int)ag.GAParameterSet[3];
            int    maxGen         = (int)ag.GAParameterSet[4];
            double fitnessFactor  = ag.GAParameterSet[5];
            double mutationFactor = ag.GAParameterSet[6];

            //Initialize Minimum and Maximum value
            double[] tempMaxInput = ag.MaxInput.Clone() as double[];
            double[] tempMinInput = ag.MinInput.Clone() as double[];

            //create initial genes
            Random myRandom  = new Random((int)DateTime.Now.Ticks);
            double goodAngle = maxRectDirection(plot);

            //double goodAngle = Math.PI * 152 / 180;

            List <ParameterSet> offspringGenes = new List <ParameterSet>();

            //for (int i = 0; i < initialBoost; i++)
            //{
            //    CoreType tempCoreType = ag.GetRandomCoreType();

            //    double[] oneGene = new double[ag.MinInput.Length];

            //    //if (ag.IsCoreProtrude)
            //    //    tempMaxInput[2] = tempCoreType.GetDepth();

            //    for (int j = 0; j < ag.MinInput.Length; j++)
            //    {
            //        if (i % 2 == 0 && j == 3 && ag.GetType() == typeof(AG1))
            //        {
            //            oneGene[j] = goodAngle;
            //        }
            //        else
            //        {
            //            double parameterForGene = (tempMaxInput[j] - tempMinInput[j]) * myRandom.NextDouble() + tempMinInput[j];
            //            oneGene[j] = parameterForGene;
            //        }

            //        oneGene[0] = Math.Floor(oneGene[0]);
            //        oneGene[1] = Math.Floor(oneGene[1]);

            //    }

            //    ParameterSet a = new ParameterSet(oneGene, ag.GetType().ToString(), tempCoreType);
            //    offspringGenes.Add(a);
            //}

            double otherAngles = population * initialBoost;//(population - 1) * initialBoost;

            for (int i = 0; i < (int)otherAngles; i++)
            {
                CoreType tempCoreType = ag.GetRandomCoreType();

                double[] oneGene = new double[ag.MinInput.Length];

                //if (ag.IsCoreProtrude)
                //    tempMaxInput[2] = tempCoreType.GetDepth();

                for (int j = 0; j < ag.MinInput.Length; j++)
                {
                    if (/*i % 2 == 0 &&*/ j == 3 && ag.GetType() == typeof(AG1))
                    {
                        double parameterForGene = ((goodAngle + Math.PI / 2 * (i % 4) / 2) % (Math.PI * 2) + Math.PI * ((int)(i / 4) % 2) % (Math.PI * 2));
                        //oneGene[j] = parameterForGene;
                        //double mainAngle = Math.PI * i / otherAngles;
                        //oneGene[j] = mainAngle;
                        oneGene[j] = parameterForGene;
                    }
                    else
                    {
                        double parameterForGene = (tempMaxInput[j] - tempMinInput[j]) * myRandom.NextDouble() + tempMinInput[j];

                        //width - 100씩
                        if (j == 2)
                        {
                            parameterForGene = Math.Round(parameterForGene / 100) * 100;
                        }
                        oneGene[j] = parameterForGene;
                    }

                    oneGene[0] = Math.Floor(oneGene[0]);
                    oneGene[1] = Math.Floor(oneGene[1]);
                }

                ParameterSet a = new ParameterSet(oneGene);
                offspringGenes.Add(a);
            }

            //initializing end condition
            bool endCondition = true;

            //start genetic algorithm
            int          genCount = 0;
            ParameterSet bestGene = offspringGenes[0];

            while (endCondition)
            {
                //evaluate fitness`
                List <List <double> > evaluation    = new List <List <double> >(evaluateFitness(plot, ag, target, offspringGenes, fitnessFactor, previewOn));
                List <double>         fitnessValues = new List <double>(evaluation[0]);

                //sort genes and fitness values
                RhinoList <ParameterSet> myRhinoList = new RhinoList <ParameterSet>(offspringGenes);
                myRhinoList.Sort(fitnessValues.ToArray());
                myRhinoList.Reverse();
                fitnessValues.Sort();
                fitnessValues.Reverse();
                offspringGenes = myRhinoList.ToList();

                var radcheck = offspringGenes.Select(n => n.Parameters[3]);

                /*
                 * //write
                 * Rhino.RhinoApp.WriteLine(genCount.ToString());
                 * Rhino.RhinoApp.WriteLine(evaluation[1][0].ToString());
                 * Rhino.RhinoApp.WriteLine(evaluation[1][offspringGenes.Count-1].ToString());
                 * ParameterSet geneToShow = offspringGenes[0];
                 *
                 * for (int i = 0; i < geneToShow.Parameters.Length; i++)
                 * {
                 *  Rhino.RhinoApp.WriteLine(geneToShow.Parameters[i].ToString());
                 * }
                 */

                //create new generation
                List <ParameterSet> tempGenes = new List <ParameterSet>();

                //Add elites to new generation
                int eliteNum = (int)(population * elitismPercentage);
                for (int i = 0; i < eliteNum; i++)
                {
                    tempGenes.Add(offspringGenes[i]);
                }

                //crossover & mutation
                for (int i = 0; i < population - eliteNum; i++)
                {
                    ParameterSet newOffspring = crossover(offspringGenes, fitnessValues, (int)myRandom.Next(0, int.MaxValue), ag.GetType().ToString());
                    if (myRandom.NextDouble() < mutationProbability)
                    {
                        newOffspring = mutation(newOffspring, ag, mutationFactor, (int)myRandom.Next(0, int.MaxValue));
                    }
                    tempGenes.Add(newOffspring);
                }
                offspringGenes = tempGenes;

                genCount += 1;
                if (genCount == maxGen)
                {
                    endCondition = false;
                }

                GC.Collect();
                //Rhino.RhinoApp.Wait();

                //finalize before end
                if (endCondition == false)
                {
                    //evaluate fitness
                    evaluation    = new List <List <double> >(evaluateFitness(plot, ag, target, offspringGenes, fitnessFactor, previewOn));
                    fitnessValues = new List <double>(evaluation[0]);

                    //sort genes and fitness values
                    myRhinoList = new RhinoList <ParameterSet>(offspringGenes);
                    myRhinoList.Sort(fitnessValues.ToArray());
                    myRhinoList.Reverse();
                    fitnessValues.Sort();
                    fitnessValues.Reverse();
                    offspringGenes = myRhinoList.ToList();



                    bestGene = offspringGenes[0];
                }

                Rhino.RhinoApp.Wait();
            }

            //best 1
            Apartment bestOutput = ag.generator(plot, bestGene, target);

            return(new Apartment[] { bestOutput }.ToList());

            //best 5
            //var uniqueGenes = offspringGenes.Distinct();
            //Apartment[] bestOutputs = offspringGenes.Take(5).Select(n => ag.generator(plot, n, target)).ToArray();
            //return bestOutputs.ToList();


            //best 10
            //var uniqueGenes = offspringGenes.Distinct();
            //Apartment[] bestOutputs = offspringGenes.Take(10).Select(n=>ag.generator(plot, n, target)).ToArray();
            //return new Apartment[] { bestOutput }.ToList();
            //return bestOutputs.ToList();

            //all
            Apartment[] bestOutputs = offspringGenes.Select(n => ag.generator(plot, n, target)).ToArray();
            return(bestOutputs.ToList());

            if (bestOutput.ParameterSet == null)
            {
                return(FinalizeApartment.finalizeAGoutput(bestOutput, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxBuildingCoverage, false));
            }

            if (bestOutput.ParameterSet.Parameters != null)
            {
                List <Apartment> output = FinalizeApartment.finalizeAGoutput(bestOutput, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxBuildingCoverage, false);

                bool IsSatisfyingLegalParking = false;

                List <Apartment> satisFyingLegalParkingOutput = new List <Apartment>();

                foreach (Apartment i in output)
                {
                    if (i.GetLegalParkingLotOfCommercial() + i.GetLegalParkingLotofHousing() < i.ParkingLotOnEarth.GetCount() + i.ParkingLotUnderGround.Count)
                    {
                        satisFyingLegalParkingOutput.Add(i);
                        IsSatisfyingLegalParking = true;
                    }
                }

                if (IsSatisfyingLegalParking == false)
                {
                    targetError      tempErrorMessage = new targetError();
                    List <Apartment> tempNewOutput    = tempErrorMessage.showDialogAndReturnValue(ag, plot, bestGene, target, output);

                    bool tempSatisfyingLegalParking = false;

                    List <Apartment> tempSatisFyingLegalParkingOutput = new List <Apartment>();

                    foreach (Apartment i in tempNewOutput)
                    {
                        if (i.GetLegalParkingLotOfCommercial() + i.GetLegalParkingLotofHousing() < i.ParkingLotOnEarth.GetCount() + i.ParkingLotUnderGround.Count)
                        {
                            tempSatisfyingLegalParking = true;
                            tempSatisFyingLegalParkingOutput.Add(i);
                        }
                    }

                    if (tempSatisfyingLegalParking == false)
                    {
                        System.Windows.MessageBox.Show("선택한 설계로 법정 주차대수를 만족하기 어려운 대지입니다.");

                        return(output);
                    }
                    else
                    {
                        return(tempSatisFyingLegalParkingOutput);
                    }
                }
                else
                {
                    return(output);
                }
            }
            else
            {
                System.Windows.MessageBox.Show(CommonFunc.GetApartmentType(ag.GetAGType) + " 타입 설계에 적합하지 않은 대지입니다.");
            }

            return(FinalizeApartment.finalizeAGoutput(bestOutput, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxFloorAreaRatio, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.MaxBuildingCoverage, false));
        }
コード例 #37
0
        /// <summary>
        /// found the element which using the GUID
        /// that was assigned to the shared parameter in the shared parameters file.
        /// </summary>
        /// <param name="UniqueIdValue"></param>
        public void FindElement(string UniqueIdValue)
        {
            SelElementSet seleElements = m_revit.ActiveUIDocument.Selection.Elements;

            // all the elements of current document
            IEnumerator i = seleElements.GetEnumerator();


            // if the selections include beams and slabs,
            // find out the element using the select value for display
            i.Reset();
            bool moreElements = i.MoveNext();

            while (moreElements)
            {
                // Get beams and slabs from selections
                Element component = i.Current as Autodesk.Revit.DB.Element;

                if (null == component)
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                if (null == component.Category)
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                if (("Structural Framing" != component.Category.Name) &&
                    ("Floors" != component.Category.Name))
                {
                    moreElements = i.MoveNext();
                    continue;
                }

                // Get "Unique ID" parameter
                ParameterSet attributes = component.Parameters;

                foreach (object o in attributes)
                {
                    Parameter attribute = o as Parameter;

                    if ("Unique ID" == attribute.Definition.Name)
                    {
                        if (null == attribute.AsString())
                        {
                            break;
                        }

                        // compare if the parameter's value is the same as the selected value.
                        // Clear the SelElementSet and add the found element into it.
                        // So this element will highlight in Revit UI
                        if (UniqueIdValue == attribute.AsString())
                        {
                            seleElements.Clear();
                            seleElements.Add(component);
                            return;
                        }

                        break;
                    }
                }

                moreElements = i.MoveNext();
            }
        }
コード例 #38
0
 public override void StepInsideWithTarget(decimal targetValue, HashSet <OptimizationParameter> optimizationParameters, ParameterSet solution)
 {
     base.StepInsideWithTarget(targetValue, optimizationParameters, solution);
 }
コード例 #39
0
 public override void TargetNotReached(decimal targetValue, HashSet <OptimizationParameter> optimizationParameters, ParameterSet solution)
 {
     base.TargetNotReached(targetValue, optimizationParameters, solution);
 }
コード例 #40
0
 public override void StepInsideWithConstraints(decimal drawdown, HashSet <OptimizationParameter> optimizationParameters, ParameterSet solution)
 {
     base.StepInsideWithConstraints(drawdown, optimizationParameters, solution);
 }
コード例 #41
0
 public override void StepInsideNoTargetNoConstraints(Extremum extremum, HashSet <OptimizationParameter> optimizationParameters, ParameterSet solution)
 {
     base.StepInsideNoTargetNoConstraints(extremum, optimizationParameters, solution);
 }
コード例 #42
0
        /// <summary>
        /// Builds a ParameterizedMetodSuite containing individual
        /// test cases for each set of parameters provided for
        /// this method.
        /// </summary>
        /// <param name="method">The MethodInfo for which a test is to be built</param>
        /// <returns>A ParameterizedMethodSuite populated with test cases</returns>
        public static Test BuildParameterizedMethodSuite(MethodInfo method, Test parentSuite)
        {
            ParameterizedMethodSuite methodSuite = new ParameterizedMethodSuite(method);

            NUnitFramework.ApplyCommonAttributes(method, methodSuite);

            if (parentSuite != null)
            {
                if (parentSuite.RunState == RunState.NotRunnable && methodSuite.RunState != RunState.NotRunnable)
                {
                    methodSuite.RunState     = RunState.NotRunnable;
                    methodSuite.IgnoreReason = parentSuite.IgnoreReason;
                }

                if (parentSuite.RunState == RunState.Ignored && methodSuite.RunState != RunState.Ignored && methodSuite.RunState != RunState.NotRunnable)
                {
                    methodSuite.RunState     = RunState.Ignored;
                    methodSuite.IgnoreReason = parentSuite.IgnoreReason;
                }
            }

            foreach (object source in CoreExtensions.Host.TestCaseProviders.GetTestCasesFor(method, parentSuite))
            {
                ParameterSet parms;

                if (source == null)
                {
                    parms           = new ParameterSet();
                    parms.Arguments = new object[] { null };
                }
                else
                {
                    parms = source as ParameterSet;
                }

                if (parms == null)
                {
                    if (source.GetType().GetInterface("NUnit.Framework.ITestCaseData") != null)
                    {
                        parms = ParameterSet.FromDataSource(source);
                    }
                    else
                    {
                        parms = new ParameterSet();

                        ParameterInfo[] parameters = method.GetParameters();
                        Type            sourceType = source.GetType();

                        if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(sourceType))
                        {
                            parms.Arguments = new object[] { source }
                        }
                        ;
                        else if (source is object[])
                        {
                            parms.Arguments = (object[])source;
                        }
                        else if (source is Array)
                        {
                            Array array = (Array)source;
                            if (array.Rank == 1)
                            {
                                parms.Arguments = new object[array.Length];
                                for (int i = 0; i < array.Length; i++)
                                {
                                    parms.Arguments[i] = (object)array.GetValue(i);
                                }
                            }
                        }
                        else
                        {
                            parms.Arguments = new object[] { source }
                        };
                    }
                }

                TestMethod test = BuildSingleTestMethod(method, parentSuite, parms);

                methodSuite.Add(test);
            }

            return(methodSuite);
        }
コード例 #43
0
 protected static bool AlreadyGenerated(ParameterSet paramSet, IEnumerable <ParameterSet> previousRuns)
 {
     return(previousRuns.Any(previousRun => previousRun.Equals(paramSet)));
 }
コード例 #44
0
 public override T BuildInstance(InjectionContext context, InjectionOperator <T> injectionOperator, ParameterSet parameters)
 {
     return(DoBuildInstance(context, injectionOperator, parameters));
 }
コード例 #45
0
        /// <summary>
        /// Builds a single NUnitTestMethod, either as a child of the fixture
        /// or as one of a set of test cases under a ParameterizedTestMethodSuite.
        /// </summary>
        /// <param name="method">The MethodInfo from which to construct the TestMethod</param>
        /// <param name="parms">The ParameterSet to be used, or null</param>
        /// <returns></returns>
        public static NUnitTestMethod BuildSingleTestMethod(MethodInfo method, Test parentSuite, ParameterSet parms)
        {
#if CLR_2_0 || CLR_4_0
            NUnitTestMethod testMethod = Reflect.IsAsyncMethod(method) ?
                                         new NUnitAsyncTestMethod(method) : new NUnitTestMethod(method);
#else
            NUnitTestMethod testMethod = new NUnitTestMethod(method);
#endif

            string prefix = method.ReflectedType.FullName;

            if (parentSuite != null)
            {
                prefix = parentSuite.TestName.FullName;
                testMethod.TestName.FullName = prefix + "." + testMethod.TestName.Name;
            }

            if (CheckTestMethodSignature(testMethod, parms))
            {
                if (parms == null)
                {
                    NUnitFramework.ApplyCommonAttributes(method, testMethod);
                }
                NUnitFramework.ApplyExpectedExceptionAttribute(method, testMethod);
            }

            if (parms != null)
            {
                // NOTE: After the call to CheckTestMethodSignature, the Method
                // property of testMethod may no longer be the same as the
                // original MethodInfo, so we reassign it here.
                method = testMethod.Method;

                if (parms.TestName != null)
                {
                    testMethod.TestName.Name     = parms.TestName;
                    testMethod.TestName.FullName = prefix + "." + parms.TestName;
                }
                else if (parms.OriginalArguments != null)
                {
                    string name = MethodHelper.GetDisplayName(method, parms.OriginalArguments);
                    testMethod.TestName.Name     = name;
                    testMethod.TestName.FullName = prefix + "." + name;
                }

                if (parms.Ignored)
                {
                    testMethod.RunState     = RunState.Ignored;
                    testMethod.IgnoreReason = parms.IgnoreReason;
                }
                else if (parms.Explicit)
                {
                    testMethod.RunState = RunState.Explicit;
                }

                if (parms.ExpectedExceptionName != null)
                {
                    testMethod.exceptionProcessor = new ExpectedExceptionProcessor(testMethod, parms);
                }

                foreach (string key in parms.Properties.Keys)
                {
                    testMethod.Properties[key] = parms.Properties[key];
                }

                // Description is stored in parms.Properties
                if (parms.Description != null)
                {
                    testMethod.Description = parms.Description;
                }
            }

            //if (testMethod.BuilderException != null && testMethod.RunState != RunState.NotRunnable)
            //{
            //    testMethod.RunState = RunState.NotRunnable;
            //    testMethod.IgnoreReason = testMethod.BuilderException.Message;
            //}

            if (parentSuite != null)
            {
                if (parentSuite.RunState == RunState.NotRunnable && testMethod.RunState != RunState.NotRunnable)
                {
                    testMethod.RunState     = RunState.NotRunnable;
                    testMethod.IgnoreReason = parentSuite.IgnoreReason;
                }

                if (parentSuite.RunState == RunState.Ignored && testMethod.RunState != RunState.Ignored && testMethod.RunState != RunState.NotRunnable)
                {
                    testMethod.RunState     = RunState.Ignored;
                    testMethod.IgnoreReason = parentSuite.IgnoreReason;
                }
            }

            return(testMethod);
        }
コード例 #46
0
        public override T BuildInstance(InjectionContext context, InjectionOperator <T> injectionOperator, ParameterSet parameters)
        {
            var matchingScope = context.LifetimeScope.SharingScope;

            Lifetime.ThrowWhenMatchingScopeIsNull(matchingScope, _error);
            var instance   = DoBuildInstance(context, injectionOperator, parameters);
            var disposable = instance as IDisposable;

            lock (matchingScope.SyncRoot)
                matchingScope.RegisterForDisposal(disposable);
            return(instance);
        }
コード例 #47
0
ファイル: ParameterUtil.cs プロジェクト: bimone/IFC-for-Revit
        /// <summary>
        /// Cache the parameters for an element, allowing quick access later.
        /// </summary>
        /// <param name="id">The element id.</param>
        static private void CacheParametersForElement(ElementId id)
        {
            if (id == ElementId.InvalidElementId)
            {
                return;
            }

            if (m_NonIFCParameters.ContainsKey(id))
            {
                return;
            }

            IDictionary <BuiltInParameterGroup, ParameterElementCache> nonIFCParameters = new SortedDictionary <BuiltInParameterGroup, ParameterElementCache>();
            ParameterElementCache ifcParameters = new ParameterElementCache();

            m_NonIFCParameters[id] = nonIFCParameters;
            m_IFCParameters[id]    = ifcParameters;

            Element element = ExporterCacheManager.Document.GetElement(id);

            if (element == null)
            {
                return;
            }

            ParameterSet parameterIds = element.Parameters;

            if (parameterIds.Size == 0)
            {
                return;
            }

            // We will do two passes.  In the first pass, we will look at parameters in the IFC group.
            // In the second pass, we will look at all other groups.
            ParameterSetIterator parameterIt = parameterIds.ForwardIterator();

            while (parameterIt.MoveNext())
            {
                Parameter parameter = parameterIt.Current as Parameter;
                if (parameter == null)
                {
                    continue;
                }

                if (IsDuplicateParameter(parameter))
                {
                    continue;
                }

                Definition paramDefinition = parameter.Definition;
                if (paramDefinition == null)
                {
                    continue;
                }

                // Don't cache parameters that aren't visible to the user.
                InternalDefinition internalDefinition = paramDefinition as InternalDefinition;
                if (internalDefinition != null && internalDefinition.Visible == false)
                {
                    continue;
                }

                if (string.IsNullOrWhiteSpace(paramDefinition.Name))
                {
                    continue;
                }

                string cleanPropertyName = NamingUtil.RemoveSpaces(paramDefinition.Name);

                BuiltInParameterGroup groupId = paramDefinition.ParameterGroup;
                if (groupId != BuiltInParameterGroup.PG_IFC)
                {
                    ParameterElementCache cacheForGroup = null;
                    if (!nonIFCParameters.TryGetValue(groupId, out cacheForGroup))
                    {
                        cacheForGroup             = new ParameterElementCache();
                        nonIFCParameters[groupId] = cacheForGroup;
                    }
                    cacheForGroup.ParameterCache[cleanPropertyName] = parameter;
                }
                else
                {
                    ifcParameters.ParameterCache[cleanPropertyName] = parameter;
                }
            }
        }
コード例 #48
0
 public override T BuildInstance(ISharingLifetimeScope scope, InjectionOperator <T> injectionOperator, ParameterSet parameters)
 {
     return(DoBuildInstance(scope, injectionOperator, parameters));
 }
コード例 #49
0
ファイル: ParameterUtil.cs プロジェクト: bimone/IFC-for-Revit
        /// <summary>
        /// Cache the parameters for an element, allowing quick access later.
        /// </summary>
        /// <param name="id">The element id.</param>
        static private void CacheParametersForElement(ElementId id)
        {
            if (id == ElementId.InvalidElementId)
            {
                return;
            }

            if (m_NonIFCParameters.ContainsKey(id))
            {
                return;
            }

            IDictionary <BuiltInParameterGroup, ParameterElementCache> nonIFCParameters = new SortedDictionary <BuiltInParameterGroup, ParameterElementCache>();
            ParameterElementCache ifcParameters = new ParameterElementCache();

            m_NonIFCParameters[id] = nonIFCParameters;
            m_IFCParameters[id]    = ifcParameters;

            Element element = ExporterCacheManager.Document.GetElement(id);

            if (element == null)
            {
                return;
            }

            ParameterSet parameterIds = element.Parameters;

            if (parameterIds.Size == 0)
            {
                return;
            }

            IDictionary <int, KeyValuePair <string, Parameter> > stableSortedParameterSet =
                new SortedDictionary <int, KeyValuePair <string, Parameter> >();

            // We will do two passes.  In the first pass, we will look at parameters in the IFC group.
            // In the second pass, we will look at all other groups.
            ParameterSetIterator parameterIt = parameterIds.ForwardIterator();

            while (parameterIt.MoveNext())
            {
                Parameter parameter = parameterIt.Current as Parameter;
                if (parameter == null)
                {
                    continue;
                }

                if (IsDuplicateParameter(parameter))
                {
                    continue;
                }

                Definition paramDefinition = parameter.Definition;
                if (paramDefinition == null)
                {
                    continue;
                }

                // Don't cache parameters that aren't visible to the user.
                InternalDefinition internalDefinition = paramDefinition as InternalDefinition;
                if (internalDefinition != null && internalDefinition.Visible == false)
                {
                    continue;
                }

                string name = paramDefinition.Name;
                if (string.IsNullOrWhiteSpace(name))
                {
                    continue;
                }

                stableSortedParameterSet[parameter.Id.IntegerValue] = new KeyValuePair <string, Parameter>(name, parameter);
            }

            foreach (KeyValuePair <string, Parameter> stableSortedParameter in stableSortedParameterSet.Values)
            {
                Parameter  parameter         = stableSortedParameter.Value;
                Definition paramDefinition   = parameter.Definition;
                string     cleanPropertyName = NamingUtil.RemoveSpaces(stableSortedParameter.Key);

                BuiltInParameterGroup groupId       = paramDefinition.ParameterGroup;
                ParameterElementCache cacheForGroup = null;

                if (groupId != BuiltInParameterGroup.PG_IFC)
                {
                    if (!nonIFCParameters.TryGetValue(groupId, out cacheForGroup))
                    {
                        cacheForGroup             = new ParameterElementCache();
                        nonIFCParameters[groupId] = cacheForGroup;
                    }
                }
                else
                {
                    cacheForGroup = ifcParameters;
                }

                if (cacheForGroup != null)
                {
                    // We may have situations (due to bugs) where a parameter with the same name appears multiple times.
                    // In this case, we will preserve the first parameter with a value.
                    // Note that this can still cause inconsistent behavior in the case where multiple parameters with the same
                    // name have values, and we should warn about that when we start logging.
                    if (!cacheForGroup.ParameterCache.ContainsKey(cleanPropertyName) ||
                        !cacheForGroup.ParameterCache[cleanPropertyName].HasValue)
                    {
                        cacheForGroup.ParameterCache[cleanPropertyName] = parameter;
                    }
                }
            }
        }
コード例 #50
0
        /// <summary>
        /// Helper method that checks the signature of a TestMethod and
        /// any supplied parameters to determine if the test is valid.
        ///
        /// Currently, NUnitTestMethods are required to be public,
        /// non-abstract methods, either static or instance,
        /// returning void. They may take arguments but the values must
        /// be provided or the TestMethod is not considered runnable.
        ///
        /// Methods not meeting these criteria will be marked as
        /// non-runnable and the method will return false in that case.
        /// </summary>
        /// <param name="testMethod">The TestMethod to be checked. If it
        /// is found to be non-runnable, it will be modified.</param>
        /// <param name="parms">Parameters to be used for this test, or null</param>
        /// <returns>True if the method signature is valid, false if not</returns>
        private static bool CheckTestMethodSignature(TestMethod testMethod, ParameterSet parms)
        {
            if (testMethod.Method.IsAbstract)
            {
                testMethod.RunState     = RunState.NotRunnable;
                testMethod.IgnoreReason = "Method is abstract";
                return(false);
            }

            if (!testMethod.Method.IsPublic)
            {
                testMethod.RunState     = RunState.NotRunnable;
                testMethod.IgnoreReason = "Method is not public";
                return(false);
            }

            ParameterInfo[] parameters = testMethod.Method.GetParameters();
            int             argsNeeded = parameters.Length;

            object[] arglist      = null;
            int      argsProvided = 0;

            if (parms != null)
            {
                testMethod.arguments         = parms.Arguments;
                testMethod.hasExpectedResult = parms.HasExpectedResult;
                if (testMethod.hasExpectedResult)
                {
                    testMethod.expectedResult = parms.Result;
                }
                testMethod.RunState         = parms.RunState;
                testMethod.IgnoreReason     = parms.IgnoreReason;
                testMethod.BuilderException = parms.ProviderException;

                arglist = parms.Arguments;

                if (arglist != null)
                {
                    argsProvided = arglist.Length;
                }

                if (testMethod.RunState != RunState.Runnable)
                {
                    return(false);
                }
            }


#if CLR_2_0 || CLR_4_0
            bool isAsyncMethod           = Reflect.IsAsyncMethod(testMethod.Method);
            bool hasMeaningfulReturnType = isAsyncMethod ? testMethod.Method.ReturnType.IsGenericType : testMethod.Method.ReturnType != typeof(void);
#else
            bool hasMeaningfulReturnType = testMethod.Method.ReturnType != typeof(void);
#endif

            if (hasMeaningfulReturnType && (parms == null || !parms.HasExpectedResult && parms.ExpectedExceptionName == null))
            {
                return(MarkAsNotRunnable(testMethod, "Test method has non-void return type, but no result is expected"));
            }
            if (!hasMeaningfulReturnType && parms != null && parms.HasExpectedResult)
            {
                return(MarkAsNotRunnable(testMethod, "Test method has void return type, but a result is expected"));
            }

            if (argsProvided > 0 && argsNeeded == 0)
            {
                return(MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any"));
            }

            if (argsProvided == 0 && argsNeeded > 0)
            {
                return(MarkAsNotRunnable(testMethod, "No arguments were provided"));
            }

            //if (argsProvided > argsNeeded)
            //{
            //    ParameterInfo lastParameter = parameters[argsNeeded - 1];
            //    Type lastParameterType = lastParameter.ParameterType;

            //    if (lastParameterType.IsArray && lastParameter.IsDefined(typeof(ParamArrayAttribute), false))
            //    {
            //        object[] newArglist = new object[argsNeeded];
            //        for (int i = 0; i < argsNeeded; i++)
            //            newArglist[i] = arglist[i];

            //        int length = argsProvided - argsNeeded + 1;
            //        Array array = Array.CreateInstance(lastParameterType.GetElementType(), length);
            //        for (int i = 0; i < length; i++)
            //            array.SetValue(arglist[argsNeeded + i - 1], i);

            //        newArglist[argsNeeded - 1] = array;
            //        testMethod.arguments = arglist = newArglist;
            //        argsProvided = argsNeeded;
            //    }
            //}

            if (argsProvided != argsNeeded)
            {
                testMethod.RunState     = RunState.NotRunnable;
                testMethod.IgnoreReason = "Wrong number of arguments provided";
                return(false);
            }

#if CLR_2_0 || CLR_4_0
            if (testMethod.Method.IsGenericMethodDefinition)
            {
                Type[] typeArguments = GetTypeArgumentsForMethod(testMethod.Method, arglist);
                foreach (object o in typeArguments)
                {
                    if (o == null)
                    {
                        testMethod.RunState     = RunState.NotRunnable;
                        testMethod.IgnoreReason = "Unable to determine type arguments for fixture";
                        return(false);
                    }
                }

                testMethod.method = testMethod.Method.MakeGenericMethod(typeArguments);
                parameters        = testMethod.Method.GetParameters();

                for (int i = 0; i < parameters.Length; i++)
                {
                    if (arglist[i].GetType() != parameters[i].ParameterType && arglist[i] is IConvertible)
                    {
                        try
                        {
                            arglist[i] = Convert.ChangeType(arglist[i], parameters[i].ParameterType);
                        }
                        catch (Exception)
                        {
                            // Do nothing - the incompatible argument will be reported below
                        }
                    }
                }
            }
#endif

            return(true);
        }
コード例 #51
0
 internal override void BuildInstance(ISharingLifetimeScope scope, ParameterSet parameters, out T instance)
 {
     DoBuildInstance(scope, parameters, out instance);
 }
            /// <summary>
            /// Gets OLTP report data.
            /// </summary>
            /// <param name="request">The request with report configuration, locale and settings.</param>
            /// <returns><see cref="ReportDataSet"/> object.</returns>
            private SingleEntityDataServiceResponse <ReportDataSet> GetOLTPReportData(GetOLTPReportDataRequest request)
            {
                ThrowIf.Null(request.ReportConfiguration, "Parameters are empty.");

                ReportConfiguration config        = request.ReportConfiguration;
                ParameterSet        sqlParameters = new ParameterSet();

                // Add channel id and user id to report parameters.
                if (config.Parameters != null && config.Parameters.Any())
                {
                    foreach (CommerceProperty parameter in config.Parameters)
                    {
                        sqlParameters[parameter.Key] = parameter.Value.GetPropertyValue();
                    }
                }

                sqlParameters[ParamChannelId] = request.RequestContext.GetPrincipal().ChannelId;
                if (config.IsUserBasedReport)
                {
                    sqlParameters[ParamUserId] = request.RequestContext.GetPrincipal().UserId;
                }

                DataSet outputDataSet;

                using (SqlServerDatabaseContext sqlServerDatabaseContext = new SqlServerDatabaseContext(request))
                {
                    outputDataSet = sqlServerDatabaseContext.ExecuteQueryDataSet(config.Query, sqlParameters);
                }

                ReportDataSet reportDataSet = null;

                if (outputDataSet != null && outputDataSet.Tables.Count == 1)
                {
                    // Get localized strings for the report.
                    if (this.LocalizedStrings == null)
                    {
                        this.LocalizedStrings = this.GetLocalizedReportsStrings(request.RequestContext, request.QueryResultSettings);
                    }

                    outputDataSet.Tables[0].TableName = OutputTableName;
                    if (outputDataSet.Tables[0].Columns.Count > 0)
                    {
                        foreach (DataColumn column in outputDataSet.Tables[0].Columns)
                        {
                            column.ColumnName = this.GetLocalizedLabel(column.ColumnName);
                        }
                    }

                    reportDataSet = new ReportDataSet
                    {
                        ReportId      = config.ReportId,
                        Locale        = request.RequestContext.LanguageId,
                        Parameters    = config.Parameters,
                        HasTotalRow   = config.HasTotalRow,
                        HasDisclaimer = config.HasDisclaimer,
                        Output        = this.ConvertDataTableToCollection(outputDataSet.Tables[0])
                    };
                }

                return(new SingleEntityDataServiceResponse <ReportDataSet>(reportDataSet));
            }
コード例 #53
0
 internal override void BuildInstance(ISharingLifetimeScope scope, ParameterSet parameters, out T instance)
 {
     instance = _lifetime.BuildInstance(scope, this, parameters);
 }
コード例 #54
0
        /// <summary>
        /// Exports a Rebar to IFC ReinforcingBar.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC object.</param>
        /// <param name="rebarItem">The rebar to be exported.  This might be an element or a sub-element.</param>
        /// <param name="rebarElement">The element that contains the rebar to be exported.  This may be the same as rebarItem.</param>
        /// <param name="itemIndex">If greater than 0, the index of the first rebar in the rebarItem in the rebarElement, used for naming and GUID creation.</param>
        /// <param name="productWrapper">The ProductWrapper object.</param>
        /// <returns>The set of handles created, to add to the ProductWrapper in the calling function.</returns>
        private static ISet <DelayedProductWrapper> ExportRebar(ExporterIFC exporterIFC, object rebarItem, Element rebarElement, int itemIndex, ProductWrapper productWrapper)
        {
            // Check the intended IFC entity or type name is in the exclude list specified in the UI
            Common.Enums.IFCEntityType elementClassTypeEnum = Common.Enums.IFCEntityType.IfcReinforcingBar;
            if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum))
            {
                return(null);
            }

            IFCFile file = exporterIFC.GetFile();
            HashSet <DelayedProductWrapper> createdRebars = new HashSet <DelayedProductWrapper>();

            int rebarQuantity = GetRebarQuantity(rebarItem);

            if (rebarQuantity == 0)
            {
                return(null);
            }

            using (IFCTransaction transaction = new IFCTransaction(file))
            {
                using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, rebarElement))
                {
                    bool         cannotExportRebar = false;
                    IFCAnyHandle rebarHandle       = ExportRebarAsProxyElementInView(exporterIFC, rebarElement, productWrapper, out cannotExportRebar);
                    if (!IFCAnyHandleUtil.IsNullOrHasNoValue(rebarHandle) || cannotExportRebar)
                    {
                        if (!cannotExportRebar)
                        {
                            transaction.Commit();
                        }
                        return(null); // Rebar doesn't create a group.
                    }

                    IFCAnyHandle prodRep = null;

                    double totalBarLengthUnscale = GetRebarTotalLength(rebarItem);
                    double volumeUnscale         = GetRebarVolume(rebarItem);
                    double totalBarLength        = UnitUtil.ScaleLength(totalBarLengthUnscale);

                    if (MathUtil.IsAlmostZero(totalBarLength))
                    {
                        return(null);
                    }

                    ElementId materialId = ElementId.InvalidElementId;
                    ParameterUtil.GetElementIdValueFromElementOrSymbol(rebarElement, BuiltInParameter.MATERIAL_ID_PARAM, out materialId);

                    double diameter = GetBarDiameter(rebarItem);
                    double radius   = diameter / 2.0;
                    double longitudinalBarNominalDiameter  = diameter;
                    double longitudinalBarCrossSectionArea = UnitUtil.ScaleArea(volumeUnscale / totalBarLengthUnscale);

                    int numberOfBarPositions = GetNumberOfBarPositions(rebarItem);

                    string steelGrade = NamingUtil.GetOverrideStringValue(rebarElement, "SteelGrade", null);

                    // Allow use of IFC2x3 or IFC4 naming.
                    string predefinedType = NamingUtil.GetOverrideStringValue(rebarElement, "BarRole", null);
                    if (string.IsNullOrWhiteSpace(predefinedType))
                    {
                        predefinedType = NamingUtil.GetOverrideStringValue(rebarElement, "PredefinedType", null);
                    }
                    IFCReinforcingBarRole role = GetReinforcingBarRole(predefinedType);

                    string origRebarName = NamingUtil.GetNameOverride(rebarElement, NamingUtil.GetIFCName(rebarElement));

                    const int maxBarGUIDS = IFCReinforcingBarSubElements.BarEnd - IFCReinforcingBarSubElements.BarStart + 1;
                    ElementId categoryId  = CategoryUtil.GetSafeCategoryId(rebarElement);

                    IFCAnyHandle originalPlacement = setter.LocalPlacement;

                    // Potential issue : totalBarLength has a rounded value but individual lengths (from centerlines) do not have rounded values.
                    // Also dividing a rounded totalBarLength does not result in barLength rounded by the same round value.
                    double        barLength  = totalBarLength / rebarQuantity;
                    IList <Curve> baseCurves = GetRebarCenterlineCurves(rebarItem, true, false, false);

                    ElementId    barLengthParamId   = new ElementId(BuiltInParameter.REBAR_ELEM_LENGTH);
                    ParameterSet rebarElementParams = rebarElement.Parameters;
                    for (int ii = 0; ii < numberOfBarPositions; ii++)
                    {
                        if (!DoesBarExistAtPosition(rebarItem, ii))
                        {
                            continue;
                        }

                        Rebar rebar = rebarElement as Rebar;
                        if ((rebar != null) && (rebar.DistributionType == DistributionType.VaryingLength || rebar.IsRebarFreeForm()))
                        {
                            baseCurves = GetRebarCenterlineCurves(rebar, true, false, false, MultiplanarOption.IncludeOnlyPlanarCurves, ii);
                            DoubleParameterValue barLengthParamVal = rebar.GetParameterValueAtIndex(barLengthParamId, ii) as DoubleParameterValue;
                            if (barLengthParamVal != null)
                            {
                                barLength = barLengthParamVal.Value;
                            }
                        }


                        string rebarNameFormated = origRebarName;
                        if (rebar != null && rebar.CanBeMatchedWithMultipleShapes())
                        {
                            string shapeName   = getShapeNameAtIndex(rebar, ii);
                            string elementName = rebar.Name;
                            string strVaries   = "";
                            if (!elementName.Contains(shapeName))
                            {
                                // it means that element name contains "Shape Varies"

                                // get "Varies" string from elem name
                                for (int iChar = elementName.Length - 1; iChar > 0; iChar--)
                                {
                                    if (elementName[iChar] == ' ')
                                    {
                                        break;
                                    }
                                    strVaries = strVaries.Insert(0, elementName[iChar].ToString());
                                }

                                // Replace "Varies" with shape name.
                                rebarNameFormated = origRebarName.Replace(strVaries, shapeName);
                            }
                        }

                        int indexForNamingAndGUID = (itemIndex > 0) ? ii + itemIndex : ii + 1;

                        string rebarName = NamingUtil.GetNameOverride(rebarElement, rebarNameFormated + ": " + indexForNamingAndGUID);

                        Transform barTrf = GetBarPositionTransform(rebarItem, ii);

                        IList <Curve> curves   = new List <Curve>();
                        double        endParam = 0.0;
                        foreach (Curve baseCurve in baseCurves)
                        {
                            if (baseCurve is Arc || baseCurve is Ellipse)
                            {
                                if (baseCurve.IsBound)
                                {
                                    endParam += UnitUtil.ScaleAngle(baseCurve.GetEndParameter(1) - baseCurve.GetEndParameter(0));
                                }
                                else
                                {
                                    endParam += UnitUtil.ScaleAngle(2 * Math.PI);
                                }
                            }
                            else
                            {
                                endParam += 1.0;
                            }
                            curves.Add(baseCurve.CreateTransformed(barTrf));
                        }

                        IFCAnyHandle           compositeCurve = GeometryUtil.CreateCompositeCurve(exporterIFC, curves);
                        IFCAnyHandle           sweptDiskSolid = IFCInstanceExporter.CreateSweptDiskSolid(file, compositeCurve, radius, null, 0, endParam);
                        HashSet <IFCAnyHandle> bodyItems      = new HashSet <IFCAnyHandle>();
                        bodyItems.Add(sweptDiskSolid);

                        IFCAnyHandle         shapeRep  = RepresentationUtil.CreateAdvancedSweptSolidRep(exporterIFC, rebarElement, categoryId, exporterIFC.Get3DContextHandle("Body"), bodyItems, null);
                        IList <IFCAnyHandle> shapeReps = new List <IFCAnyHandle>();
                        shapeReps.Add(shapeRep);
                        prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, shapeReps);

                        IFCAnyHandle copyLevelPlacement = (ii == 0) ? originalPlacement : ExporterUtil.CopyLocalPlacement(file, originalPlacement);

                        string rebarGUID = (indexForNamingAndGUID < maxBarGUIDS) ?
                                           GUIDUtil.CreateSubElementGUID(rebarElement, indexForNamingAndGUID + (int)IFCReinforcingBarSubElements.BarStart - 1) :
                                           GUIDUtil.CreateGUID();
                        IFCAnyHandle elemHnd = IFCInstanceExporter.CreateReinforcingBar(exporterIFC, rebarElement, rebarGUID, ExporterCacheManager.OwnerHistoryHandle,
                                                                                        copyLevelPlacement, prodRep, steelGrade, longitudinalBarNominalDiameter, longitudinalBarCrossSectionArea, barLength, role, null);
                        IFCAnyHandleUtil.OverrideNameAttribute(elemHnd, rebarName);
                        IFCExportInfoPair exportInfo = new IFCExportInfoPair(IFCEntityType.IfcReinforcingBar);

                        // We will not add the element ot the productWrapper here, but instead in the function that calls
                        // ExportRebar.  The reason for this is that we don't currently know if the handles such be associated
                        // to the level or not, depending on whether they will or won't be grouped.
                        createdRebars.Add(new DelayedProductWrapper(rebarElement, elemHnd, setter.LevelInfo, exportInfo));

                        CacheSubelementParameterValues(rebarElement, rebarElementParams, ii, elemHnd);

                        ExporterCacheManager.HandleToElementCache.Register(elemHnd, rebarElement.Id);
                        CategoryUtil.CreateMaterialAssociation(exporterIFC, elemHnd, materialId);
                    }
                }
                transaction.Commit();
            }
            return(createdRebars);
        }
コード例 #55
0
        public void InferredPipelinesHashTest()
        {
            var context    = new MLContext(1);
            var columnInfo = new ColumnInformation();

            // test same learners with no hyperparameters have the same hash code
            var trainer1          = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo);
            var trainer2          = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo);
            var transforms1       = new List <SuggestedTransform>();
            var transforms2       = new List <SuggestedTransform>();
            var inferredPipeline1 = new SuggestedPipeline(transforms1, new List <SuggestedTransform>(), trainer1, context, false);
            var inferredPipeline2 = new SuggestedPipeline(transforms2, new List <SuggestedTransform>(), trainer2, context, false);

            Assert.Equal(inferredPipeline1.GetHashCode(), inferredPipeline2.GetHashCode());

            // test same learners with hyperparameters set vs empty hyperparameters have different hash codes
            var hyperparams1 = new ParameterSet(new List <IParameterValue>()
            {
                new LongParameterValue("NumberOfLeaves", 2)
            });

            trainer1          = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo, hyperparams1);
            trainer2          = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo);
            inferredPipeline1 = new SuggestedPipeline(transforms1, new List <SuggestedTransform>(), trainer1, context, false);
            inferredPipeline2 = new SuggestedPipeline(transforms2, new List <SuggestedTransform>(), trainer2, context, false);
            Assert.NotEqual(inferredPipeline1.GetHashCode(), inferredPipeline2.GetHashCode());

            // same learners with different hyperparameters
            hyperparams1 = new ParameterSet(new List <IParameterValue>()
            {
                new LongParameterValue("NumberOfLeaves", 2)
            });
            var hyperparams2 = new ParameterSet(new List <IParameterValue>()
            {
                new LongParameterValue("NumberOfLeaves", 6)
            });

            trainer1          = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo, hyperparams1);
            trainer2          = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo, hyperparams2);
            inferredPipeline1 = new SuggestedPipeline(transforms1, new List <SuggestedTransform>(), trainer1, context, false);
            inferredPipeline2 = new SuggestedPipeline(transforms2, new List <SuggestedTransform>(), trainer2, context, false);
            Assert.NotEqual(inferredPipeline1.GetHashCode(), inferredPipeline2.GetHashCode());

            // same learners with same transforms
            trainer1    = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo);
            trainer2    = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo);
            transforms1 = new List <SuggestedTransform>()
            {
                ColumnConcatenatingExtension.CreateSuggestedTransform(context, new[] { "In" }, "Out")
            };
            transforms2 = new List <SuggestedTransform>()
            {
                ColumnConcatenatingExtension.CreateSuggestedTransform(context, new[] { "In" }, "Out")
            };
            inferredPipeline1 = new SuggestedPipeline(transforms1, new List <SuggestedTransform>(), trainer1, context, false);
            inferredPipeline2 = new SuggestedPipeline(transforms2, new List <SuggestedTransform>(), trainer2, context, false);
            Assert.Equal(inferredPipeline1.GetHashCode(), inferredPipeline2.GetHashCode());

            // same transforms with different learners
            trainer1    = new SuggestedTrainer(context, new SdcaLogisticRegressionBinaryExtension(), columnInfo);
            trainer2    = new SuggestedTrainer(context, new LightGbmBinaryExtension(), columnInfo);
            transforms1 = new List <SuggestedTransform>()
            {
                ColumnConcatenatingExtension.CreateSuggestedTransform(context, new[] { "In" }, "Out")
            };
            transforms2 = new List <SuggestedTransform>()
            {
                ColumnConcatenatingExtension.CreateSuggestedTransform(context, new[] { "In" }, "Out")
            };
            inferredPipeline1 = new SuggestedPipeline(transforms1, new List <SuggestedTransform>(), trainer1, context, false);
            inferredPipeline2 = new SuggestedPipeline(transforms2, new List <SuggestedTransform>(), trainer2, context, false);
            Assert.NotEqual(inferredPipeline1.GetHashCode(), inferredPipeline2.GetHashCode());
        }
コード例 #56
0
ファイル: CMD.cs プロジェクト: inktan/RevitApi_
        public ElementId ChangeTypeKeepParameter(Element elem_old, ElementType type)
        {
            Document  doc           = elem_old.Document;
            ElementId id_newelement = null;
            //复制图元(偏移一段距离,跳过警告窗口)=>参数转移=>偏移回原位=>删除原有图元.
            ICollection <ElementId> ids_newelement = ElementTransformUtils.CopyElement(doc, elem_old.Id, new XYZ(1, 0, 0));

            if (ids_newelement.Count != 1)
            {
                return(null);
            }
            id_newelement = ids_newelement.First();
            Element elem_new = doc.GetElement(id_newelement);

            elem_new.ChangeTypeId(type.Id);
            //parameter
            ParameterSet parameterSet = elem_old.Parameters;

            foreach (Parameter para_oldelem in parameterSet)
            {
                if (para_oldelem.IsReadOnly)
                {
                    continue;
                }
                if (!para_oldelem.HasValue)
                {
                    continue;
                }
                if (para_oldelem.StorageType == StorageType.None)
                {
                    continue;
                }
                if (para_oldelem.StorageType == StorageType.ElementId)
                {
                    continue;
                }

                Parameter para_newelem = elem_new.LookupParameter(para_oldelem.Definition.Name);
                if (para_newelem.IsReadOnly)
                {
                    continue;
                }
                if (!para_newelem.HasValue)
                {
                    continue;
                }
                if (para_newelem.StorageType == StorageType.None)
                {
                    continue;
                }
                if (para_newelem.StorageType == StorageType.ElementId)
                {
                    continue;
                }
                if (para_newelem.StorageType == StorageType.Double)
                {
                    para_newelem.Set(para_oldelem.AsDouble());
                }
                if (para_newelem.StorageType == StorageType.Integer)
                {
                    para_newelem.Set(para_oldelem.AsInteger());
                }
                if (para_newelem.StorageType == StorageType.String)
                {
                    para_newelem.Set(para_oldelem.AsValueString());
                }
            }
            doc.Delete(elem_old.Id);
            ElementTransformUtils.MoveElement(doc, id_newelement, new XYZ(-1, 0, 0));
            return(id_newelement);
        }
コード例 #57
0
        //method to align created element
        public static bool AdjustElement(Document m_document, Element createdInstance,
                                         XYZ instancePoint, Pipe pipeElement, double rodLength, Curve pipeCurve)
        {
            bool rod = false, radius = false;

            try
            {
                if (pipeCurve is Line)
                {
                    Line pipeLine = (Line)pipeCurve;

                    //axis to find the y angle
                    Line yAngleAxis = Line.CreateBound(pipeLine.GetEndPoint(0), new XYZ(pipeLine.GetEndPoint(1).X, pipeLine.GetEndPoint(1).Y, pipeLine.GetEndPoint(0).Z));

                    double yAngle = XYZ.BasisY.AngleTo(yAngleAxis.Direction);

                    //axis of rotation
                    Line axis = Line.CreateBound(instancePoint, new XYZ(instancePoint.X, instancePoint.Y, instancePoint.Z + 10));

                    if (pipeCurve.GetEndPoint(0).Y > pipeCurve.GetEndPoint(1).Y)
                    {
                        if (pipeCurve.GetEndPoint(0).X > pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, Math.PI + yAngle);
                        }
                        else if (pipeCurve.GetEndPoint(0).X < pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, 2 * Math.PI - yAngle);
                        }
                    }
                    else if (pipeCurve.GetEndPoint(0).Y < pipeCurve.GetEndPoint(1).Y)
                    {
                        if (pipeCurve.GetEndPoint(0).X > pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, Math.PI + yAngle);
                        }
                        else if (pipeCurve.GetEndPoint(0).X < pipeCurve.GetEndPoint(1).X)
                        {
                            //rotate the created family instance to align with the pipe
                            ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, 2 * Math.PI - yAngle);
                        }
                    }
                    else
                    {
                        //rotate the created family instance to align with the pipe
                        ElementTransformUtils.RotateElement(m_document, createdInstance.Id, axis, yAngle);
                    }

                    ParameterSet parameters = createdInstance.Parameters;

                    //set the Nominal radius and Rod height parameters
                    foreach (Parameter para in parameters)
                    {
                        if (para.Definition.Name == "PIPE RADIUS")
                        {
                            para.Set(pipeElement.get_Parameter("Outside Diameter").AsDouble() / 2.0);
                            radius = true;
                        }
                        else if (para.Definition.Name == "ROD LENGTH")
                        {
                            para.Set(rodLength);
                            rod = true;
                        }
                    }
                }
            }
            catch
            {
                return(false);
            }

            if (rod == true && radius == true)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #58
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            if (!doc.IsFamilyDocument)
            {
                message =
                    "Please run this command in a family document.";
            }
            else
            {
                FamilyManager mgr = doc.FamilyManager;

                int n = mgr.Parameters.Size;

                Debug.Print(
                    "\nFamily {0} has {1} parameter{2}.",
                    doc.Title, n, Util.PluralSuffix(n));

                Dictionary <string, FamilyParameter> fps
                    = new Dictionary <string, FamilyParameter>(n);

                foreach (FamilyParameter fp in mgr.Parameters)
                {
                    string name = fp.Definition.Name;
                    fps.Add(name, fp);

                    #region Look at associated parameters
#if LOOK_AT_ASSOCIATED_PARAMETERS
                    ParameterSet ps = fp.AssociatedParameters;
                    n = ps.Size;

                    string values = string.Empty;
                    foreach (Parameter p in ps)
                    {
                        if (0 == values.Length)
                        {
                            values = " ";
                        }
                        else
                        {
                            values += ", ";
                        }
                        values += p.AsValueString();
                    }

                    Debug.Print(
                        "Parameter {0} has {1} associated parameter{2}{3}{4}.",
                        name,
                        n,
                        PluralSuffix(n),
                        (0 < n ? ":" : ""),
                        values);
#endif // LOOK_AT_ASSOCIATED_PARAMETERS
                    #endregion // Look at associated parameters
                }
                List <string> keys = new List <string>(fps.Keys);
                keys.Sort();

                n = mgr.Types.Size;

                Debug.Print(
                    "Family {0} has {1} type{2}{3}",
                    doc.Title,
                    n,
                    Util.PluralSuffix(n),
                    Util.DotOrColon(n));

                foreach (FamilyType t in mgr.Types)
                {
                    string name = t.Name;
                    Debug.Print("  {0}:", name);
                    foreach (string key in keys)
                    {
                        FamilyParameter fp = fps[key];
                        if (t.HasValue(fp))
                        {
                            string value
                                = FamilyParamValueString(t, fp, doc);

                            Debug.Print("    {0} = {1}", key, value);
                        }
                    }
                }
            }

            #region Exercise ExtractPartAtomFromFamilyFile

            // by the way, here is a completely different way to
            // get at all the parameter values, and all the other
            // family information as well:

            bool exercise_this_method = false;

            if (doc.IsFamilyDocument && exercise_this_method)
            {
                string path = doc.PathName;
                if (0 < path.Length)
                {
                    app.Application.ExtractPartAtomFromFamilyFile(
                        path, path + ".xml");
                }
            }
            #endregion // Exercise ExtractPartAtomFromFamilyFile

            return(Result.Failed);
        }
コード例 #59
0
        /// <summary>
        /// Return an IEnumerable providing test cases for use in
        /// running a parameterized test.
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public IEnumerable GetTestCasesFor(MethodInfo method, Test parentSuite)
        {
            ArrayList parameterList = new ArrayList();

            foreach (ProviderReference providerReference in GetSourcesFor(method, parentSuite))
            {
                foreach (object source in providerReference.GetInstance())
                {
                    ParameterSet parms;

                    if (source == null)
                    {
                        parms           = new ParameterSet();
                        parms.Arguments = new object[] { null };
                    }
                    else
                    {
                        parms = source as ParameterSet;
                    }

                    if (parms == null)
                    {
                        Type sourceType = source.GetType();

                        if (sourceType.GetInterface("NUnit.Framework.ITestCaseData") != null ||
                            sourceType.GetInterface("NUnit.Framework.Api.ITestCaseData") != null)
                        {
                            parms = ParameterSet.FromDataSource(source);
                        }
                        else
                        {
                            parms = new ParameterSet();

                            ParameterInfo[] parameters = method.GetParameters();

                            if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(sourceType))
                            {
                                parms.Arguments = new object[] { source }
                            }
                            ;
                            else if (source is object[])
                            {
                                parms.Arguments = (object[])source;
                            }
                            else if (source is Array)
                            {
                                Array array = (Array)source;
                                if (array.Rank == 1)
                                {
                                    parms.Arguments = new object[array.Length];
                                    for (int i = 0; i < array.Length; i++)
                                    {
                                        parms.Arguments[i] = (object)array.GetValue(i);
                                    }
                                }
                            }
                            else
                            {
                                parms.Arguments = new object[] { source }
                            };
                        }
                    }


                    // This is the only point we can easily check the individual returned
                    // ParameterSet items from a TestCaseSourceAttribute.
                    if (parms.ExpectedExceptionName != null)
                    {
                        Compatibility.Error(providerReference.ProviderLocation,
                                            "TestCaseSourceAttribute does not support ExpectedException in NUnit 3. Use Assert.Throws or ThrowsConstraint.");
                    }
                    if (parms.RunState == RunState.Ignored && string.IsNullOrEmpty(parms.IgnoreReason))
                    {
                        Compatibility.Error(providerReference.ProviderLocation,
                                            "TestCaseSourceAttribute requires a reason when case is ignored in NUnit 3.");
                    }

                    if (providerReference.ProviderCategory != null)
                    {
                        foreach (string cat in providerReference.ProviderCategory.Split(new char[] { ',' }))
                        {
                            parms.Categories.Add(cat);
                        }
                    }

                    parameterList.Add(parms);
                }
            }

            return(parameterList);
        }
コード例 #60
0
        /// <summary>
        /// Return an IEnumerable providing test cases for use in
        /// running a parameterized test.
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public IEnumerable GetTestCasesFor(MethodInfo method, Test parentSuite)
        {
            ArrayList parameterList = new ArrayList();

            foreach (ProviderReference info in GetSourcesFor(method, parentSuite))
            {
                foreach (object source in info.GetInstance())
                {
                    ParameterSet parms;

                    if (source == null)
                    {
                        parms           = new ParameterSet();
                        parms.Arguments = new object[] { null };
                    }
                    else
                    {
                        parms = source as ParameterSet;
                    }

                    if (parms == null)
                    {
                        if (source.GetType().GetInterface("NUnit.Framework.ITestCaseData") != null)
                        {
                            parms = ParameterSet.FromDataSource(source);
                        }
                        else
                        {
                            parms = new ParameterSet();

                            ParameterInfo[] parameters = method.GetParameters();
                            Type            sourceType = source.GetType();

                            if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(sourceType))
                            {
                                parms.Arguments = new object[] { source }
                            }
                            ;
                            else if (source is object[])
                            {
                                parms.Arguments = (object[])source;
                            }
                            else if (source is Array)
                            {
                                Array array = (Array)source;
                                if (array.Rank == 1)
                                {
                                    parms.Arguments = new object[array.Length];
                                    for (int i = 0; i < array.Length; i++)
                                    {
                                        parms.Arguments[i] = (object)array.GetValue(i);
                                    }
                                }
                            }
                            else
                            {
                                parms.Arguments = new object[] { source }
                            };
                        }
                    }

                    if (info.Category != null)
                    {
                        foreach (string cat in info.Category.Split(new char[] { ',' }))
                        {
                            parms.Categories.Add(cat);
                        }
                    }

                    parameterList.Add(parms);
                }
            }

            return(parameterList);
        }