Example #1
0
        public static GH_NumberSlider CreateNumbersilder(string name, decimal min, decimal max, int precision = 0, int length = 174)
        {
            var nS = new GH_NumberSlider();

            nS.ClearData();

            //Naming
            nS.Name     = name;
            nS.NickName = name;

            nS.Slider.Minimum = min;
            nS.Slider.Maximum = max;

            nS.Slider.DecimalPlaces = Axis.Util.LimitToRange(precision, 0, 12);

            if (precision == 0)
            {
                nS.Slider.Type = Grasshopper.GUI.Base.GH_SliderAccuracy.Integer;
            }
            else
            {
                nS.Slider.Type = Grasshopper.GUI.Base.GH_SliderAccuracy.Float;
            }

            nS.CreateAttributes();
            var bounds = nS.Attributes.Bounds;

            bounds.Width         = length;
            nS.Attributes.Bounds = bounds;

            nS.SetSliderValue(min);
            return(nS);
        }
 public DVariableGH(double val, double min, double max, GH_NumberSlider slider)// : base(val)
 {
     this.Value  = val;
     this.Min    = min;
     this.Max    = max;
     this.Slider = slider;
 }
        /// <summary>
        /// Makes the DockPanel containing the slider and labels from the GH_NumberSlider it's passed.
        /// </summary>
        /// <param name="slider">The slider.</param>
        /// <param name="labelList">The label list.</param>
        /// <returns>A DockPanel containing the slider and labels.</returns>
        private DockPanel MakeSlider(GH_NumberSlider slider, ref List <Label> labelList, double snapValue)
        {
            int    decimalPlaces = slider.Slider.DecimalPlaces;
            string name          = slider.ImpliedNickName;

            //if (String.IsNullOrWhiteSpace(name) || name.Length == 0) name = "Slider";
            return(createNewSliderWithLabels(slider.Slider.Minimum, slider.Slider.Maximum, slider.Slider.Value, name, slider.Slider.Type == Grasshopper.GUI.Base.GH_SliderAccuracy.Integer, decimalPlaces, ref labelList, snapValue));
        }
        /// <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)
        {
            string jsonString     = null;
            bool   prevIsUpdating = isUpdating;

            if (!DA.GetData(0, ref jsonString))
            {
                return;
            }

            if (prevJSONString == jsonString)
            {
                DA.SetData(0, isUpdating);
                return;
            }
            prevJSONString = jsonString;
            var             data           = JsonSerializer.Deserialize <UpdateMessage>(jsonString);
            var             doc            = OnPingDocument();
            var             guid           = new Guid(data.guid);
            GH_NumberSlider sliderToExpire = null;

            foreach (IGH_DocumentObject docObject in doc.Objects)
            {
                if (guid == docObject.InstanceGuid)
                {
                    sliderToExpire = docObject as GH_NumberSlider;
                    break;
                }
            }

            if (sliderToExpire != null)
            {
                isUpdating = true;
                doc.ScheduleSolution(5, (GH_Document _doc) =>
                {
                    sliderToExpire.SetSliderValue((decimal)data.value);
                    sliderToExpire.ExpireSolution(false);
                });


                if (timer != null)
                {
                    timer.Stop();
                    timer.Elapsed -= Timer_Elapsed;
                    timer.Dispose();
                }

                timer = new Timer()
                {
                    Interval = 300
                };
                timer.AutoReset = false;
                timer.Elapsed  += Timer_Elapsed;
                timer.Start();
            }

            DA.SetData(0, isUpdating);
        }
Example #5
0
        /*******************************************/

        public static INode ToNode(this GH_NumberSlider component)
        {
            double value = (double)component.CurrentValue;
            Type   type  = (value % 1 == 0) ? typeof(int) : typeof(double);

            return(ParamNode(PopulateParam(new DataParam {
                Data = value, DataType = type
            }, component)));
        }
Example #6
0
        private StackPanel MakeSlider(GH_NumberSlider slider)
        {
            string name = slider.ImpliedNickName;

            if (String.IsNullOrWhiteSpace(name) || name.Length == 0)
            {
                name = "Slider";
            }
            return(createNewSliderWithLabels(slider.Slider.Minimum, slider.Slider.Maximum, slider.Slider.Value, name, slider.Slider.Type == Grasshopper.GUI.Base.GH_SliderAccuracy.Integer));
        }
        public List <DesignVM> GenerateAndSelectTop(int number, int popsize, double rate)
        {
            // get new generation
            DesignVM      myFirstDesign = this.myDesignToolVM.InitialDesign;
            int           rowIndex      = this.DesignGrid.RowDefinitions.Count - 1;
            List <Design> seeds         = new List <Design>();

            if (rowIndex >= 0)
            {
                seeds = this.GetSeeds(rowIndex);
            }
            List <Design>   Designs          = EvolutionaryUtilities.NewGeneration(myFirstDesign.Design, seeds, EvolutionaryUtilities.NormalGenerator, popsize, rate);//, null);
            List <DesignVM> generatedDesigns = new List <DesignVM>();

            // Run designs through grasshopper solution
            foreach (Design design in Designs)
            {
                for (int i = 0; i < Component.Params.Input[2].Sources.Count; i++)
                {
                    GH_NumberSlider slider = Component.Params.Input[2].Sources[i] as GH_NumberSlider;
                    if (slider != null)
                    {
                        slider.SetSliderValue((decimal)design.DesignVariables[i].Value);
                    }
                }
                Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);
                List <Rhino.Geometry.Line>  lines  = Component.DesignLines; // write csv here??
                List <Rhino.Geometry.Curve> curves = Component.DesignCurves;
                List <Rhino.Geometry.Mesh>  meshes = Component.DesignMeshes;
                List <Rhino.Geometry.Brep>  breps  = Component.DesignBreps;

                double   normscore = Component.Score / this.myDesignToolVM.getinitscore();
                DesignVM genDesign = new DesignVM(lines, curves, meshes, breps, false, true, normscore, design.DesignClone());
                this.myDesignToolVM.ExplorationRec.AppendLine(csvWriter.writeDesign(genDesign));
                generatedDesigns.Add(genDesign);
            }
            // sort and identify top performers
            List <DesignVM> best = EvolutionaryUtilities.FindTopDesignsVM(generatedDesigns, number, rate);

            // Change main viewport design to top best design
            DesignVM topbest = best[0];

            for (int i = 0; i < Component.Params.Input[2].Sources.Count; i++)
            {
                GH_NumberSlider slider = Component.Params.Input[2].Sources[i] as GH_NumberSlider;
                if (slider != null)
                {
                    slider.SetSliderValue((decimal)topbest.Design.DesignVariables[i].Value);
                }
            }
            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);

            // number = number of designs to select
            return(best);
        }
