Exemple #1
0
        /// <summary>
        /// Replace a number slider with one that has the proper values set.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void OnParameterSourcesChanged(Object sender, GH_ParamServerEventArgs e)
        {
            int       index = e.ParameterIndex;
            IGH_Param param = e.Parameter;

            //Trigger data collection
            if (param.Name == "Robot" | param.Name == "Instructions")
            {
                newData = true;
            }

            //Only add value list to the first input
            if (param.Name != "*Timeline")
            {
                return;
            }

            //Only change value lists
            var extractedItems = param.Sources.Where(p => p.Name == "Number Slider");

            //Set up the number slider
            Grasshopper.Kernel.Special.GH_NumberSlider gH_NumberSlider = Canvas.Component.CreateNumbersilder("Timeline", 0, 1m, 4, 400);

            //The magic
            Canvas.Component.ChangeObjects(extractedItems, gH_NumberSlider);
        }
Exemple #2
0
        public static void ReinstateGenome(ChihuahuaComponent comp, List <decimal> Ngenome)
        {
            GH_Document docu = comp.OnPingDocument();

            //Change value of sliders
            IList <IGH_Param> sliders = comp.Params.Input[0].Sources;

            List <decimal> genome = new List <decimal>();

            if (sliders.Count != Ngenome.Count)
            {
                throw new System.ArgumentException("Numbers of genes not equal to number of sliders", "Genome");
            }

            for (int i = 0; i < sliders.Count; i++)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = sliders[i] as Grasshopper.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    decimal N_gene_value = Ngenome[i];
                    decimal gene_value   = N_gene_value.Remap(0, 1, slider.Slider.Minimum, slider.Slider.Maximum);
                    slider.SetSliderValue(gene_value);
                    genome.Add(gene_value);
                }
            }


            // Get a new solution

            docu.NewSolution(false);
        }
Exemple #3
0
        public override GH_ObjectResponse RespondToMouseDoubleClick(GH_Canvas sender, GH_CanvasMouseEvent e)
        {
            RectangleF rec = GrabBound;

            if (rec.Contains(e.CanvasLocation))
            {
                Grasshopper.Kernel.Special.GH_NumberSlider hiddenSlider = new Grasshopper.Kernel.Special.GH_NumberSlider();
                hiddenSlider.Slider.Maximum       = (decimal)MaxValue;
                hiddenSlider.Slider.Minimum       = (decimal)MinValue;
                hiddenSlider.Slider.DecimalPlaces = noDigits;
                hiddenSlider.Slider.Type          = noDigits == 0 ? Grasshopper.GUI.Base.GH_SliderAccuracy.Integer : Grasshopper.GUI.Base.GH_SliderAccuracy.Float;
                hiddenSlider.Name         = Owner.Name + " Slider";
                hiddenSlider.Slider.Value = (decimal)CurrentValue;
                Grasshopper.GUI.GH_NumberSliderPopup gH_MenuSliderForm = new Grasshopper.GUI.GH_NumberSliderPopup();
                GH_WindowsFormUtil.CenterFormOnCursor(gH_MenuSliderForm, true);
                gH_MenuSliderForm.Setup(hiddenSlider);
                //hiddenSlider.PopupEditor();
                var res = gH_MenuSliderForm.ShowDialog();
                if (res == DialogResult.OK)
                {
                    first        = true;
                    MaxValue     = (double)hiddenSlider.Slider.Maximum;
                    MinValue     = (double)hiddenSlider.Slider.Minimum;
                    CurrentValue = (double)hiddenSlider.Slider.Value;
                    noDigits     = hiddenSlider.Slider.Type == Grasshopper.GUI.Base.GH_SliderAccuracy.Integer ? 0 : hiddenSlider.Slider.DecimalPlaces;
                    ChangeMaxMin(MaxValue, MinValue);
                    Owner.OnDisplayExpired(false);
                    Owner.ExpireSolution(true);
                    return(GH_ObjectResponse.Handled);
                }
            }
            return(GH_ObjectResponse.Ignore);
        }
        public override Grasshopper.GUI.Canvas.GH_ObjectResponse RespondToMouseDoubleClick(Grasshopper.GUI.Canvas.GH_Canvas sender, Grasshopper.GUI.GH_CanvasMouseEvent e)
        {
            // Read in Cluster number slider
            List <IGH_Param> sliderListClust = new List <IGH_Param>();

            foreach (IGH_Param src2 in MyComponent.Params.Input[4].Sources)
            {
                sliderListClust.Add(src2);
            }
            Grasshopper.Kernel.Special.GH_NumberSlider clusterSlider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderListClust[0];

            //Set all cluster values
            if (MyComponent.ClusterDone)

            {
                DesignMapSorted   = MyComponent.DesignMapSorted;
                ClusterAves       = MyComponent.ClusterAves;
                ClusterMaxs       = MyComponent.ClusterMaxs;
                ClusterMins       = MyComponent.ClusterMins;
                ClusterLabelsList = MyComponent.ClusterLabelsList;
                int numVars = MyComponent.numVars;

                List <IGH_Param> sliderList = new List <IGH_Param>();

                foreach (IGH_Param src in MyComponent.Params.Input[0].Sources)
                {
                    sliderList.Add(src);
                }

                for (int i = 0; i < numVars; i++)
                {
                    // if input is not zero, reset sliders based on clusters properties
                    if (MyComponent.index != 0)
                    {
                        Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderList[i];

                        double adjmin = ClusterMins[MyComponent.index][i] + (1 - MyComponent.flexibility) * (ClusterAves[MyComponent.index][i] - ClusterMins[MyComponent.index][i]);
                        double adjmax = ClusterMaxs[MyComponent.index][i] - (1 - MyComponent.flexibility) * (ClusterMaxs[MyComponent.index][i] - ClusterAves[MyComponent.index][i]);

                        nslider.Slider.Minimum = ((decimal)adjmin);
                        nslider.Slider.Maximum = ((decimal)adjmax);
                        nslider.TrySetSliderValue((decimal)ClusterAves[MyComponent.index][i]);
                    }
                    else
                    {
                        Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderList[i];

                        nslider.Slider.Minimum = ((decimal)ClusterMins[MyComponent.index][i]);
                        nslider.Slider.Maximum = ((decimal)ClusterMaxs[MyComponent.index][i]);
                        nslider.TrySetSliderValue((decimal)ClusterAves[MyComponent.index][i]);
                    }
                }
            }

            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);

            return(base.RespondToMouseDoubleClick(sender, e));
        }
Exemple #5
0
            public Slider(Grasshopper.Kernel.Special.GH_NumberSlider slider, Plane p, string fontFace, double length, double textHeight, string name)
            {
                plane   = p;
                vMin    = (double)slider.Slider.Minimum;
                vMax    = (double)slider.Slider.Maximum;
                val     = (double)slider.CurrentValue;
                normVal = (val - vMin) / (vMax - vMin);

                range  = new Line(p.Origin, p.XAxis, length);
                sValue = new Line(p.Origin, p.XAxis, length * normVal);

                this.name       = name;
                this.textHeight = textHeight;
                this.fontFace   = fontFace;

                label        = new Rhino.Display.Text3d(name);
                label.Height = textHeight;

                Plane labPlane = new Plane(plane);

                labPlane.Translate(p.YAxis * -(textHeight * 1.8));
                label.TextPlane = labPlane;

                tMin = new Rhino.Display.Text3d(Convert.ToString(vMin));
                tMax = new Rhino.Display.Text3d(Convert.ToString(vMax));
                tVal = new Rhino.Display.Text3d(Convert.ToString(val));

                if (this.fontFace != "")
                {
                    tMin.FontFace  = this.fontFace;
                    tMax.FontFace  = this.fontFace;
                    tVal.FontFace  = this.fontFace;
                    label.FontFace = this.fontFace;
                }

                tMin.Height = textHeight;
                tMax.Height = textHeight;
                tVal.Height = textHeight * 1.2;
                Plane tPlane = new Plane(plane);

                tPlane.Translate(p.XAxis * -(textHeight * 0.8));
                tMin.TextPlane = tPlane;
                tPlane.Origin  = p.Origin + p.XAxis * length;
                tPlane.Translate(p.XAxis * (textHeight * 0.8));
                tMax.TextPlane = tPlane;
                tPlane.Origin  = p.Origin + p.XAxis * length * normVal;
                tPlane.Translate(p.YAxis * textHeight);
                tVal.TextPlane           = tPlane;
                tMin.HorizontalAlignment = Rhino.DocObjects.TextHorizontalAlignment.Right;
                tMax.HorizontalAlignment = Rhino.DocObjects.TextHorizontalAlignment.Left;
                tVal.HorizontalAlignment = Rhino.DocObjects.TextHorizontalAlignment.Center;
                tVal.Bold = true;
            }
