Exemplo n.º 1
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);
            }
        }
Exemplo n.º 2
0
        public override GH_ObjectResponse RespondToMouseDown(GH_Canvas sender, GH_CanvasMouseEvent e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                ModelBuilder modelbld = Owner as ModelBuilder;


                System.Drawing.RectangleF rec1 = Button1Bounds;
                if (rec1.Contains(e.CanvasLocation))
                {
                    if (own.Params.Input[0].Sources.Count == 0) // if no inputs are plugged in
                    {
                        DialogResult result = MessageBox.Show("Datagenerator is not connected.", "Warning");
                    }
                    else
                    {
                        CSVtype csvinput = own.Params.Input[0].Sources[0] as CSVtype;

                        if (!File.Exists(own.csvfilepath))
                        {
                            DialogResult result = MessageBox.Show("No data has been generated.", "Warning");
                        }

                        else if (own.datagencomponent.Params.Input[0].SourceCount == 0 || own.datagencomponent.Params.Input[1].SourceCount == 0 || own.datagencomponent.Params.Input[2].SourceCount == 0)

                        {
                            DialogResult result = MessageBox.Show("Datagenerator is missing some inputs.", "Warning");
                        }

                        else
                        {
                            modelbld.RunSolver_BuildBN();
                        }
                    }

                    return(GH_ObjectResponse.Handled);
                }

                System.Drawing.RectangleF rec2 = Button2Bounds;
                if (rec2.Contains(e.CanvasLocation))
                {
                    if (own.Params.Input[0].Sources.Count == 0) // if no inputs are plugged in
                    {
                        DialogResult result = MessageBox.Show("Datagenerator is not connected.", "Warning");
                    }
                    else
                    {
                        if (modelbld.model == null)
                        {
                            DialogResult result = MessageBox.Show("No model has been built. Please build model before updating.", "Warning");
                        }
                        else
                        {
                            modelbld.RunSolver_UpdateBN();
                        }
                    }



                    return(GH_ObjectResponse.Handled);
                }

                System.Drawing.RectangleF rec3 = Button3Bounds;
                if (rec3.Contains(e.CanvasLocation))
                {
                    if (own.Params.Input[0].Sources.Count == 0) // if no inputs are plugged in
                    {
                        DialogResult result = MessageBox.Show("Datagenerator is not connected.", "Warning");
                    }
                    else
                    {
                        if (modelbld.model == null)
                        {
                            DialogResult result = MessageBox.Show("Nothing to reset. No model has been built.", "Warning");
                        }

                        else
                        {
                            modelbld.RunSolver_ResetBN();
                        }
                    }

                    return(GH_ObjectResponse.Handled);
                }
            }
            return(base.RespondToMouseDown(sender, e));
        }