Example #8
0
        public List <GH_NumberSlider> readSlidersList()
        {
            slidersList.Clear();

            foreach (IGH_Param param in Params.Input[0].Sources)
            {
                GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                slidersList.Add(slider);
            }
            return(slidersList);
        }
        private void readSlidersList()
        {
            this.VarsList.Clear();

            foreach (IGH_Param param in Params.Input[0].Sources)
            {
                GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;

                DSEVariable newVar = new DSEVariable((double)slider.Slider.Minimum, (double)slider.Slider.Maximum, (double)slider.Slider.Value);
                this.VarsList.Add(newVar);
            }
        }
 private void ControlGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     for (int i = 0; i < Component.Params.Input[2].Sources.Count; i++)
     {
         GH_NumberSlider slider = Component.Params.Input[2].Sources[i] as GH_NumberSlider;
         if (slider != null)
         {
             slider.SetSliderValue((decimal)this.myViewModel.Design.DesignVariables[i].Value);
         }
     }
     Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);
 }
        // SetGeneInputs: Initializes list of input gene sliders
        private void InitializeGeneInputs()
        {
            geneInputSliders = new List <GH_NumberSlider>();

            foreach (IGH_Param source in gh.Params.Input[0].Sources)
            {
                GH_NumberSlider slider = source as GH_NumberSlider;   // Add gene pool inputs as well?

                if (slider != null)
                {
                    geneInputSliders.Add(slider);
                }
            }
        }
Example #12
0
 public static void ChangeSliders(List <GH_NumberSlider> sliders, List <double> targetVals)
 {
     if (sliders.Count != targetVals.Count)
     {
         throw new Exception("Error: Number of sliders and number of target values must be equal.");
     }
     for (int i = 0; i < sliders.Count; i++)
     {
         GH_NumberSlider s = sliders[i];
         double          d = targetVals[i];
         s.SetSliderValue((decimal)d);
     }
     Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);
 }
        // SetSliders: Sets the gene sliders to the given gene values
        internal void SetSliders(List <double> genes)
        {
            for (int i = 0; i < genes.Count; i++)
            {
                GH_NumberSlider slider = geneInputSliders[i];

                slider.Slider.RaiseEvents = false;
                slider.SetSliderValue((decimal)genes[i]);
                slider.ExpireSolution(false);
                slider.Slider.RaiseEvents = true;
            }

            RecalculateSolution();
        }
Example #14
0
        //Get Variables
        public bool SetInputs()
        {
            Sliders    = new List <GH_NumberSlider>();
            _genepools = new List <GalapagosGeneListObject>();

            var s = new GH_NumberSlider();
            var g = new GalapagosGeneListObject();

            foreach (var source in OptimizationComponent.Params.Input[0].Sources)
            {
                var guid = source.InstanceGuid;
                _inputGuids.Add(guid);
            }

            if (_inputGuids.Count == 0)
            {
                MessageBox.Show("FrOG needs at least one variable input (defined as a number slider or gene pool, of type integer or float", "FrOG Error");
                return(false);
            }

            foreach (var guid in _inputGuids)
            {
                var input = _doc.FindObject(guid, true);

                if (input == null)
                {
                    MessageBox.Show(
                        "The variables connected to FrOG are inconsistent. This error typically occurs after removing one or more connected number sliders. Please consider deleting and setting up all variables connections again.",
                        "FrOG Error");
                    return(false);
                }

                if (input.ComponentGuid == s.ComponentGuid)
                {
                    var slider = (GH_NumberSlider)input;
                    Sliders.Add(slider);
                }

                if (input.ComponentGuid == g.ComponentGuid)
                {
                    var genepool = (GalapagosGeneListObject)input;
                    _genepools.Add(genepool);
                }
            }

            SetVariables();
            return(true);
        }
        // ChangeGeneValue: Changes only one slider value for mutation and returns the new gene value
        internal double MutateGeneValue(int index)
        {
            double gene;

            GH_NumberSlider slider = geneInputSliders[index];

            slider.Slider.RaiseEvents = false;
            slider.TickValue          = random.Next(slider.TickCount + 1); // +1 (include Max value)
            gene = (double)slider.Slider.Value;
            slider.ExpireSolution(false);
            slider.Slider.RaiseEvents = true;

            RecalculateSolution();

            return(gene);
        }
        /// <summary>
        /// Constructor.
        /// Creates a new multiobjective problem instance.
        /// </summary>
        /// <param name="solutionType">The solution type must "Real" or "BinaryReal", and "ArrayReal".</param>
        /// <param name="numberOfVariables">Number of variables</param>
        public NSGAIIProblem(string solutionType, MOO comp, int solutionsCounter)
        {
            this.component      = comp;
            NumberOfVariables   = comp.readSlidersList().Count;
            NumberOfObjectives  = comp.objectives.Count;
            NumberOfConstraints = 0;
            ProblemName         = "Multiobjective";

            // Log
            comp.LogAddMessage("Number of Variables = " + NumberOfVariables);
            comp.LogAddMessage("Number of Objectives = " + NumberOfObjectives);
            comp.LogAddMessage("Number of Constraints = " + NumberOfConstraints);


            UpperLimit = new double[NumberOfVariables];
            LowerLimit = new double[NumberOfVariables];

            for (int i = 0; i < NumberOfVariables; i++)
            {
                GH_NumberSlider curSlider = comp.readSlidersList()[i];

                LowerLimit[i] = (double)curSlider.Slider.Minimum;
                UpperLimit[i] = (double)curSlider.Slider.Maximum;
            }

            if (solutionType == "BinaryReal")
            {
                SolutionType = new BinaryRealSolutionType(this);
            }
            else if (solutionType == "Real")
            {
                SolutionType = new RealSolutionType(this);
            }
            else if (solutionType == "ArrayReal")
            {
                SolutionType = new ArrayRealSolutionType(this);
            }
            else
            {
                Console.WriteLine("Error: solution type " + solutionType + " is invalid");
                //Logger.Log.Error("Solution type " + solutionType + " is invalid");
                return;
            }

            // Log
            comp.LogAddMessage("Solution Type = " + solutionType);
        }
 //Preset slider values to calculated weights
 public void presetSliders(List <String> nicknames, List <double> values)
 {
     for (int i = 0; i < values.Count; i++)
     {
         foreach (IGH_DocumentObject obj in this.OnPingDocument().Objects)
         {
             GH_NumberSlider slider = obj as GH_NumberSlider;
             if (slider == null)
             {
                 continue;
             }
             if (slider.NickName.Equals(nicknames[i], StringComparison.OrdinalIgnoreCase))
             {
                 slider.Slider.Value = (decimal)values[i];
             }
         }
     }
 }