Exemple #6
0
        public static Individual CreateIndividualFromNGenome(ChihuahuaComponent comp, List <decimal> Ngenome)
        {
            GH_Document docu = comp.OnPingDocument();

            //Change value of sliders
            IList <IGH_Param> sliders = comp.Params.Input[0].Sources;

            List <decimal> genome = new List <decimal>();

            if (sliders.Count != Ngenome.Count)
            {
                throw new System.ArgumentException("Numbers of genes not equal to number of sliders", "Genome");
            }

            for (int i = 0; i < sliders.Count; i++)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = sliders[i] as Grasshopper.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    decimal N_gene_value = Ngenome[i];
                    decimal gene_value   = N_gene_value.Remap(0, 1, slider.Slider.Minimum, slider.Slider.Maximum);
                    slider.SetSliderValue(gene_value);
                    genome.Add(gene_value);
                }
            }


            // Get a new solution

            docu.NewSolution(false);

            //Read new fitness value

            decimal fitness = 0;

            IGH_Param param = comp.Params.Input[1].Sources[0];
            GH_Structure <GH_Number> outcome = comp.Params.Input[1].Sources[0].VolatileData as GH_Structure <GH_Number>;

            if (outcome == null)
            {
                throw new System.ArgumentException("Fitness input is not a number", "Fitness");
            }
            if (outcome != null)
            {
                fitness = (decimal)outcome.Branches[0][0].Value;
            }

            Individual ind = new Individual(fitness, genome, Ngenome);

            return(ind);
        }
Exemple #7
0
        private bool MoveToNextPermutation(ref int index, List <GH.Kernel.Special.GH_NumberSlider> sliders)
        {
            if (index >= sliders.Count)
            {
                return(false);
            }

            GH.Kernel.Special.GH_NumberSlider slider = sliders[index];
            if (slider.TickValue < slider.TickCount)
            {
                //Figure out which step to fly to...

                //look up the current slider's current sliderStepsPosition and target number
                int totalNumberOfSteps         = sliderSteps[index];
                int currentSliderStepsPosition = sliderStepsPositions[index];
                int numTicksToAddPerStep       = slider.TickCount / totalNumberOfSteps;


                //find the closest tick
                int closestTick = numTicksToAddPerStep * currentSliderStepsPosition;

                // Increment the slider.
                slider.TickValue = closestTick;

                //Increment the current step position
                sliderStepsPositions[index]++;

                return(true);
            }
            else
            {
                // The current slider is already at the maximum value. Reset it back to zero.
                slider.TickValue = 0;

                //set our slider steps position back to 0
                sliderStepsPositions[index] = 0;

                // Move on to the next slider.
                index++;

                // If we've run out of sliders to modify, we're done permutatin'
                if (index >= sliders.Count)
                {
                    return(false);
                }

                return(MoveToNextPermutation(ref index, sliders));
            }
        }
Exemple #8
0
        public override Grasshopper.GUI.Canvas.GH_ObjectResponse RespondToMouseDoubleClick(Grasshopper.GUI.Canvas.GH_Canvas sender, Grasshopper.GUI.GH_CanvasMouseEvent e)
        {
            if (MyComponent.SlidersList.Count != MyComponent.DesignMap[MyComponent.Index].Count)
            {
                throw new Exception("Error: Number of sliders and number of target values must be equal.");
            }

            for (int i = 0; i < MyComponent.SlidersList.Count; i++)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider s = MyComponent.SlidersList[i];
                double d = MyComponent.DesignMap[MyComponent.Index][i];
                s.SetSliderValue((decimal)d);
            }

            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(false, GH_SolutionMode.Default);

            //Grasshopper.Instances.ActiveCanvas.Document.NewSolution(false);
            return(base.RespondToMouseDoubleClick(sender, e));
        }
Exemple #9
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Plane P = Plane.WorldXY;

            DA.GetData(1, ref P);
            if (P == null)
            {
                P = Plane.WorldXY;
            }
            from = P.Origin;
            double len = 0;

            DA.GetData(2, ref len);
            string fontFace = "";

            DA.GetData(3, ref fontFace);
            double th = 0;

            DA.GetData(4, ref th);
            idle   = Color.DarkGray;
            active = Color.Black;
            DA.GetData(5, ref idle);
            DA.GetData(6, ref active);

            basePlane = new Plane(P);
            yOffset   = basePlane.YAxis * (-th * 6);

            sliders = new List <Slider>();

            for (int i = 0; i < Params.Input[0].Sources.Count; i++)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = Params.Input[0].Sources[i] as Grasshopper.Kernel.Special.GH_NumberSlider;
                basePlane.Origin = from;
                slid             = new Slider(slider, basePlane, fontFace, len, th, slider.NickName);
                sliders.Add(slid);
                _clip.Union(slid.GetBoundingBox());
                from += yOffset;
            }
        }