Example #18
0
        private IGH_Param CreateIntegerSlider(int d)
        {
            var slider = new GH_NumberSlider();

            slider.CreateAttributes();

            // setup the slider according to the grid
            // each slider account for one grid dimension
            var t0 = ghGrid.Value.Intervals[d].T0;
            var t1 = ghGrid.Value.Intervals[d].T1;

            slider.Slider.Type    = Grasshopper.GUI.Base.GH_SliderAccuracy.Integer;
            slider.Slider.Minimum = (decimal)t0;
            slider.Slider.Maximum = (decimal)t1 - 1;
            slider.SetSliderValue((decimal)(0.5 * (t0 + t1)));

            return(slider);
        }
        public override void Evaluate(Solution solution)
        {
            // Current Solution
            List <double> currentSolution = new List <double>();

            double[] storeVar = new double[NumberOfVariables];
            double[] storeObj = new double[NumberOfObjectives];
            XReal    x        = new XReal(solution);

            // Reading x values
            double[] xValues = new double[NumberOfVariables];
            for (int i = 0; i < NumberOfVariables; i++)
            {
                xValues[i] = x.GetValue(i);
                var1Value.Add(x.GetValue(0));
                var2Value.Add(x.GetValue(1));

                currentSolution.Add(x.GetValue(i)); // add current variable value to current solution
            }
            GH_NumberSlider currentSlider = null;

            for (int i = 0; i < component.readSlidersList().Count; i++)
            {
                currentSlider = component.readSlidersList()[i];
                currentSlider.SetSliderValue((decimal)x.GetValue(i));
                //Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true); //<- NOTE: Is this the part that's re-evaluating after every slider change??
            }

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

            for (int i = 0; i < component.objectives.Count; i++)
            {
                solution.Objective[i] = component.objectives[i];

                currentSolution.Add(component.objectives[i]); //adding current i-objective to current solution
            }
            //component.allSolutions = component.allSolutions +"" + component.objectives[i] + " ";

            allSolutions.Add(currentSolution);
        }
Example #20
0
        //Methods

        //Automatically add a slider to the canvas
        void addWeightSlider(bool addSlider)
        {
            if (addSlider)
            {
                //Instantiate new slider
                GH_NumberSlider slider = new GH_NumberSlider();
                slider.CreateAttributes();                              //set to default values

                //Customisation of values
                int inputCount = this.Params.Input[1].SourceCount;      //count the number of connected inputs
                slider.Attributes.Pivot     = new PointF((float)this.Attributes.DocObject.Attributes.Bounds.Left - slider.Attributes.Bounds.Width - 30, (float)this.Params.Input[1].Attributes.Bounds.Y + inputCount * 30);
                slider.Slider.Minimum       = -1;
                slider.Slider.Maximum       = 1;
                slider.Slider.DecimalPlaces = 2;
                slider.SetSliderValue((decimal)0.00);
                slider.NickName = String.Format("w{0}", inputCount);

                //Add the slider to the canvas
                OnPingDocument().AddObject(slider, false);
                this.Params.Input[1].AddSource(slider);
            }
        }
Example #21
0
        // Remote controller setting up the solution
        private void PrepareSolution(GH_Document gH_Document)
        {
            System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0);
            CurrentJobClient = ( string )t.Key;

            foreach (dynamic param in ( IEnumerable )t.Value)
            {
                IGH_DocumentObject controller = null;
                try
                {
                    controller = Document.Objects.First(doc => doc.InstanceGuid.ToString() == param.guid);
                }
                catch { }
                if (controller != null)
                {
                    switch (( string )param.inputType)
                    {
                    case "TextPanel":
                        GH_Panel panel = controller as GH_Panel;
                        panel.UserText = ( string )param.value;
                        panel.ExpireSolution(false);
                        break;

                    case "Slider":
                        GH_NumberSlider slider = controller as GH_NumberSlider;
                        slider.SetSliderValue(decimal.Parse(param.value.ToString()));
                        break;

                    case "Toggle":
                        break;

                    default:
                        break;
                    }
                }
            }
            SolutionPrepared = true;
        }
        /// <summary>
        /// /
        /// </summary>
        /// <param name="popsize"></param>
        /// <param name="mutrate"></param>
        /// <returns></returns>

        //public List<DesignVM> NewGeneration(int popsize, double mutrate)
        //{
        //    List<DesignVM> newgen = new List<DesignVM>();
        //    Random r = new Random();
        //    for (int i = 0; i < popsize; i++)
        //    {
        //        List<decimal> paramvalues = new List<decimal>();
        //        foreach (IGH_Param param in Component.Params.Input[2].Sources) // dvar is input 2
        //        {
        //            GH_NumberSlider slider = param as GH_NumberSlider;
        //            decimal n = r.Next(10);
        //            Console.WriteLine(n);
        //            if (slider != null)
        //                slider.SetSliderValue(n);
        //            paramvalues.Add(n);
        //        }
        //        Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);
        //        //ComputedStructure comp = (ComputedStructure)Component.compstruc.CloneImpl();
        //        List<Rhino.Geometry.Line> lines = Component.DesignLines;
        //        newgen.Add(new DesignVM(lines, false,true, Component.Score, paramvalues));
        //    }
        //    List<DesignVM> newgensorted = newgen.OrderBy(x => x.Score).ToList(); //here?
        //    return newgensorted;
        //}

        public List <DesignVM> GenDesignVMs(List <Design> listDesigns)
        {
            List <DesignVM> generatedDesigns = new List <DesignVM>();

            foreach (Design design in listDesigns)
            {
                for (int i = 0; i < Component.Params.Input[2].Sources.Count; i++)
                {
                    GH_NumberSlider slider = Component.Params.Input[2].Sources[i] as GH_NumberSlider;
                    if (slider != null)
                    {
                        slider.SetSliderValue((decimal)design.DesignVariables[i].Value);
                    }
                }
                Grasshopper.Instances.ActiveCanvas.Document.NewSolution(true);
                List <Rhino.Geometry.Line>  lines  = Component.DesignLines;
                List <Rhino.Geometry.Curve> curves = Component.DesignCurves;
                List <Rhino.Geometry.Mesh>  meshes = Component.DesignMeshes;
                List <Rhino.Geometry.Brep>  breps  = Component.DesignBreps;

                generatedDesigns.Add(new DesignVM(lines, curves, meshes, breps, false, true, Component.Score, design));
            }
            return(generatedDesigns);
        }
Example #23
0
        /// <summary>
        /// Grasshopper solveinstance
        /// </summary>
        /// <param name="DA"></param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <string>            genoGuids = new List <string>();
            GH_Structure <GH_Number> populationData;

            if (!DA.GetDataList <string>("GenoGuids", genoGuids))
            {
                return;
            }
            if (!DA.GetDataTree("Population", out populationData))
            {
                if (populationData == null)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No population data!");
                    return;
                }
                else
                {
                    Message = "Popcount = " + populationData.Branches.Count;
                }
            }

            if (!DA.GetData <GH_Integer>("DesignID", ref designID))
            {
                return;
            }
            ;


            // Horrible workaround for genepools. I'm completely lost finding a better way to be honest.
            // Maybe only trigger this bit IF the input data has changed in some way? That might solve the Embryo problem.

            if (isActive)
            {
                //GH_Path
                List <double> genes = new List <double>();
                for (int i = 0; i < populationData.get_Branch(i).Count; i++)
                {
                    double myDouble;
                    GH_Convert.ToDouble(populationData.get_Branch(designID.Value)[i], out myDouble, GH_Conversion.Primary);
                    genes.Add(myDouble);
                }

                List <GH_NumberSlider>         theSliders   = new List <GH_NumberSlider>();
                List <GalapagosGeneListObject> theGenePools = new List <GalapagosGeneListObject>();

                bool flag    = false;
                int  counter = 0;

                foreach (string myGuid in genoGuids)
                {
                    try
                    {
                        System.Guid me = new Guid(myGuid);

                        // Try for a slider
                        GH_NumberSlider slidy = OnPingDocument().FindObject <GH_NumberSlider>(me, true);
                        if (slidy != null)
                        {
                            theSliders.Add(slidy);
                            counter++;
                        }

                        // Try for a genepool
                        GalapagosGeneListObject pooly = OnPingDocument().FindObject <GalapagosGeneListObject>(me, true);
                        if (pooly != null)
                        {
                            theGenePools.Add(pooly);
                            counter += pooly.Count;
                        }
                    }
                    catch
                    {
                        flag = true;
                    }
                }

                if (flag)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No slider or genepool found at specified guid. Has the definition been altered?");
                    return;
                }


                // Catch an unequal amount of sliders and genes/guids
                if (genes.Count != counter)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Guid count does not equal chromosome gene count");
                    return;
                }

                canvas.Document.Enabled = false;
                SetSliders(genes, theSliders, theGenePools);
                canvas.Document.Enabled = true;

                if (theGenePools.Count > 0)
                {
                    isActive = false;
                }
            }

            else
            {
                // Turn the thing back on without setting all the sliders etc.
                isActive = true;
            }
        }
Example #24
0
        object RunPermutations(int[] lengths, GH_BooleanToggle boolTrigger, List <GH_NumberSlider> sliders, GH_SolutionEventArgs e, params object[] objs)
        {
            // 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();

            Stopwatch sw      = Stopwatch.StartNew();
            int       counter = 0;

            foreach (int[] idxs in new IterateNDArray(lengths))
            {
                // 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(null);
                    }
                }

                for (int i = 0; i < sliders.Count; i++)
                {
                    GH_NumberSlider slider = sliders[i];

                    //look up the current slider's current sliderStepsPosition and target number
                    int totalNumberOfSteps = sliderSteps[i];
                    int steps = slider.TickCount / sliderSteps[i];
                    slider.TickValue = steps * idxs[i];
                    //int numTicksToAddAsInt = slider.TickCount / totalNumberOfSteps;
                    //double numTicksToAddAsDouble = (double)slider.TickCount / (double)totalNumberOfSteps;

                    ////find the closest tick
                    //int closestTick = 0;
                    //if (currentSliderStepsPosition + numTicksToAddAsInt >= sliderMidStep)
                    //{
                    //    closestTick = (int)Math.Ceiling(numTicksToAddAsDouble * currentSliderStepsPosition);
                    //}
                    //else
                    //{
                    //    closestTick = (int)Math.Floor(numTicksToAddAsDouble * currentSliderStepsPosition);
                    //}

                    // Increment the slider.
                }

                // 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);
            }

            // 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
            sliderNames          = new List <string>();
            sliderSteps          = new int[sliderNames.Count];
            sliderStepsPositions = new int[sliderNames.Count];
            computedValues       = new List <string>();
            e.Document.NewSolution(false);
            Rhino.RhinoDoc.ActiveDoc.Views.Redraw();

            return(null);
        }
Example #25
0
        public void PrepareSolution(IEnumerable args)
        {
            var x = args;

            foreach (dynamic param in args)
            {
                IGH_DocumentObject controller = null;
                try
                {
                    controller = Document.Objects.First(doc => doc.InstanceGuid.ToString() == param.guid);
                }
                catch { }

                if (controller != null)
                {
                    switch (( string )param.type)
                    {
                    case "TextPanel":
                        GH_Panel panel = controller as GH_Panel;
                        panel.UserText = ( string )param.value;
                        panel.ExpireSolution(false);
                        break;

                    case "Slider":
                        GH_NumberSlider slider = controller as GH_NumberSlider;
                        slider.SetSliderValue(decimal.Parse(param.value.ToString()));
                        break;

                    case "Point":
                        PointController p    = controller as PointController;
                        var             xxxx = p;
                        p.setParam(( double )param.value.X, ( double )param.value.Y, ( double )param.value.Z);
                        break;

                    case "Toggle":
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    try
                    {
                        if (param.type == "MaterialTable")
                        {
                            var MatOut = ( GH_Panel )Document.Objects.FirstOrDefault(doc => doc.NickName == "MAT_OUT");
                            if (MatOut != null)
                            {
                                string mats = "";
                                foreach (var layer in param.layers)
                                {
                                    try
                                    {
                                        mats += layer.name + ":" + layer.material + ":" + layer.price + "\n";
                                    }
                                    catch { }
                                }

                                MatOut.UserText = mats;
                                MatOut.ExpireSolution(true);
                            }
                        }
                    }
                    catch { }
                }
            }
            // TODO: Expire component
            Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction);
        }
 public DVariableGH(GH_NumberSlider slider)
 {
     this.Slider = slider;
 }