Exemple #10
0
    private void SolutionCallback(GH_Document doc)
    {
        //read file, deserialize json, send variables out of the extracted class

        string     jsonstring = File.ReadAllText(_path);
        ParamsData paramdata  = new ParamsData();

        paramdata   = JsonConvert.DeserializeObject <ParamsData>(jsonstring);
        _n          = paramdata.NumSliders;
        _dataIn     = paramdata.SliderVals;
        _pointsdata = paramdata.Points;


        Random rnd = new Random();

        List <IGH_DocumentObject> deletions       = new List <IGH_DocumentObject>(); //list of objects to delete from grasshopper document
        List <OutputParam>        outputParams    = new List <OutputParam>();        //list of the slider grouping params and their output connections
        List <IGH_Param>          PointRecvParams = new List <IGH_Param>();          //list of what the point param is connected to

        foreach (IGH_DocumentObject obj in GrasshopperDocument.Objects)
        {
            if (obj.NickName.StartsWith(_controlComponentName)) //the point and integer params i've created
            {
                deletions.Add(obj);
                IGH_Param tempParam = obj as IGH_Param; //cast obj into a param to locate sources and recipients
                if (tempParam.SourceCount > 0)
                {
                    deletions.AddRange(tempParam.Sources); //add source sliders to deletions list
                }

                if (obj.NickName.StartsWith(_controlComponentName + "points"))
                {
                    foreach (IGH_Param recip in tempParam.Recipients)
                    {
                        PointRecvParams.Add(recip);
                    }
                }

                if (obj.NickName.StartsWith(_controlComponentName + "slids")) //the integer params
                {
                    int ObjectIndex;
                    Int32.TryParse(System.Text.RegularExpressions.Regex.Match(obj.NickName, @"(\d+)\z").Value, out ObjectIndex); //regex to extract index number from end of param name
                    List <IGH_Param> receivingParams = new List <IGH_Param>();
                    foreach (IGH_Param recip in tempParam.Recipients)
                    {
                        receivingParams.Add(recip);
                    }
                    outputParams.Add(new OutputParam(ObjectIndex, receivingParams)); //put output param index and recipients into an object in a list
                }
            }
        }

        foreach (IGH_DocumentObject delobj in deletions) //delete the stuff
        {
            GrasshopperDocument.RemoveObject(delobj, false);
        }

        List <Grasshopper.Kernel.Parameters.Param_Integer> targetParam = new List <Grasshopper.Kernel.Parameters.Param_Integer>(); //holds the new output params as we build them  //rename targetParam

        for (int index = 0; index < _n.Count; index++)                                                                             //this loop runs once per slider bank    //rename index

        {
            targetParam.Add(new Grasshopper.Kernel.Parameters.Param_Integer());    //create the new output param
            targetParam[index].NickName = _controlComponentName + "slids" + index; //assign the name to the output param including the index number
            GrasshopperDocument.AddObject(targetParam[index], false);

            if (index == 0) //put param in place
            {
                targetParam[index].Attributes.Pivot = new System.Drawing.PointF(Component.Attributes.Pivot.X + 20, Component.Attributes.Pivot.Y + 110);
            }
            else
            {
                _n[index] = _n[index] + _n[index - 1]; //aggregate list of number of sliders per bank to create slider index breakpoints
                targetParam[index].Attributes.Pivot = new System.Drawing.PointF(Component.Attributes.Pivot.X + 20, Component.Attributes.Pivot.Y + 110 + _n[index - 1] * 20 + index * 10);
            }

            if (outputParams.Exists(opar => opar.outParam == index)) //looks in the list of deleted output params and determines if one has the same index as the param being created
            {
                foreach (IGH_Param receivingParam in outputParams.Find(opar => opar.outParam == index).recvParams)
                {
                    receivingParam.AddSource(targetParam[index]); //connects the new param to the old param stuff
                }
            }
        }

        Grasshopper.Kernel.Parameters.Param_Point pointsParam = new Grasshopper.Kernel.Parameters.Param_Point();
        pointsParam.NickName = _controlComponentName + "points";
        GrasshopperDocument.AddObject(pointsParam, false);
        pointsParam.Attributes.Pivot = new System.Drawing.PointF(Component.Attributes.Pivot.X + 20, Component.Attributes.Pivot.Y + 70);
        foreach (IGH_Param receivingParam in PointRecvParams)
        {
            receivingParam.AddSource(pointsParam);
        }

        pointsParam.SetPersistentData(_pointsdata.ToArray());



        int Yoffset      = -12;
        int CurrentParam = 0;

        for (int i = 0; i < _n[_n.Count - 1]; i++)
        {
            if (_n.Exists(x => x == i))
            {
                Yoffset = Yoffset + 10;
                CurrentParam++;
            }
            //instantiate  new slider
            Grasshopper.Kernel.Special.GH_NumberSlider slid = new Grasshopper.Kernel.Special.GH_NumberSlider();
            slid.CreateAttributes(); //sets up default values, and makes sure your slider doesn't crash rhino

            //customise slider (position, ranges etc)
            //targetParam.Attributes.Bounds


            slid.Attributes.Pivot     = new System.Drawing.PointF((float)targetParam[0].Attributes.Pivot.X - slid.Attributes.Bounds.Width - 70, (float)targetParam[0].Attributes.Pivot.Y + i * 20 + Yoffset);
            slid.Slider.Maximum       = 100;
            slid.Slider.Minimum       = 0;
            slid.Slider.DecimalPlaces = 0;
            // slid.SetSliderValue((decimal) (rnd.Next(-50, 51)));

            if (i + 1 > _dataIn.Count)
            {
                slid.SetSliderValue(_dataIn[_dataIn.Count - 1]);
            }
            else
            {
                slid.SetSliderValue(_dataIn[i]);
            }

            //Until now, the slider is a hypothetical object.
            // This command makes it 'real' and adds it to the canvas.
            GrasshopperDocument.AddObject(slid, false);

            //Connect the new slider to this component
            targetParam[CurrentParam].AddSource(slid);
        }
    }
        private void TakeStep()
        {
            // create design map stepper, which is the list of new points to be tested
            for (int i = 0; i < numVars; i++)
            {
                DesignMapStepperOne.Add(new List <double>());
                DesignMapStepperTwo.Add(new List <double>());
            }

            for (int i = 0; i < numVars; i++)
            {
                for (int j = 0; j < numVars; j++)
                {
                    DesignMapStepperOne[i].Add(MyComponent.VarsVals[j]);
                    DesignMapStepperTwo[i].Add(MyComponent.VarsVals[j]);
                }
            }

            for (int i = 0; i < numVars; i++)
            {
                double left  = MyComponent.VarsVals[i] - 0.5 * FDstep * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                double right = MyComponent.VarsVals[i] + 0.5 * FDstep * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);

                DesignMapStepperOne[i][i] = left;
                DesignMapStepperTwo[i][i] = right;
            }

            // combine lists
            DesignMapStepperCombined.AddRange(DesignMapStepperOne);
            DesignMapStepperCombined.AddRange(DesignMapStepperTwo);

            // Add dummy at end to resent sliders
            DesignMapStepperCombined.Add(MyComponent.VarsVals);


            // run through both design maps, gather objective values on left and right for each variable
            MyComponent.ObjValues = new List <List <double> >();

            MyComponent.Iterating = true;
            this.Iterate();
            MyComponent.Iterating = false;

            for (int j = 0; j < numObjs; j++)
            {
                ObjValsOne.AddRange(MyComponent.ObjValues);
            }

            double maxObj = double.MinValue;
            double minObj = double.MaxValue;

            // find the gradient for each objective by taking finite differences of every variable

            for (int j = 0; j < numObjs; j++)
            {
                Gradient.Add(new List <double>());


                for (int i = 0; i < numVars; i++)
                {
                    double left  = ObjValsOne[i][j];
                    double right = ObjValsOne[numVars + i][j];

                    double difference = (right - left) / (FDstep); //* (MyComponent.MaxVals[i] - MyComponent.MinVals[i]));

                    if (difference > maxObj)
                    {
                        maxObj = difference;
                    }
                    if (difference < minObj)
                    {
                        minObj = difference;
                    }

                    Gradient[j].Add((double)difference);

                    //Gradient[j].Add((double) maxObj);
                }

                //Normalize by max/min difference

                double maxAbs    = double.MinValue;
                double vecLength = 0;

                if (Math.Abs(maxObj) > maxAbs)
                {
                    maxAbs = Math.Abs(maxObj);
                }
                if (Math.Abs(minObj) > maxAbs)
                {
                    maxAbs = Math.Abs(minObj);
                }

                for (int i = 0; i < numVars; i++)
                {
                    Gradient[j][i] = (Gradient[j][i] / maxAbs);
                    vecLength      = vecLength + Gradient[j][i] * Gradient[j][i];
                }

                for (int i = 0; i < numVars; i++)
                {
                    Gradient[j][i] = (Gradient[j][i] / Math.Sqrt(vecLength));
                }
            }

            // Find length of both gradient vectors
            double sum1       = 0;
            double sum2       = 0;
            double dotProduct = 0;

            for (int i = 0; i < numVars; i++)
            {
                sum1       = sum1 + Gradient[0][i] * Gradient[0][i];
                sum2       = sum2 + Gradient[1][i] * Gradient[1][i];
                dotProduct = dotProduct + Gradient[0][i] * Gradient[1][i];
            }

            GradLengths.Add(Math.Sqrt(sum1));
            GradLengths.Add(Math.Sqrt(sum2));

            //Find angle between
            double angleRad = Math.Acos(dotProduct / (GradLengths[0] * GradLengths[1]));

            angle = angleRad * 57.2958;

            // step in the right direction based on the gradient vector

            List <IGH_Param> sliderlist = new List <IGH_Param>();

            foreach (IGH_Param src in MyComponent.Params.Input[0].Sources)
            {
                sliderlist.Add(src);
            }

            for (int i = 0; i < numVars; i++)
            {
                // Take dot product to find bisector
                double change = GradLengths[1] * Gradient[0][i] + GradLengths[0] * Gradient[1][i];

                deltaSlider.Add(change);
                double SteppedSlider = 0;

                Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];


                // First two modes keep advancing both; second two modes, follow one gradient or the other
                if (MyComponent.Direction > 0 && !MyComponent.Mode)
                {
                    SteppedSlider = MyComponent.VarsVals[i] + deltaSlider[i] * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                }

                if (MyComponent.Direction < 0 && !MyComponent.Mode)
                {
                    SteppedSlider = MyComponent.VarsVals[i] - deltaSlider[i] * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                }

                if (MyComponent.Direction > 0 && MyComponent.Mode)
                {
                    SteppedSlider = MyComponent.VarsVals[i] + Gradient[0][i] * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                }

                if (MyComponent.Direction < 0 && MyComponent.Mode)
                {
                    SteppedSlider = MyComponent.VarsVals[i] + Gradient[1][i] * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                }

                nslider.TrySetSliderValue((decimal)SteppedSlider);
            }

            // Send to history, depending on mode

            List <double> VarsObjsCurrent = new List <double>();

            VarsObjsCurrent.AddRange(MyComponent.VarsVals);
            VarsObjsCurrent.AddRange(MyComponent.ObjInput);

            if (!MyComponent.Mode)
            {
                HistoryBiSteps.Add(VarsObjsCurrent);
            }
            else
            {
                HistoryGradSteps.Add(VarsObjsCurrent);
            }

            double sum3 = 0;

            //Calculate length of bisector
            for (int i = 0; i < numVars; i++)
            {
                sum3 += deltaSlider[i] * deltaSlider[i];
            }

            bisectLength = Math.Sqrt(sum3);

            //stepped = true;

            // Do not recompute UI--------------------------
            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);

            //

            //return base.RespondToKeyDown(sender, e);
        }