Example #27
0
        protected int FindFrameObject(IGH_DataAccess DA)
        {
            if (this.Params.Input[0].SourceCount == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Please input a NumberSlider or a VrayTimeLine to Input Frame.");
                return(int.MinValue);
            }

            FrameObject = this.Params.Input[0].Sources[0].Attributes.GetTopLevel.DocObject;
            if (FrameObject is GH_NumberSlider)
            {
                this.IsInputASlider = true;
                GH_NumberSlider frameSlider = FrameObject as GH_NumberSlider;

                if (frameSlider.Slider.Maximum != this.MaxFrame)
                {
                    frameSlider.Slider.Maximum = this.MaxFrame;
                }
                if (frameSlider.Slider.Minimum != 0)
                {
                    frameSlider.Slider.Minimum = 0;
                }
                frameSlider.Slider.Type = Grasshopper.GUI.Base.GH_SliderAccuracy.Integer;

                if (frameSlider.Slider.Value > frameSlider.Slider.Maximum)
                {
                    frameSlider.Slider.Value = frameSlider.Slider.Maximum;
                }
                else if (frameSlider.Slider.Value < frameSlider.Slider.Minimum)
                {
                    frameSlider.Slider.Value = frameSlider.Slider.Minimum;
                }

                frameSlider.NickName = "Frames";

                frameSlider.Expression = "X * " + this.FrameTimeLast.ToString() + " + " + (this.TimeInFrame * FrameTimeLast).ToString();

                this.SliderWidth = (float)(this.MaxTime * SliderMultiple) + 20;
                this.SliderWidth = SliderWidth > 120 ? SliderWidth : 120;

                float beforeWidth = frameSlider.Attributes.Bounds.Width;


                int SliderBigger = (int)SliderWidth - frameSlider.Slider.Bounds.Width;
                frameSlider.Attributes.Bounds = new RectangleF(frameSlider.Attributes.Bounds.X, frameSlider.Attributes.Bounds.Y,
                                                               frameSlider.Attributes.Bounds.Width + SliderBigger, frameSlider.Attributes.Bounds.Height);

                float afterWidth = frameSlider.Attributes.Bounds.Width;
                float X          = frameSlider.Attributes.Pivot.X - (afterWidth - beforeWidth);
                frameSlider.Attributes.Pivot = new PointF(X, frameSlider.Attributes.Pivot.Y);

                frameSlider.OnPingDocument().DestroyAttributeCache();
                frameSlider.Attributes.ExpireLayout();
                frameSlider.Attributes.PerformLayout();

                this.Params.Input[1].Optional = false;

                return((int)frameSlider.Slider.Value);
            }

            else if (FrameObject.GetType().ToString() == "VRayForGrasshopper.VRayTimelineComponent")
            {
                this.IsInputASlider = false;
                GH_Component VrayComponent = FrameObject as GH_Component;
                SliderWidth = VrayComponent.Attributes.Bounds.Width - VrayComponent.Params.InputWidth - VrayComponent.Params.OutputWidth - 4;
                if ((VrayComponent.Params.Input[0].VolatileData.AllData(true).ElementAt(0) as GH_Integer).Value != this.MaxFrame)
                {
                    VrayComponent.Params.Input[0].VolatileData.Clear();
                    VrayComponent.Params.Input[0].AddVolatileData(new Grasshopper.Kernel.Data.GH_Path(0), 0, this.MaxFrame);
                    VrayComponent.ExpireSolution(true);
                }
                this.Params.Input[1].Optional = true;

                this.Save = false;

                int inputFrame = 0;
                DA.GetData("Current Frame", ref inputFrame);
                return(inputFrame);
            }

            else
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Only NumberSlider and VrayTimeLine are allowed for Input Frame!");
                FrameObject = null;
                return(int.MinValue);
            }
        }
        public static Response Grasshopper(NancyContext ctx)
        {
            // load grasshopper file
            var archive = new GH_Archive();
            // TODO: stream to string
            var body = ctx.Request.Body.ToString();

            string json = string.Empty;

            using (var reader = new StreamReader(ctx.Request.Body))
            {
                json = reader.ReadToEnd();
            }

            //GrasshopperInput input = Newtonsoft.Json.JsonConvert.DeserializeObject<GrasshopperInput>(json);
            //JsonSerializerSettings settings = new JsonSerializerSettings();
            //settings.ContractResolver = new DictionaryAsArrayResolver();
            Schema input = JsonConvert.DeserializeObject <Schema>(json);

            string grasshopperXml = string.Empty;

            if (input.Algo != null)
            {
                // If request contains markup
                byte[] byteArray = Convert.FromBase64String(input.Algo);
                grasshopperXml = System.Text.Encoding.UTF8.GetString(byteArray);
            }
            else
            {
                // If request contains pointer
                string pointer = input.Pointer;
                grasshopperXml = GetGhxFromPointer(pointer);
            }
            if (!archive.Deserialize_Xml(grasshopperXml))
            {
                throw new Exception();
            }

            var definition = new GH_Document();

            if (!archive.ExtractObject(definition, "Definition"))
            {
                throw new Exception();
            }

            // Set input params
            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                if (group.NickName.Contains("RH_IN"))
                {
                    // It is a RestHopper input group!
                    GHTypeCodes code  = (GHTypeCodes)Int32.Parse(group.NickName.Split(':')[1]);
                    var         param = group.Objects()[0];
                    //GH_Param<IGH_Goo> goo = obj as GH_Param<IGH_Goo>;

                    // SetData
                    foreach (Resthopper.IO.DataTree <ResthopperObject> tree in input.Values)
                    {
                        string paramname = tree.ParamName;
                        if (group.NickName == paramname)
                        {
                            switch (code)
                            {
                            case GHTypeCodes.Boolean:
                                //PopulateParam<GH_Boolean>(goo, tree);
                                Param_Boolean boolParam = param as Param_Boolean;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Boolean> objectList = new List <GH_Boolean>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj = entree.Value[i];
                                        bool             boolean = JsonConvert.DeserializeObject <bool>(restobj.Data);
                                        GH_Boolean       data    = new GH_Boolean(boolean);
                                        boolParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Point:
                                //PopulateParam<GH_Point>(goo, tree);
                                Param_Point ptParam = param as Param_Point;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Point> objectList = new List <GH_Point>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject       restobj = entree.Value[i];
                                        Rhino.Geometry.Point3d rPt     = JsonConvert.DeserializeObject <Rhino.Geometry.Point3d>(restobj.Data);
                                        GH_Point data = new GH_Point(rPt);
                                        ptParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Vector:
                                //PopulateParam<GH_Vector>(goo, tree);
                                Param_Vector vectorParam = param as Param_Vector;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Vector> objectList = new List <GH_Vector>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject        restobj  = entree.Value[i];
                                        Rhino.Geometry.Vector3d rhVector = JsonConvert.DeserializeObject <Rhino.Geometry.Vector3d>(restobj.Data);
                                        GH_Vector data = new GH_Vector(rhVector);
                                        vectorParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Integer:
                                //PopulateParam<GH_Integer>(goo, tree);
                                Param_Integer integerParam = param as Param_Integer;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Integer> objectList = new List <GH_Integer>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj = entree.Value[i];
                                        int        rhinoInt      = JsonConvert.DeserializeObject <int>(restobj.Data);
                                        GH_Integer data          = new GH_Integer(rhinoInt);
                                        integerParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Number:
                                //PopulateParam<GH_Number>(goo, tree);
                                Param_Number numberParam = param as Param_Number;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Number> objectList = new List <GH_Number>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        double           rhNumber = JsonConvert.DeserializeObject <double>(restobj.Data);
                                        GH_Number        data     = new GH_Number(rhNumber);
                                        numberParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Text:
                                //PopulateParam<GH_String>(goo, tree);
                                Param_String stringParam = param as Param_String;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_String> objectList = new List <GH_String>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        string           rhString = JsonConvert.DeserializeObject <string>(restobj.Data);
                                        GH_String        data     = new GH_String(rhString);
                                        stringParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Line:
                                //PopulateParam<GH_Line>(goo, tree);
                                Param_Line lineParam = param as Param_Line;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path        path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Line> objectList = new List <GH_Line>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject    restobj = entree.Value[i];
                                        Rhino.Geometry.Line rhLine  = JsonConvert.DeserializeObject <Rhino.Geometry.Line>(restobj.Data);
                                        GH_Line             data    = new GH_Line(rhLine);
                                        lineParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Curve:
                                //PopulateParam<GH_Curve>(goo, tree);
                                Param_Curve curveParam = param as Param_Curve;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Curve> objectList = new List <GH_Curve>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj = entree.Value[i];
                                        GH_Curve         ghCurve;
                                        try
                                        {
                                            Rhino.Geometry.Polyline data = JsonConvert.DeserializeObject <Rhino.Geometry.Polyline>(restobj.Data);
                                            Rhino.Geometry.Curve    c    = new Rhino.Geometry.PolylineCurve(data);
                                            ghCurve = new GH_Curve(c);
                                        }
                                        catch
                                        {
                                            Rhino.Geometry.NurbsCurve data = JsonConvert.DeserializeObject <Rhino.Geometry.NurbsCurve>(restobj.Data);
                                            Rhino.Geometry.Curve      c    = new Rhino.Geometry.NurbsCurve(data);
                                            ghCurve = new GH_Curve(c);
                                        }
                                        curveParam.AddVolatileData(path, i, ghCurve);
                                    }
                                }
                                break;

                            case GHTypeCodes.Circle:
                                //PopulateParam<GH_Circle>(goo, tree);
                                Param_Circle circleParam = param as Param_Circle;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Circle> objectList = new List <GH_Circle>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject      restobj  = entree.Value[i];
                                        Rhino.Geometry.Circle rhCircle = JsonConvert.DeserializeObject <Rhino.Geometry.Circle>(restobj.Data);
                                        GH_Circle             data     = new GH_Circle(rhCircle);
                                        circleParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.PLane:
                                //PopulateParam<GH_Plane>(goo, tree);
                                Param_Plane planeParam = param as Param_Plane;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Plane> objectList = new List <GH_Plane>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject     restobj = entree.Value[i];
                                        Rhino.Geometry.Plane rhPlane = JsonConvert.DeserializeObject <Rhino.Geometry.Plane>(restobj.Data);
                                        GH_Plane             data    = new GH_Plane(rhPlane);
                                        planeParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Rectangle:
                                //PopulateParam<GH_Rectangle>(goo, tree);
                                Param_Rectangle rectangleParam = param as Param_Rectangle;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path             path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Rectangle> objectList = new List <GH_Rectangle>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject           restobj     = entree.Value[i];
                                        Rhino.Geometry.Rectangle3d rhRectangle = JsonConvert.DeserializeObject <Rhino.Geometry.Rectangle3d>(restobj.Data);
                                        GH_Rectangle data = new GH_Rectangle(rhRectangle);
                                        rectangleParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Box:
                                //PopulateParam<GH_Box>(goo, tree);
                                Param_Box boxParam = param as Param_Box;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path       path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Box> objectList = new List <GH_Box>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject   restobj = entree.Value[i];
                                        Rhino.Geometry.Box rhBox   = JsonConvert.DeserializeObject <Rhino.Geometry.Box>(restobj.Data);
                                        GH_Box             data    = new GH_Box(rhBox);
                                        boxParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Surface:
                                //PopulateParam<GH_Surface>(goo, tree);
                                Param_Surface surfaceParam = param as Param_Surface;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Surface> objectList = new List <GH_Surface>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject       restobj   = entree.Value[i];
                                        Rhino.Geometry.Surface rhSurface = JsonConvert.DeserializeObject <Rhino.Geometry.Surface>(restobj.Data);
                                        GH_Surface             data      = new GH_Surface(rhSurface);
                                        surfaceParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Brep:
                                //PopulateParam<GH_Brep>(goo, tree);
                                Param_Brep brepParam = param as Param_Brep;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path        path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Brep> objectList = new List <GH_Brep>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject    restobj = entree.Value[i];
                                        Rhino.Geometry.Brep rhBrep  = JsonConvert.DeserializeObject <Rhino.Geometry.Brep>(restobj.Data);
                                        GH_Brep             data    = new GH_Brep(rhBrep);
                                        brepParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Mesh:
                                //PopulateParam<GH_Mesh>(goo, tree);
                                Param_Mesh meshParam = param as Param_Mesh;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path        path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Mesh> objectList = new List <GH_Mesh>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject    restobj = entree.Value[i];
                                        Rhino.Geometry.Mesh rhMesh  = JsonConvert.DeserializeObject <Rhino.Geometry.Mesh>(restobj.Data);
                                        GH_Mesh             data    = new GH_Mesh(rhMesh);
                                        meshParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Slider:
                                //PopulateParam<GH_Number>(goo, tree);
                                GH_NumberSlider sliderParam = param as GH_NumberSlider;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path          path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Number> objectList = new List <GH_Number>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        double           rhNumber = JsonConvert.DeserializeObject <double>(restobj.Data);
                                        GH_Number        data     = new GH_Number(rhNumber);
                                        sliderParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.BooleanToggle:
                                //PopulateParam<GH_Boolean>(goo, tree);
                                GH_BooleanToggle toggleParam = param as GH_BooleanToggle;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path           path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Boolean> objectList = new List <GH_Boolean>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj   = entree.Value[i];
                                        bool             rhBoolean = JsonConvert.DeserializeObject <bool>(restobj.Data);
                                        GH_Boolean       data      = new GH_Boolean(rhBoolean);
                                        toggleParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;

                            case GHTypeCodes.Panel:
                                //PopulateParam<GH_String>(goo, tree);
                                GH_Panel panelParam = param as GH_Panel;
                                foreach (KeyValuePair <string, List <ResthopperObject> > entree in tree)
                                {
                                    GH_Path         path       = new GH_Path(GhPath.FromString(entree.Key));
                                    List <GH_Panel> objectList = new List <GH_Panel>();
                                    for (int i = 0; i < entree.Value.Count; i++)
                                    {
                                        ResthopperObject restobj  = entree.Value[i];
                                        string           rhString = JsonConvert.DeserializeObject <string>(restobj.Data);
                                        GH_String        data     = new GH_String(rhString);
                                        panelParam.AddVolatileData(path, i, data);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }

            Schema OutputSchema = new Schema();

            OutputSchema.Algo = Utils.Base64Encode(string.Empty);

            // Parse output params
            foreach (var obj in definition.Objects)
            {
                var group = obj as GH_Group;
                if (group == null)
                {
                    continue;
                }

                if (group.NickName.Contains("RH_OUT"))
                {
                    // It is a RestHopper output group!
                    GHTypeCodes code  = (GHTypeCodes)Int32.Parse(group.NickName.Split(':')[1]);
                    var         param = group.Objects()[0] as IGH_Param;
                    if (param == null)
                    {
                        continue;
                    }

                    try
                    {
                        param.CollectData();
                        param.ComputeData();
                    }
                    catch (Exception)
                    {
                        param.Phase = GH_SolutionPhase.Failed;
                        // TODO: throw something better
                        throw;
                    }

                    // Get data
                    Resthopper.IO.DataTree <ResthopperObject> OutputTree = new Resthopper.IO.DataTree <ResthopperObject>();
                    OutputTree.ParamName = group.NickName;

                    var volatileData = param.VolatileData;
                    for (int p = 0; p < volatileData.PathCount; p++)
                    {
                        List <ResthopperObject> ResthopperObjectList = new List <ResthopperObject>();
                        foreach (var goo in volatileData.get_Branch(p))
                        {
                            if (goo == null)
                            {
                                continue;
                            }
                            else if (goo.GetType() == typeof(GH_Boolean))
                            {
                                GH_Boolean ghValue = goo as GH_Boolean;
                                bool       rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <bool>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Point))
                            {
                                GH_Point ghValue = goo as GH_Point;
                                Point3d  rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Point3d>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Vector))
                            {
                                GH_Vector ghValue = goo as GH_Vector;
                                Vector3d  rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Vector3d>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Integer))
                            {
                                GH_Integer ghValue = goo as GH_Integer;
                                int        rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <int>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Number))
                            {
                                GH_Number ghValue = goo as GH_Number;
                                double    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <double>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_String))
                            {
                                GH_String ghValue = goo as GH_String;
                                string    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <string>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Line))
                            {
                                GH_Line ghValue = goo as GH_Line;
                                Line    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Line>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Curve))
                            {
                                GH_Curve ghValue = goo as GH_Curve;
                                Curve    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Curve>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Circle))
                            {
                                GH_Circle ghValue = goo as GH_Circle;
                                Circle    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Circle>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Plane))
                            {
                                GH_Plane ghValue = goo as GH_Plane;
                                Plane    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Plane>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Rectangle))
                            {
                                GH_Rectangle ghValue = goo as GH_Rectangle;
                                Rectangle3d  rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Rectangle3d>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Box))
                            {
                                GH_Box ghValue = goo as GH_Box;
                                Box    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Box>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Surface))
                            {
                                GH_Surface ghValue = goo as GH_Surface;
                                Brep       rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Brep>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Brep))
                            {
                                GH_Brep ghValue = goo as GH_Brep;
                                Brep    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Brep>(rhValue));
                            }
                            else if (goo.GetType() == typeof(GH_Mesh))
                            {
                                GH_Mesh ghValue = goo as GH_Mesh;
                                Mesh    rhValue = ghValue.Value;
                                ResthopperObjectList.Add(GetResthopperObject <Mesh>(rhValue));
                            }
                        }

                        GhPath path = new GhPath(new int[] { p });
                        OutputTree.Add(path.ToString(), ResthopperObjectList);
                    }

                    OutputSchema.Values.Add(OutputTree);
                }
            }


            if (OutputSchema.Values.Count < 1)
            {
                throw new System.Exceptions.PayAttentionException("Looks like you've missed something..."); // TODO
            }
            string returnJson = JsonConvert.SerializeObject(OutputSchema);

            return(returnJson);
        }