Exemple #12
0
        private void OnSolutionEnd(object sender, GH_SolutionEventArgs e)
        {
            // Unregister the event, we don't want to get called again.
            e.Document.SolutionEnd -= OnSolutionEnd;

            // If we're not supposed to run, abort now.
            if (!_run)
            {
                return;
            }

            // If we're already running, abort now.
            if (_running)
            {
                return;
            }

            // Reset run and running states.
            _run     = false;
            _running = true;

            try
            {
                // Find the Guid for connected slides
                List <System.Guid>          guids           = new List <System.Guid>(); //empty list for guids
                GH.Kernel.IGH_Param         selSlidersInput = this.Params.Input[0];     //ref for input where sliders are connected to this component
                IList <GH.Kernel.IGH_Param> sources         = selSlidersInput.Sources;  //list of things connected on this input
                bool isAnythingConnected = sources.Any();                               //is there actually anything connected?


                // Find connected
                GH.Kernel.IGH_Param trigger = this.Params.Input[1].Sources[0]; //ref for input where a boolean or a button is connected
                GH.Kernel.Special.GH_BooleanToggle boolTrigger = trigger as GH.Kernel.Special.GH_BooleanToggle;

                if (isAnythingConnected)
                {                                                                                                    //if something's connected,
                    foreach (var source in sources)                                                                  //for each of these connected things:
                    {
                        IGH_DocumentObject component = source.Attributes.GetTopLevel.DocObject;                      //for this connected thing, bring it into the code in a way where we can access its properties
                        GH.Kernel.Special.GH_NumberSlider mySlider = component as GH.Kernel.Special.GH_NumberSlider; //...then cast (?) it as a slider
                        if (mySlider == null)                                                                        //of course, if the thing isn't a slider, the cast doesn't work, so we get null. let's filter out the nulls
                        {
                            continue;
                        }
                        guids.Add(mySlider.InstanceGuid); //things left over are sliders and are connected to our input. save this guid.
                                                          //we now have a list of guids of sliders connected to our input, saved in list var 'mySlider'
                    }
                }

                // Find all sliders.
                List <GH.Kernel.Special.GH_NumberSlider> sliders = new List <GH.Kernel.Special.GH_NumberSlider>();
                foreach (IGH_DocumentObject docObject in doc.Objects)
                {
                    GH.Kernel.Special.GH_NumberSlider slider = docObject as GH.Kernel.Special.GH_NumberSlider;
                    if (slider != null)
                    {
                        // check if the slider is in the selected list
                        if (isAnythingConnected)
                        {
                            if (guids.Contains(slider.InstanceGuid))
                            {
                                sliders.Add(slider);
                            }
                        }
                        else
                        {
                            sliders.Add(slider);
                        }
                    }
                }
                if (sliders.Count == 0)
                {
                    System.Windows.Forms.MessageBox.Show("No sliders could be found", "<harsh buzzing sound>", MessageBoxButtons.OK);
                    return;
                }

                //we now have all sliders
                //ask the user to give a sanity check
                int    counter      = 0;
                int    totalLoops   = 1;
                string popupMessage = "";

                // create progress bar by dots and |
                string pb      = ".................................................."; //50 of "." - There should be a better way to create this in C# > 50 * "." does it in Python!
                char[] pbChars = pb.ToCharArray();

                foreach (GH.Kernel.Special.GH_NumberSlider slider in sliders)
                {
                    totalLoops   *= (slider.TickCount + 1);
                    popupMessage += slider.ImpliedNickName;
                    popupMessage += "\n";
                }
                if (System.Windows.Forms.MessageBox.Show(sliders.Count + " slider(s) connected:\n" + popupMessage +
                                                         "\n" + totalLoops.ToString() + " iterations will be done. Continue?" + "\n\n (Press ESC to pause during progressing!)", "Start?", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    SetBooleanToFalse(boolTrigger);
                    this.Message = "Release Colibri!";
                    return;
                }

                // Set all sliders back to first tick
                foreach (GH.Kernel.Special.GH_NumberSlider slider in sliders)
                {
                    slider.TickValue = 0;
                }

                //start a stopwatch
                System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

                // Start a giant loop in which we'll permutate our way across all slider layouts.
                while (true)
                {
                    int idx = 0;

                    // let the user cancel the process
                    if (GH_Document.IsEscapeKeyDown())
                    {
                        if (System.Windows.Forms.MessageBox.Show("Do you want to stop the process?\nSo far " + counter.ToString() +
                                                                 " out of " + totalLoops.ToString() + " iterations are done!", "Stop?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            // cancel the process by user input!
                            SetBooleanToFalse(boolTrigger);
                            this.Message += "\nCanceled by user! :|";
                            return;
                        }
                    }

                    if (!MoveToNextPermutation(ref idx, sliders))
                    {
                        // study is over!
                        SetBooleanToFalse(boolTrigger);
                        sw.Stop(); //stop start watch
                        UpdateProgressBar(counter, totalLoops, sw, pbChars);
                        this.Message += "\nFinished at " + DateTime.Now.ToShortTimeString();

                        //wipe out colibri variables
                        sliderSteps          = new List <int>();
                        sliderStepsPositions = new Dictionary <int, int>();

                        break;
                    }

                    // We've just got a new valid permutation. Solve the new solution.
                    counter++;
                    e.Document.NewSolution(false);
                    Rhino.RhinoDoc.ActiveDoc.Views.Redraw();
                    UpdateProgressBar(counter, totalLoops, sw, pbChars);
                }
            }
            catch
            {
                // "something went wrong!";
            }
            finally
            {
                // Always make sure that _running is switched off.
                _running = false;
            }
        }
        public override Grasshopper.GUI.Canvas.GH_ObjectResponse RespondToMouseDoubleClick(Grasshopper.GUI.Canvas.GH_Canvas sender, Grasshopper.GUI.GH_CanvasMouseEvent e)
        {
            //Prevent opening of multiple windows at once
            if (!MyComponent.IsWindowOpen)
            {
                MyComponent.IsWindowOpen = true;
                StepperVM VM = new StepperVM(this.MyComponent);

                Thread viewerThread = new Thread(delegate()
                {
                    System.Windows.Window viewer = new StepperWindow(VM);
                    viewer.Show();
                    System.Windows.Threading.Dispatcher.Run();
                });

                viewerThread.SetApartmentState(ApartmentState.STA); // needs to be STA or throws exception
                viewerThread.Start();
            }

            //reset relevant lists
            this.Gradient                 = new List <List <double> >();
            this.DifOne                   = new List <List <double> >();
            this.DifTwo                   = new List <List <double> >();
            this.DesignMapStepperOne      = new List <List <double> >();
            this.DesignMapStepperTwo      = new List <List <double> >();
            this.DesignMapStepperCombined = new List <List <double> >();
            this.ObjValsOne               = new List <List <double> >();
            this.ObjValsTwo               = new List <List <double> >();
            this.IsoPerf                  = new List <List <double> >();

            //TO TEST OUTPUTS
            test.Add(new List <double>());
            test[0].Add(248.0);

            numVars = MyComponent.numVars;
            numObjs = MyComponent.numObjs;

            //Set Finite Differences step size
            FDstep = 0.01;


            // create design map stepper, which is the list of new points to be tested
            for (int i = 0; i < numVars; i++)
            {
                DesignMapStepperOne.Add(new List <double>());
                DesignMapStepperTwo.Add(new List <double>());
            }

            for (int i = 0; i < numVars; i++)
            {
                for (int j = 0; j < numVars; j++)
                {
                    DesignMapStepperOne[i].Add(MyComponent.VarsVals[j]);
                    DesignMapStepperTwo[i].Add(MyComponent.VarsVals[j]);
                }
            }

            for (int i = 0; i < numVars; i++)
            {
                double left  = MyComponent.VarsVals[i] - 0.5 * FDstep * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                double right = MyComponent.VarsVals[i] + 0.5 * FDstep * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);

                DesignMapStepperOne[i][i] = left;
                DesignMapStepperTwo[i][i] = right;
            }

            // combine lists
            DesignMapStepperCombined.AddRange(DesignMapStepperOne);
            DesignMapStepperCombined.AddRange(DesignMapStepperTwo);

            // Add dummy at end to resent sliders
            DesignMapStepperCombined.Add(MyComponent.VarsVals);


            // run through both design maps, gather objective values on left and right for each variable
            MyComponent.ObjValues = new List <List <double> >();

            MyComponent.Iterating = true;
            this.Iterate();
            MyComponent.Iterating = false;

            for (int j = 0; j < numObjs; j++)
            {
                ObjValsOne.AddRange(MyComponent.ObjValues);
            }

            double maxObj = double.MinValue;
            double minObj = double.MaxValue;

            // find the gradient for each objective by taking finite differences of every variable
            for (int j = 0; j < numObjs; j++)
            {
                Gradient.Add(new List <double>());


                for (int i = 0; i < numVars; i++)
                {
                    double left  = ObjValsOne[i][j];
                    double right = ObjValsOne[numVars + i][j];

                    double difference = (right - left) / (FDstep); //* (MyComponent.MaxVals[i] - MyComponent.MinVals[i]));

                    if (difference > maxObj)
                    {
                        maxObj = difference;
                    }
                    if (difference < minObj)
                    {
                        minObj = difference;
                    }

                    Gradient[j].Add((double)difference);

                    //Gradient[j].Add((double) maxObj);
                }

                //Normalize by max/min difference
                double maxAbs    = double.MinValue;
                double vecLength = 0;

                if (Math.Abs(maxObj) > maxAbs)
                {
                    maxAbs = Math.Abs(maxObj);
                }
                if (Math.Abs(minObj) > maxAbs)
                {
                    maxAbs = Math.Abs(minObj);
                }

                for (int i = 0; i < numVars; i++)
                {
                    Gradient[j][i] = (Gradient[j][i] / maxAbs);
                    vecLength      = vecLength + Gradient[j][i] * Gradient[j][i];
                }

                for (int i = 0; i < numVars; i++)
                {
                    Gradient[j][i] = (Gradient[j][i] / Math.Sqrt(vecLength));
                }
            }

            //// FIND THE ORTHOGONAL VECTORS
            ////double[][] gradientArray = Gradient.Select(a => a.ToArray()).ToArray();
            List <List <string> > lst = new List <List <string> >();

            double[,] gradientArray = new double[Gradient.Count, Gradient[0].Count];

            for (int j = 0; j < Gradient.Count; j++)
            {
                for (int i = 0; i < Gradient[j].Count; i++)
                {
                    gradientArray[j, i] = Gradient[j][i];
                }
            }

            var matrixGrad = MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.OfArray(gradientArray);

            //var matrixGrad = MathNet.Numerics.LinearAlgebra.Double.Matrix.Abs(14.0);

            //var matrixGradT = matrixGrad.Transpose();

            var nullspace = matrixGrad.Kernel();

            // Convert array to List of nullspace vectors
            if (numVars > numObjs)
            {
                for (int i = 0; i < numVars - numObjs; i++)
                {
                    IsoPerf.Add(new List <double>());
                    double[] IsoPerfDir = nullspace[i].ToArray();
                    IsoPerf[i].AddRange(IsoPerfDir);
                }
            }

            // Randomly pick an isoperformance direction
            Random rnd      = new Random();
            int    dir      = new int();
            int    testrand = new int();

            testrand = rnd.Next(numVars - numObjs);

            dir = testrand;



            // Ensure that direction is "interesting"

            //for (int i = testrand; i < numVars - numObjs - 1; i++)
            //{

            //    dir = i;
            //    List<double> IsoVecAbs = IsoPerf[i].Select(x => Math.Abs(x)).ToList();
            //    IsoVecAbs.Sort();

            //    double a = IsoVecAbs[numVars - 1];
            //    double b = IsoVecAbs[numVars - 2];
            //    double c = a / b;

            //    if (c < 3) { break; }
            //    else { dir = dir + 1; }

            //}

            //for (int i = 0; i < numVars - numObjs; i++)
            //{
            //    for (int j = 0; j < IsoPerf[i].Count; j++)
            //    {
            //        IsoPerf.Add(new List<double>());
            //        double[] IsoPerfDir = nullspace[i].ToArray();

            //    }
            //}


            List <double> IsoPerfDirList = IsoPerf[dir];


            // step in the right direction based on the gradient vector

            List <IGH_Param> sliderlist = new List <IGH_Param>();

            foreach (IGH_Param src in MyComponent.Params.Input[0].Sources)
            {
                sliderlist.Add(src);
            }

            for (int i = 0; i < numVars; i++)
            {
                if (MyComponent.Direction > 0)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];
                    double SteppedSlider = MyComponent.VarsVals[i] + Gradient[MyComponent.ObjNum][i] * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                    nslider.TrySetSliderValue((decimal)SteppedSlider);
                }

                if (MyComponent.Direction < 0)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];
                    double SteppedSlider = MyComponent.VarsVals[i] - Gradient[MyComponent.ObjNum][i] * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                    nslider.TrySetSliderValue((decimal)SteppedSlider);
                }

                // TAKE STEP IN ORTHOGONAL DIRECTION
                if (MyComponent.Direction == 0)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];
                    double SteppedSlider = MyComponent.VarsVals[i] + IsoPerfDirList[i] * MyComponent.StepSize * MyComponent.numVars;
                    nslider.TrySetSliderValue((decimal)SteppedSlider);
                }
            }

            stepped = true;
            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);

            return(base.RespondToMouseDoubleClick(sender, e));
        }
Exemple #14
0
        /// <summary>
        /// Grasshopper solve method
        /// </summary>
        /// <param name="DA"></param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // If we are currently static, then reset things and collect sliders
            if (!GO)
            {
                // Spring clean
                counter = 0;
                sliders.Clear();
                persGeo.Clear();
                sliderValues.Clear();

                DA.GetData("PopSize", ref popSize);

                // Collect the sliders up (just one at the moment)
                foreach (IGH_Param param in this.Params.Input[0].Sources)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                    if (slider != null)
                    {
                        sliders.Add(slider);
                    }
                }


                // Now set the value list
                // TODO: Replace with a tree, not just the first slider!
                // Thanks to Dimitrie A. Stefanescu for making Speckle open which has helped greatly here.


                for (int i = 0; i < sliders.Count; i++)
                {
                    double min = (double)sliders[i].Slider.Minimum;
                    double max = (double)sliders[i].Slider.Maximum;

                    // Note we use divisions-1 because we have inclusive slider bounds
                    double increment = (max - min) / ((double)popSize - 1);

                    for (int j = 0; j < popSize; j++)
                    {
                        sliderValues.Add(j * increment + min);
                    }
                }
            }

            // So if GO = true...
            else
            {
                // Get the slider values.
                // TODO: Include more than one slider.
                if (counter < popSize)
                {
                    //for (int i = 0; i < sliders.Count; i++)
                    sliders[0].Slider.Value = (decimal)sliderValues[counter];
                }


                // First things first...
                // We have to do the else stuff AFTER the slider has moved and the component is expired (tricky).
                if (counter == 0)
                {
                }
                else
                {
                    // Collect the object at the current instance
                    List <object> localObjs = new List <object>();
                    DA.GetDataList("Geometry", localObjs);

                    // Currently we only take meshes
                    Mesh joinedMesh = new Mesh();

                    for (int i = 0; i < localObjs.Count; i++)
                    {
                        if (localObjs[i] is GH_Mesh)
                        {
                            GH_Mesh myGHMesh = new GH_Mesh();
                            myGHMesh = (GH_Mesh)localObjs[i];
                            Mesh myLocalMesh = new Mesh();
                            GH_Convert.ToMesh(myGHMesh, ref myLocalMesh, GH_Conversion.Primary);
                            myLocalMesh.Faces.ConvertQuadsToTriangles();
                            joinedMesh.Append(myLocalMesh);
                        }
                    }

                    persGeo.Add(joinedMesh);
                }


                // If we reach a limit, then stop and launch the window
                if (counter == sliderValues.Count)
                {
                    // Instantiate the window and export the geometry to WPF3D
                    myMainWindow = new DesignSpaceWindow(GetPersMeshList());
                    myMainWindow.Show();

                    GO = false;

                    // Expire this component
                    this.ExpireSolution(true);
                }

                // NOW iterate the master counter
                counter++;
            }

            // We need some interaction with the form before sending out the chosen phenotypes.
            DA.SetData(0, 444);
        }