Example #29
0
        /// <summary>
        /// Grasshopper solveinstance
        /// </summary>
        /// <param name="DA"></param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get Solution and data
            BiomorpherGoo temp = new BiomorpherGoo();

            if (!DA.GetData("Solution", ref temp))
            {
                return;
            }
            solutionData = temp.Value;

            if (!DA.GetData <int>("Branch", ref branch))
            {
                return;
            }
            ;
            if (!DA.GetData <int>("Generation", ref generation))
            {
                return;
            }
            ;
            if (!DA.GetData <int>("Design", ref design))
            {
                return;
            }
            ;

            // Check to see if we have anything at all (population is the lowest possible thing in the hierarchy)
            if (solutionData.historicData == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Empty biomorpher solution!");
                return;
            }

            // If we have then display the number of designs in a typical population
            else
            {
                Message = "Population size = " + solutionData.PopCount;
            }

            // Only if things have changed do we actually want to change the sliders and expire the solution
            if (branch != localBranch || localGeneration != generation || localDesign != design || !localSolutionData.Equals(solutionData))
            {
                localBranch       = branch;
                localGeneration   = generation;
                localDesign       = design;
                localSolutionData = solutionData;
                active            = true;
            }

            else
            {
                active = false;
            }

            // Only do things if there is a design at the location
            if (solutionData.historicData.get_Branch(new GH_Path(branch, generation, design)) != null)
            {
                if (active)
                {
                    //We need a list of genes for the selected design
                    List <double> genes = new List <double>();

                    // g
                    for (int i = 0; i < solutionData.historicData.get_Branch(new GH_Path(branch, generation, design)).Count; i++)
                    {
                        double myDouble;
                        GH_Convert.ToDouble(solutionData.historicData.get_Branch(new GH_Path(branch, generation, design))[i], out myDouble, GH_Conversion.Primary);
                        genes.Add(myDouble);
                    }

                    // Set up some local sliders and genepools
                    List <GH_NumberSlider>         theSliders   = new List <GH_NumberSlider>();
                    List <GalapagosGeneListObject> theGenePools = new List <GalapagosGeneListObject>();

                    bool flag = false;

                    // Note that the sliders and genepools are stored in two branches of a GH_Structure
                    try
                    {
                        // Get sliders
                        List <GH_Guid> sliderList = new List <GH_Guid>();

                        foreach (GH_Guid x in solutionData.genoGuids.get_Branch(0))
                        {
                            GH_NumberSlider slidy = OnPingDocument().FindObject <GH_NumberSlider>(x.Value, true);
                            if (slidy != null)
                            {
                                theSliders.Add(slidy);
                            }
                        }

                        // Get genepools
                        foreach (GH_Guid x in solutionData.genoGuids.get_Branch(1))
                        {
                            GalapagosGeneListObject pooly = OnPingDocument().FindObject <GalapagosGeneListObject>(x.Value, true);
                            if (pooly != null)
                            {
                                theGenePools.Add(pooly);
                            }
                        }
                    }
                    catch
                    {
                        flag = true;
                    }


                    if (flag)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Getting sliders and/or genepools from the canvas was unsuccesful. Have they been modified?");
                        return;
                    }

                    canvas.Document.Enabled = false;
                    //this.Locked = true;

                    SetSliders(genes, theSliders, theGenePools);

                    canvas.Document.Enabled = true;
                    canvas.Document.ExpireSolution();
                }
            }


            else
            {
                // Turn the thing back on without setting all the sliders etc.
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No historic design found at this reference");
            }
        }