Exemple #15
0
        private List <string> getConnectedSlidersNames()
        {
            List <string> names = new List <string>();

            // Find the Guid for connected slides
            List <System.Guid> guids = new List <System.Guid>();                   //empty list for guids

            GH.Kernel.IGH_Param         selSlidersInput = this.Params.Input[0];    //ref for input where sliders are connected to this component
            IList <GH.Kernel.IGH_Param> sources         = selSlidersInput.Sources; //list of things connected on this input
            bool isAnythingConnected = sources.Any();                              //is there actually anything connected?


            // Find connected
            GH.Kernel.IGH_Param trigger = this.Params.Input[1].Sources[0]; //ref for input where a boolean or a button is connected
            GH.Kernel.Special.GH_BooleanToggle boolTrigger = trigger as GH.Kernel.Special.GH_BooleanToggle;

            if (isAnythingConnected)
            {                                                                                                    //if something's connected,
                foreach (var source in sources)                                                                  //for each of these connected things:
                {
                    IGH_DocumentObject component = source.Attributes.GetTopLevel.DocObject;                      //for this connected thing, bring it into the code in a way where we can access its properties
                    GH.Kernel.Special.GH_NumberSlider mySlider = component as GH.Kernel.Special.GH_NumberSlider; //...then cast (?) it as a slider
                    if (mySlider == null)                                                                        //of course, if the thing isn't a slider, the cast doesn't work, so we get null. let's filter out the nulls
                    {
                        continue;
                    }
                    guids.Add(mySlider.InstanceGuid); //things left over are sliders and are connected to our input. save this guid.
                                                      //we now have a list of guids of sliders connected to our input, saved in list var 'mySlider'
                }
            }

            // Find all sliders.
            List <GH.Kernel.Special.GH_NumberSlider> sliders = new List <GH.Kernel.Special.GH_NumberSlider>();

            foreach (IGH_DocumentObject docObject in doc.Objects)
            {
                GH.Kernel.Special.GH_NumberSlider slider = docObject as GH.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    // check if the slider is in the selected list
                    if (isAnythingConnected)
                    {
                        if (guids.Contains(slider.InstanceGuid))
                        {
                            sliders.Add(slider);
                        }
                    }
                    else
                    {
                        sliders.Add(slider);
                    }
                }
            }


            foreach (GH.Kernel.Special.GH_NumberSlider slider in sliders)
            {
                names.Add(slider.NickName);
            }

            return(names);
        }
Exemple #16
0
        public static Individual CreateRandomIndividual(ChihuahuaComponent comp)
        {
            GH_Document docu = comp.OnPingDocument();

            //Change value of sliders
            List <decimal>    genome  = new List <decimal>();
            List <decimal>    Ngenome = new List <decimal>();
            IList <IGH_Param> sliders = comp.Params.Input[0].Sources;

            foreach (IGH_Param param in sliders)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    decimal N_gene_value = (decimal)random.NextDouble();
                    decimal gene_value   = N_gene_value.Remap(0, 1, slider.Slider.Minimum, slider.Slider.Maximum);
                    slider.SetSliderValue(gene_value);
                    Ngenome.Add(N_gene_value);
                    genome.Add(gene_value);
                }

                else
                {
                    Rhino.RhinoApp.WriteLine("At least one of the input parameters is not a number slider" + Environment.NewLine);
                    throw new System.ArgumentException("At least one of the input parameters is not a number slider", "Genome");
                }
            }

            // Get a new solution

            docu.NewSolution(false);

            //Read new fitness value

            decimal fitness = 0;

            if (comp.Params.Input[1].SourceCount != 1)
            {
                Rhino.RhinoApp.Write("Fitness input must be a unique value" + Environment.NewLine);
                throw new System.ArgumentException("Fitness input must be a unique value", "Fitness");
            }

            else
            {
                IGH_Param param = comp.Params.Input[1].Sources[0];
                GH_Structure <GH_Number> outcome = comp.Params.Input[1].Sources[0].VolatileData as GH_Structure <GH_Number>;

                if (outcome == null)
                {
                    Rhino.RhinoApp.WriteLine("Fitness input is not a number" + Environment.NewLine);
                    throw new System.ArgumentException("Fitness input is not a number", "Fitness");
                }
                if (outcome != null)
                {
                    fitness = (decimal)outcome.Branches[0][0].Value;
                }
            }

            Individual ind = new Individual(fitness, genome, Ngenome);

            return(ind);
        }
Exemple #17
0
        public void Export()
        {
            if (INSTANCECOUNT > 4242)
            {
                string message = "Warning: There are " + INSTANCECOUNT + " iterations.\nIt might take a lot of time and / or Rhino might crash.\nAre you sure you want to proceed?";

                DialogResult largeinstancewarning = MessageBox.Show(message, "Warning", MessageBoxButtons.YesNo);
                if (largeinstancewarning == DialogResult.No)
                {
                    EMERGENCY_BREAK = true;
                    return;
                }
            }

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.Description = "Please select an empty folder where the export file should be saved.";
            DialogResult result = fbd.ShowDialog();

            if (result == DialogResult.OK)
            {
                string[] files = Directory.GetFiles(fbd.SelectedPath);

                if (files.Length > 0)
                {
                    System.Windows.Forms.MessageBox.Show("This is not an empty folder!");
                }
                else
                {
                    this.PATHISSET      = true;
                    this.FOLDERLOCATION = fbd.SelectedPath;
                    GHDEFNAME           = new DirectoryInfo(fbd.SelectedPath).Name;
                    EMERGENCY_BREAK     = false;
                }
            }

            if (result == DialogResult.Cancel)
            {
                EMERGENCY_BREAK = true;
                return;
            }



            // Sanity checks
            IGH_Component component = Component;
            GH_Document   doc       = GrasshopperDocument;

            if (!PATHISSET)
            {
                return;
            }
            if (component == null)
            {
                return;
            }
            if (doc == null)
            {
                return;
            }


            /// flushing up them arrays
            geometries   = new List <List <System.Object> >();
            geometrySets = new List <string>();
            sliderNames  = new List <string>();

            currentCount = 0;

            // Collect all sliders that are plugged into the first input parameter of the script component.
            List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>();

            foreach (IGH_Param param in component.Params.Input[0].Sources)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    sliders.Add(slider);
                    sliderNames.Add(slider.NickName);
                }
            }

            if (sliders.Count == 0)
            {
                return;
            }

            // generate the Matrix File
            myMatrix = constructMatrixFromSliders((GH_Component)component);

            // update the instance count
            INSTANCECOUNT = myMatrix.Count;

            // go generate stuff
            foreach (List <double> instance in myMatrix)
            {
                // pause the solver while set up the sliders
                doc.Enabled = false;

                // update the currentInstanceName - top level var
                currentInstanceName = "";

                foreach (double tempvar in instance)
                {
                    currentInstanceName += tempvar + ",";
                }

                // set sliders up

                for (int i = 0; i < sliders.Count; i++)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider mySlider = sliders[i];
                    mySlider.Slider.Value = (decimal)instance[i];
                }

                //renable solver
                doc.Enabled = true;

                //compute new solution
                doc.NewSolution(false);
            }
        }
Exemple #18
0
        public override Grasshopper.GUI.Canvas.GH_ObjectResponse RespondToMouseDoubleClick(Grasshopper.GUI.Canvas.GH_Canvas sender, Grasshopper.GUI.GH_CanvasMouseEvent e)
        {
            // Read in Cluster number slider
            List <IGH_Param> sliderListClust = new List <IGH_Param>();

            foreach (IGH_Param src2 in MyComponent.Params.Input[4].Sources)
            {
                sliderListClust.Add(src2);
            }
            Grasshopper.Kernel.Special.GH_NumberSlider clusterSlider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderListClust[0];



            if (!MyComponent.ClusterDone)

            {
                //run clustering process
                KMeans kmeans = new KMeans(MyComponent.numClusters);


                double[][] data    = MyComponent.DesignMap.Select(a => a.ToArray()).ToArray();
                double[]   weights = null;

                // int[] labels = kmeans.Learn(data,weights);

                for (int i = 0; i < data.Count(); i++)
                {
                    data[i] = data[i].Take(data[i].Count() - MyComponent.numObjs).ToArray();
                }


                int[] labels = kmeans.Compute(data);

                LabelsList = labels.OfType <int>().ToList();


                // Set cluster slider bounds, values to default while clustering is run
                clusterSlider.TrySetSliderValue((decimal)0);
                clusterSlider.Slider.Minimum = ((decimal)0);
                clusterSlider.Slider.Maximum = ((decimal)MyComponent.numClusters);


                // list management
                this.DesignMap = MyComponent.DesignMap;
                this.numVars   = MyComponent.numVars;

                // create Sorted list
                for (int i = 0; i < MyComponent.numClusters; i++)
                {
                    DesignMapSorted.Add(new List <List <double> >());
                    for (int j = 0; j < DesignMap.Count; j++)
                    {
                        if (LabelsList[j] == i)
                        {
                            DesignMapSorted[i].Add(DesignMap[j]);
                        }
                    }
                }

                for (int i = 0; i < MyComponent.numClusters; i++)
                {
                    ClusterAves.Add(new List <double>());
                    ClusterMaxs.Add(new List <double>());
                    ClusterMins.Add(new List <double>());

                    double[] sum     = new double[numVars];
                    double[] average = new double[numVars];
                    double[] max     = new double[numVars];
                    double[] min     = new double[numVars];

                    for (int l = 0; l < numVars; l++)

                    {
                        sum[l] = 0;
                        max[l] = double.MinValue;
                        min[l] = double.MaxValue;
                    }

                    for (int j = 0; j < DesignMapSorted[i].Count; j++)

                    {
                        for (int k = 0; k < numVars; k++)

                        {
                            sum[k] = sum[k] + DesignMapSorted[i][j][k];

                            if (DesignMapSorted[i][j][k] > max[k])

                            {
                                max[k] = DesignMapSorted[i][j][k];
                            }
                            else if (DesignMapSorted[i][j][k] < min[k])

                            {
                                min[k] = DesignMapSorted[i][j][k];
                            }

                            average[k] = sum[k] / DesignMapSorted[i].Count;
                        }
                    }

                    for (int k = 0; k < numVars; k++)
                    {
                        ClusterAves[i].Add(average[k]);
                        ClusterMaxs[i].Add(max[k]);
                        ClusterMins[i].Add(min[k]);
                    }
                }


                ClusterAves.Insert(0, MyComponent.VarsVals);
                ClusterMaxs.Insert(0, MyComponent.MaxVals);
                ClusterMins.Insert(0, MyComponent.MinVals);


                //for (int i = 0; i < DesignMapSorted.Count; i++)

                //{
                //LabelsList[i] = LabelsList[i] + 1;
                //}
            }



            List <IGH_Param> sliderList = new List <IGH_Param>();

            foreach (IGH_Param src in MyComponent.Params.Input[0].Sources)
            {
                sliderList.Add(src);
            }

            for (int i = 0; i < numVars; i++)
            {
                if (MyComponent.index != 0)

                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderList[i];

                    double adjmin = ClusterMins[MyComponent.index][i] + (1 - MyComponent.flexibility) * (ClusterAves[MyComponent.index][i] - ClusterMins[MyComponent.index][i]);
                    double adjmax = ClusterMaxs[MyComponent.index][i] - (1 - MyComponent.flexibility) * (ClusterMaxs[MyComponent.index][i] - ClusterAves[MyComponent.index][i]);

                    nslider.TrySetSliderValue((decimal)ClusterAves[MyComponent.index][i]);
                    nslider.Slider.Minimum = ((decimal)adjmin);
                    nslider.Slider.Maximum = ((decimal)adjmax);
                }
                else
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderList[i];

                    nslider.TrySetSliderValue((decimal)ClusterAves[MyComponent.index][i]);
                    nslider.Slider.Minimum = ((decimal)ClusterMins[MyComponent.index][i]);
                    nslider.Slider.Maximum = ((decimal)ClusterMaxs[MyComponent.index][i]);
                }
            }

            MyComponent.ClusterDone = true;
            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);

            return(base.RespondToMouseDoubleClick(sender, e));
        }
Exemple #19
0
        /// <summary>
        /// Creates a list of lists holding up all the possible slider combinations. No idea why it returns something.
        /// </summary>

        public List <List <double> > constructMatrixFromSliders(GH_Component component)
        {
            List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>();

            foreach (IGH_Param param in component.Params.Input[0].Sources)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    sliders.Add(slider);
                }
            }

            if (sliders.Count == 0)
            {
                return(null);
            }

            sliderValues = new List <List <double> >();

            for (int k = 0; k < sliders.Count; k++)
            {
                List <double> mySliderValues = new List <double>();

                Grasshopper.Kernel.Special.GH_NumberSlider slider = sliders[k];

                if (slider.Slider.Type == Grasshopper.GUI.Base.GH_SliderAccuracy.Integer)
                {
                    // TODO restrict to MAXVALUES for int sliders
                    int min, max;

                    min = (int)slider.Slider.Minimum;
                    max = (int)slider.Slider.Maximum;

                    for (int j = min; j <= max; j++)
                    {
                        mySliderValues.Add((double)Math.Round((double)j, 0));
                    }
                }

                else if (slider.Slider.Type == Grasshopper.GUI.Base.GH_SliderAccuracy.Float)
                {
                    double min, max;

                    min = (double)slider.Slider.Minimum;
                    max = (double)slider.Slider.Maximum;

                    double absRange  = max - min;
                    double increment = absRange / (MAXVALUES - 1);

                    for (double j = min; j <= max; j += increment)
                    {
                        mySliderValues.Add((double)Convert.ToDouble(Convert.ToString(Math.Round(j, 2)))); //really, really, really stupid
                    }
                }

                sliderValues.Add(mySliderValues);
            }

            return(AllCombinationsOf(sliderValues));
        }
        public override Grasshopper.GUI.Canvas.GH_ObjectResponse RespondToMouseDoubleClick(Grasshopper.GUI.Canvas.GH_Canvas sender, Grasshopper.GUI.GH_CanvasMouseEvent e)

        //public override GH_ObjectResponse RespondToKeyDown(GH_Canvas sender, KeyEventArgs e)
        {
            //reset relevant lists
            this.Gradient                 = new List <List <double> >();
            this.DifOne                   = new List <List <double> >();
            this.DifTwo                   = new List <List <double> >();
            this.DesignMapStepperOne      = new List <List <double> >();
            this.DesignMapStepperTwo      = new List <List <double> >();
            this.DesignMapStepperCombined = new List <List <double> >();
            this.ObjValsOne               = new List <List <double> >();
            this.ObjValsTwo               = new List <List <double> >();



            numVars = MyComponent.numVars;
            numObjs = MyComponent.numObjs;


            // create design map stepper, which is the list of new points to be tested
            for (int i = 0; i < numVars; i++)
            {
                DesignMapStepperOne.Add(new List <double>());
                DesignMapStepperTwo.Add(new List <double>());
            }

            for (int i = 0; i < numVars; i++)
            {
                for (int j = 0; j < numVars; j++)
                {
                    DesignMapStepperOne[i].Add(MyComponent.VarsVals[j]);
                    DesignMapStepperTwo[i].Add(MyComponent.VarsVals[j]);
                }
            }

            for (int i = 0; i < numVars; i++)
            {
                double left  = MyComponent.VarsVals[i] - 0.5 * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);
                double right = MyComponent.VarsVals[i] + 0.5 * MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]);

                DesignMapStepperOne[i][i] = left;
                DesignMapStepperTwo[i][i] = right;
            }

            // combine lists
            DesignMapStepperCombined.AddRange(DesignMapStepperOne);
            DesignMapStepperCombined.AddRange(DesignMapStepperTwo);

            // Add dummy at end to resent sliders
            DesignMapStepperCombined.Add(MyComponent.VarsVals);


            // run through both design maps, gather objective values on left and right for each variable
            MyComponent.ObjValues = new List <List <double> >();

            MyComponent.Iterating = true;
            this.Iterate();
            MyComponent.Iterating = false;

            for (int j = 0; j < numObjs; j++)
            {
                ObjValsOne.AddRange(MyComponent.ObjValues);
            }

            double maxObj = double.MinValue;
            double minObj = double.MaxValue;

            // find the gradient for each objective by taking finite differences of every variable

            for (int j = 0; j < numObjs; j++)
            {
                Gradient.Add(new List <double>());


                for (int i = 0; i < numVars; i++)
                {
                    double left  = ObjValsOne[i][j];
                    double right = ObjValsOne[numVars + i][j];

                    double difference = (right - left) / (MyComponent.StepSize * (MyComponent.MaxVals[i] - MyComponent.MinVals[i]));

                    if (difference > maxObj)
                    {
                        maxObj = difference;
                    }
                    if (difference < minObj)
                    {
                        minObj = difference;
                    }

                    Gradient[j].Add((double)difference);

                    //Gradient[j].Add((double) maxObj);
                }

                //Normalize by max/min difference

                double maxAbs    = double.MinValue;
                double vecLength = 0;

                if (Math.Abs(maxObj) > maxAbs)
                {
                    maxAbs = Math.Abs(maxObj);
                }
                if (Math.Abs(minObj) > maxAbs)
                {
                    maxAbs = Math.Abs(minObj);
                }

                for (int i = 0; i < numVars; i++)
                {
                    Gradient[j][i] = (Gradient[j][i] / maxAbs);
                    vecLength      = vecLength + Gradient[j][i] * Gradient[j][i];
                }

                for (int i = 0; i < numVars; i++)
                {
                    Gradient[j][i] = (Gradient[j][i] / Math.Sqrt(vecLength));
                }
            }

            //// FIND THE ORTHOGONAL VECTORS

            ////double[][] gradientArray = Gradient.Select(a => a.ToArray()).ToArray();

            List <List <string> > lst = new List <List <string> >();

            double[,] gradientArray = new double[Gradient.Count, Gradient[0].Count];

            for (int j = 0; j < Gradient.Count; j++)
            {
                for (int i = 0; i < Gradient[j].Count; i++)
                {
                    gradientArray[j, i] = Gradient[j][i];
                }
            }

            var matrixGrad = MathNet.Numerics.LinearAlgebra.Double.DenseMatrix.OfArray(gradientArray);

            var matrixGradT = matrixGrad.Transpose();
            var nullspace   = matrixGradT.Kernel();


            // STRATEGY 1: Direct to Array

            double[] nullspaceArray;

            for (int i = 1; i < 2; i++)
            {
                nullspaceArray = nullspace[i].ToArray();
            }

            // STRATEGY 2: One Line to Array
            //double[] IsoPerfDir = nullspace.ToArray()[1].ToArray();

            double[] IsoPerfDir2 = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };

            //STRATEGY 3: STRING IN THE MIDDLE
            //string IsoPerfDir = nullspace.ToArray()[0].ToString();

            //List<double> IsoPerfDir3 = (List<double>)StringToDoubleList(IsoPerfDir);


            //var IsoPerfMatrix = nullspace;

            //IsoPerf.Add(IsoPerfMatrix[1]);

            //// Randomly assign coefficient, create isoperformance direction
            //Random rnd = new Random();
            //int isoDir = rnd.Next(0, numVars - 1);



            //// Convert array to List


            for (int i = 0; i < numVars; i++)
            {
                IsoPerf.Add(IsoPerfDir2[i]);
            }



            // step in the right direction based on the gradient vector

            List <IGH_Param> sliderlist = new List <IGH_Param>();

            foreach (IGH_Param src in MyComponent.Params.Input[0].Sources)
            {
                sliderlist.Add(src);
            }

            for (int i = 0; i < numVars; i++)
            {
                if (MyComponent.Direction > 0)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];

                    double SteppedSlider = MyComponent.VarsVals[i] + Gradient[MyComponent.ObjNum][i] * MyComponent.StepSize;

                    nslider.TrySetSliderValue((decimal)SteppedSlider);
                }

                if (MyComponent.Direction < 0)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];

                    double SteppedSlider = MyComponent.VarsVals[i] - Gradient[MyComponent.ObjNum][i] * MyComponent.StepSize;

                    nslider.TrySetSliderValue((decimal)SteppedSlider);
                }

                /// TAKE STEP IN ORTHOGONAL DIRECTION

                //if (MyComponent.Direction == 0)
                //{

                //Grasshopper.Kernel.Special.GH_NumberSlider nslider = (Grasshopper.Kernel.Special.GH_NumberSlider)sliderlist[i];

                //double SteppedSlider = MyComponent.VarsVals[i] - IsoPerf[i] * MyComponent.StepSize;

                //nslider.TrySetSliderValue((decimal)SteppedSlider);

                //}
            }

            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);

            //return base.RespondToKeyDown(sender, e);

            return(base.RespondToMouseDoubleClick(sender, e));
        }