Example #30
0
        public void RunSolver()
        {
            //updateMessage("sampling");
            //ExpireSolution(true);
            status = "sampling";
            updateMessage(status);

            // Get the document this component belongs to.
            GH_Document doc = OnPingDocument();

            if (doc == null)
            {
                return;
            }

            // First figure out which sliders are to be used as inputs.
            // This means iterating over all sources of the first input parameter,
            // and seeing if they are sliders. If we find something other than a slider,
            // print an error message and abort.

            List <GH_NumberSlider> sliders = new List <GH_NumberSlider>();
            //List<List<string>> slider_ranges = new List<List<string>>(); // to store slider ranges for sampling

            ////// generate sampling data based on plugged sliders //////
            var csv = new StringBuilder();

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

            foreach (IGH_Param source in Params.Input[0].Sources)
            {
                GH_NumberSlider slider = source as GH_NumberSlider;
                if (slider == null)
                {
                    Rhino.RhinoApp.Write("One of the inputs is not a slider.");
                    return;
                }
                sliders.Add(slider);
                //this.pluggedSliders.Add(slider);



                var nickname = source.NickName;
                names.Add(nickname.ToString());  // Add slider name to global list
                var minimum = (slider.Slider.Minimum).ToString("0.00");
                var maximum = (slider.Slider.Maximum).ToString("0.00");

                var newLine = string.Format("{0}, {1}, {2}", nickname, minimum, maximum);
                csv.AppendLine(newLine);


                // now write slider_ranges list to csv file and pass as parameter for python system call
            }
            this.pluggedSliders     = sliders;
            this.pluggedSliderNames = names;

            //string direc = this.Params.Input[2].Sources[0].VolatileData.ToString(); // need to check what this is returning
            //Grasshopper.Kernel.Parameters.Param_String param = (Grasshopper.Kernel.Parameters.Param_String)this.Params.Input[2];
            //string direc = param.PersistentData.ToString();

            //Param_String param0 = Params.Input[2] as Param_String;
            //GH_Structure<GH_String> data = param0.VolatileData as GH_Structure<GH_String>;

            //GH_String dat = data.AllData(true);


            // access directory string
            foreach (GH_String dat in Params.Input[2].Sources[0].VolatileData.AllData(true))

            {
                string directory = dat.Value;


                //    Grasshopper.Kernel.IGH_Param sourceZ = this.Params.Input[2].Sources[0].VolatileData; //ref for input where a boolean or a button is connected
                //Grasshopper.Kernel.Types.GH_String text = sourceZ as Grasshopper.Kernel.Types.GH_String;
                //string direc = text.Value;

                string ranges_filepath = Path.Combine(directory, "ranges.txt");

                File.WriteAllText(ranges_filepath, csv.ToString());

                /// run python script to generate samples ///
                string samplingscript_filepath = Path.Combine(directory, "Lab_Mouse\\IPC_scripts\\datagen_IPC.py");
                //string samplingscript_filepath = "Lab_Mouse\\IPC_scripts\\datagen_IPC.py";

                //string samplingscript_filepath = "C:\\Users\\zac067\\Desktop\\intercommunication_script.py"; // TODO: internalise this script in the component dll?

                List <System.Object> Arguments = new List <System.Object>();
                //Arguments.Add(ranges_filepath);
                Arguments.Add(this.directory);

                //string type = "sobol";
                Arguments.Add(this.samplingAlgorithm);

                int samplesize = 5000;
                Arguments.Add(samplesize.ToString());



                // Generate samples by calling sampling Python script //
                List <List <double> > Samples = runPythonScript(samplingscript_filepath, Arguments);

                // Print samples to Rhino Console
                for (int j = 0; j < Samples.Count; j++)
                {
                    for (int k = 0; k < Samples[j].Count; k++)
                    {
                        Console.WriteLine(Samples[j][k]);
                    }
                }

                if (sliders.Count == 0)
                {
                    Rhino.RhinoApp.Write("At least one variable slider must be connected to the X input.");
                    return;
                }

                // Similarly, we need to find which number parameter is to be used as the measure.
                // We only accept a single one, and it may only be a Param_Number (you may want to make
                // this more flexible in production code).

                var outputs = Params.Input[1].Sources;

                List <POutput> poutputs = new List <POutput>();
                List <string>  outnames = new List <string>();


                foreach (IGH_Param source in outputs)
                {
                    POutput poutput = source as POutput;
                    if (poutput == null)
                    {
                        Rhino.RhinoApp.Write("One of the outputs is not of POutput type");
                        return;
                    }
                    poutputs.Add(poutput);
                    outnames.Add(poutput.NickName.ToString());



                    var nickname = source.NickName;
                }

                this.pluggedPOutputs    = new List <POutput>(poutputs);
                this.pluggedOutputNames = new List <string>(outnames);
                //for (int o = 0; o < outputs.Count; o++)
                //{
                //    poutputs.Add(outputs[o] as POutput);
                //    outnames.Add(outputs[o].NickName.ToString());

                //}

                //update list of plugged POutputs
                //this.pluggedPOutputs = new List<POutput>(poutputs);

                //update list of plugged output names property
                //this.pluggedOutputNames = new List<string>(outnames);

                //for (int o=0; o < pluggedPOutputs.Count; o++)
                //{

                //    if (this.pluggedPOutputs[o] == null)
                //    {
                //        Rhino.RhinoApp.Write("One of the plugged output parameters is not of type POutput.");
                //        return;
                //    }
                //}


                //Param_Number outcome = Params.Input[1].Sources[0] as Param_Number;

                // Now that we have a bunch of sliders and a measure parameter,
                // we can generate a bunch of solutions.
                // We will also harvest the resulting outcome and print each state to the command line.

                //updateMessage("datagen");
                // ExpireSolution(true);
                status = "datagen";
                updateMessage(status);
                List <List <double> > csvd = new List <List <double> >();

                // Assign Samples to sliders as SliderValues
                // loop through list of Samples
                for (int i = 0; i < Samples.Count; i++)
                {
                    for (int j = 0; j < this.pluggedSliders.Count; j++)
                    {
                        this.pluggedSliders[j].SetSliderValue((decimal)Samples[i][j]); // does not work
                    }


                    doc.NewSolution(false);

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

                    // For each Sample vector, harvest the actual slider values.
                    List <string> sliderValuesTxt = new List <string>();
                    List <double> sliderValues    = new List <double>();
                    foreach (GH_NumberSlider slider in this.pluggedSliders)
                    {
                        sliderValuesTxt.Add(slider.Slider.GripText); // save as text for printing to console
                        csvrow.Add((double)slider.Slider.Value);     // cast slider value from decimal to double
                    }


                    // For each sample vector, harvest response output. This can be made more flexible.

                    string measure = "no values yet";

                    // for each output that is plugged in, store each output value
                    for (int o = 0; o < this.pluggedPOutputs.Count; o++)
                    {
                        // access stored output value
                        var volatileData = this.pluggedPOutputs[o].VolatileData as GH_Structure <GH_Number>;

                        if (volatileData != null)
                        {
                            csvrow.Add((double)volatileData.Branches[0][0].Value);                    // store output value in csv
                            measure = string.Format("{0:0.0000}", volatileData.Branches[0][0].Value); // for printing to console
                        }
                    }

                    // Add csv row to csvdata
                    csvd.Add(csvrow);

                    Rhino.RhinoApp.WriteLine("({0}) = {1:0.00000}", string.Join(", ", sliderValuesTxt), measure);
                }
                // Update CSVtype with generated csvdata
                string projfilename = Path.GetFileNameWithoutExtension(doc.FilePath);
                this.csvfilepath = Path.Combine(directory, projfilename + "_CSVdata.txt");
                this.csvdata     = new CSVtype(this.pluggedSliderNames, this.pluggedOutputNames, csvd, directory, projfilename + "_CSVdata");

                // Write csv data to text file in user-specified directory
                this.csvdata.writeCSV(directory);

                //updateMessage("datagencomplete");
                //ExpireSolution(true);
                status = "datagencomplete";
                updateMessage(status);
            }
        }