Exemple #21
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Component = this;
            doc       = Component.OnPingDocument();
            var    x = new List <double>();
            double fx = new double(); double h = new double(); int step = 0; double alpha = new double(); var eps = 1e-4;

            if (!DA.GetData("f(x)", ref fx))
            {
                return;
            }
            if (!DA.GetDataList("x", x))
            {
                return;
            }
            if (!DA.GetData("h", ref h))
            {
                return;
            }
            if (!DA.GetData("alpha", ref alpha))
            {
                return;
            }
            if (!DA.GetData("step", ref step))
            {
                return;
            }
            if (!DA.GetData("eps", ref eps))
            {
                return;
            }
            if (start == 0)
            {
                return;
            }
            if (counter == -1)
            {
                y = x;
            }
            List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>();

            for (int i = 0; i < x.Count; i++)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = Params.Input[1].Sources[i] as Grasshopper.Kernel.Special.GH_NumberSlider;
                sliders.Add(slider);
                if (counter == -1)
                {
                    minrange.Add((double)slider.Slider.Minimum); maxrange.Add((double)slider.Slider.Maximum);
                }
            }
            doc.NewSolution(false);
            if (agm == 1)
            {
                for (int i = 0; i < y.Count; i++)
                {
                    y[i] = Math.Min(Math.Max(y[i], minrange[i]), maxrange[i]);
                }                                                                                               //force y inside slider range
                var df = Sensitivity(sliders, y, h);
                dk = df; for (int i = 0; i < dk.Length; i++)
                {
                    dk[i] = -dk[i];
                }                                                               //dk=-df
                if (golden == 1)
                {
                    alpha = line_search_golden_section(sliders, y, dk);
                }
                var x_prev = x;
                for (int i = 0; i < x.Count; i++)
                {
                    x[i] = y[i] + alpha * dk[i];
                }                                                                 //x=y+alpha*dk
                var dk_norm     = Math.Sqrt(vec_multiply(dk, dk));
                var t_prev      = t;
                var reset_value = 0.0; for (int i = 0; i < dk.Length; i++)
                {
                    reset_value += -dk[i] * (x[i] - x_prev[i]);
                }                                                                                                          //np.dot(-dk,x-x_prev)
                if (reset_value <= 0.0)
                {
                    t = 0.5 * (1.0 + Math.Sqrt(1.0 + 4.0 * Math.Pow(t_prev, 2)));//t=0.50*(1.0+np.sqrt(1.0+4.0*t**2))
                    for (int i = 0; i < x.Count; i++)
                    {
                        y[i] = x[i] + (t_prev - 1.0) / t * (x[i] - x_prev[i]);
                    }                                                                                           //y=x+(t_prev-1.0)/t*(x-x_prev)
                }
                else
                {
                    t = 1.0; y = x;
                }
                DA.SetDataList("df(x)", df);
                DA.SetData("|df(x)|", dk_norm);
                DA.SetData("alpha", alpha);
                counter += 1;
                if (start == 1 && counter < step && dk_norm > eps)
                {
                    doc.ScheduleSolution(1, ScheduleCallback);
                }
            }
            else if (cg == 1)
            {
                if (counter == -1)
                {
                    dk = Sensitivity(sliders, x, h); for (int i = 0; i < dk.Length; i++)
                    {
                        dk[i] = -dk[i];
                    }
                    ; pk = dk;
                }                                                                                                                        //dk=-df
                for (int i = 0; i < pk.Length; i++)
                {
                    pk[i] = dk[i] + beta * pk[i];
                }                                                                    //pk=dk+beta*pk
                if (golden == 1)
                {
                    alpha = line_search_golden_section(sliders, x, pk);
                }
                for (int i = 0; i < x.Count; i++)
                {
                    x[i] = x[i] + alpha * pk[i];
                }                                                                 //x=x+alpha*pk
                var dk_prev = dk;
                dk = Sensitivity(sliders, x, h); for (int i = 0; i < dk.Length; i++)
                {
                    dk[i] = -dk[i];
                }                                                                                       //dk=-df
                beta = vec_multiply(dk, dk) / vec_multiply(dk_prev, dk_prev);
                var dk_norm = Math.Sqrt(vec_multiply(dk, dk));
                DA.SetDataList("df(x)", dk);
                DA.SetData("|df(x)|", dk_norm);
                DA.SetData("alpha", alpha);
                counter += 1;
                if (start == 1 && counter < step && dk_norm > eps)
                {
                    doc.ScheduleSolution(1, ScheduleCallback);
                }
            }
        }