private DataTree <object> SolutionTrigger() { DataTree <object> dataTree = null; GH_Document doc = m_document; if (doc == null) { throw new Exception("File could not be opened."); } doc.Enabled = true; doc.NewSolution(true, GH_SolutionMode.Silent); GH_ClusterOutputHook[] outputs = doc.ClusterOutputHooks(); dataTree = new DataTree <object>(); var hint = new GH_NullHint(); dataTree.MergeStructure(outputs[0].VolatileData, hint); doc.Dispose(); return(dataTree); }
public static void ReinstateGenome(ChihuahuaComponent comp, List <decimal> Ngenome) { GH_Document docu = comp.OnPingDocument(); //Change value of sliders IList <IGH_Param> sliders = comp.Params.Input[0].Sources; List <decimal> genome = new List <decimal>(); if (sliders.Count != Ngenome.Count) { throw new System.ArgumentException("Numbers of genes not equal to number of sliders", "Genome"); } for (int i = 0; i < sliders.Count; i++) { Grasshopper.Kernel.Special.GH_NumberSlider slider = sliders[i] as Grasshopper.Kernel.Special.GH_NumberSlider; if (slider != null) { decimal N_gene_value = Ngenome[i]; decimal gene_value = N_gene_value.Remap(0, 1, slider.Slider.Minimum, slider.Slider.Maximum); slider.SetSliderValue(gene_value); genome.Add(gene_value); } } // Get a new solution docu.NewSolution(false); }
public static void RunLoop(object sender, DoWorkEventArgs e) { //Get worker and component Worker = sender as BackgroundWorker; var component = (BackgroundComponent)e.Argument; if (component == null) { MessageBox.Show("Component Error"); return; } GH_Document Doc = component.OnPingDocument(); for (int i = 0; i < 10; i++) { if (Worker.CancellationPending) { e.Cancel = true; return; } Doc.NewSolution(true); //Wait until the grasshopper solution in finished while (Doc.SolutionState != GH_ProcessStep.PostProcess || Doc.SolutionDepth != 0) { } //Set progress Worker.ReportProgress((i + 1) * 10); } }
public static void Run(GH_Document definition, GrasshopperData ghData, _BcAp.Document bcDoc) { bool saveState = GH_Document.EnableSolutions; GH_Document.EnableSolutions = true; definition.Enabled = true; var inputs = GetInputParams(definition); var hostEntityId = ghData.HostEntity; foreach (var input in inputs) { if (!IsInputName(input.NickName)) { continue; } if (input is Parameters.BcEntity) { input.ClearData(); var data = new Types.BcEntity(hostEntityId.ToFsp(), bcDoc.Name); input.AddVolatileData(new Grasshopper.Kernel.Data.GH_Path(0), 0, data); data.LoadGeometry(bcDoc); continue; } var prop = ghData.GetProperty(FormatName(input.NickName)); if (prop == null) { continue; } input.VolatileData.ClearData(); switch (prop) { case int intValue: case double doubleValue: case bool boolValue: case string strValue: input.AddVolatileData(new Grasshopper.Kernel.Data.GH_Path(0), 0, prop); break; case _OdGe.Point3d pntValue: input.AddVolatileData(new Grasshopper.Kernel.Data.GH_Path(0), 0, pntValue.ToRhino()); break; case _OdGe.Vector3d vecValue: input.AddVolatileData(new Grasshopper.Kernel.Data.GH_Path(0), 0, vecValue.ToRhino()); break; } } Rhino.RhinoApp.SetFocusToMainWindow(); definition.NewSolution(false, GH_SolutionMode.Silent); Rhinoceros.Run(); GH_Document.EnableSolutions = saveState; }
// Recalculate: Recalculates Grasshopper solution private void RecalculateSolution() { //ghDoc.ScheduleSolution(1); //waitHandle.WaitOne(); ghDoc.NewSolution(false, GH_SolutionMode.CommandLine); while (ghDoc.SolutionState != GH_ProcessStep.PostProcess || ghDoc.SolutionDepth != 0) { } }
public void Apply() { foreach (var obj in ExpiredObjects) { obj.ExpireSolution(false); } if (Operation == UndoOperation.TransactionCommitted) { Definition.NewSolution(false); } else { // We create a transaction to avoid new changes while undoing or redoing using (var transaction = new Transaction(Document)) { transaction.Start(Operation.ToString()); Definition.NewSolution(false); } } }
public static Individual CreateIndividualFromNGenome(ChihuahuaComponent comp, List <decimal> Ngenome) { GH_Document docu = comp.OnPingDocument(); //Change value of sliders IList <IGH_Param> sliders = comp.Params.Input[0].Sources; List <decimal> genome = new List <decimal>(); if (sliders.Count != Ngenome.Count) { throw new System.ArgumentException("Numbers of genes not equal to number of sliders", "Genome"); } for (int i = 0; i < sliders.Count; i++) { Grasshopper.Kernel.Special.GH_NumberSlider slider = sliders[i] as Grasshopper.Kernel.Special.GH_NumberSlider; if (slider != null) { decimal N_gene_value = Ngenome[i]; decimal gene_value = N_gene_value.Remap(0, 1, slider.Slider.Minimum, slider.Slider.Maximum); slider.SetSliderValue(gene_value); genome.Add(gene_value); } } // Get a new solution docu.NewSolution(false); //Read new fitness value decimal fitness = 0; IGH_Param param = comp.Params.Input[1].Sources[0]; GH_Structure <GH_Number> outcome = comp.Params.Input[1].Sources[0].VolatileData as GH_Structure <GH_Number>; if (outcome == null) { throw new System.ArgumentException("Fitness input is not a number", "Fitness"); } if (outcome != null) { fitness = (decimal)outcome.Branches[0][0].Value; } Individual ind = new Individual(fitness, genome, Ngenome); return(ind); }
//Recalculate Grasshopper Solution public void Recalculate() { //Wait until the grasshopper solution in finished while (_doc.SolutionState != GH_ProcessStep.PreProcess || _doc.SolutionDepth != 0) { } //var strMessage = "Starting new solution" + Environment.NewLine; //MessageBox.Show(strMessage); _doc.NewSolution(true); //strMessage = "Started new solution" + Environment.NewLine; //MessageBox.Show(strMessage); //Wait until the grasshopper solution in finished while (_doc.SolutionState != GH_ProcessStep.PostProcess || _doc.SolutionDepth != 0) { } //strMessage += "Finished solution" + Environment.NewLine; //MessageBox.Show(strMessage); }
public static void AssignDataToDoc(string dataSetJson) { JObject dataSet = JsonConvert.DeserializeObject <JObject>(dataSetJson); GH_Canvas activeCanvas = Instances.ActiveCanvas; if (activeCanvas == null) { throw new Exception("读取文档失败"); } GH_Document doc = activeCanvas.Document; if (doc == null) { return; } var hooks = doc.ClusterInputHooks(); foreach (var hook in hooks) { GH_Structure <IGH_Goo> m_data; string key = hook.NickName; if (string.IsNullOrEmpty(key)) { key = hook.Name; } if (string.IsNullOrEmpty(key)) { key = hook.CustomName; } if (string.IsNullOrEmpty(key)) { key = hook.CustomNickName; } if (!key.StartsWith("@", StringComparison.Ordinal)) { continue; } key = key.Substring(1); if (!dataSet.TryGetValue(key, out var data)) { continue; } m_data = SingleDataStructrue(data); hook.ClearPlaceholderData(); hook.SetPlaceholderData(m_data); //hook.ExpireSolution(true); } // for data placeholder inside cluster (deep = 1) var clusters = new List <GH_Cluster>(); foreach (var obj in doc.Objects) { if (!(obj is GH_Cluster cluster)) { continue; } clusters.Add(cluster); } if (clusters.Count == 0) { return; } foreach (var cluster in clusters) { foreach (var obj in cluster.Document("").Objects) { if (!(obj is IGH_Param param)) { continue; } string nickname = param.NickName; if (string.IsNullOrEmpty(nickname)) { nickname = param.Name; } if (!nickname.StartsWith("@", StringComparison.Ordinal)) { continue; } nickname = nickname.Substring(1); if (!dataSet.TryGetValue(nickname, out var data)) { continue; } Utility.InvokeMethod(param, "Script_ClearPersistentData"); Utility.InvokeMethod(param, "Script_AddPersistentData", new List <object>() { data }); //param.ExpireSolution(true); //cluster.ExpireSolution(true); } } doc.NewSolution(true); activeCanvas.Document.IsModified = false; activeCanvas.Refresh(); GH_Structure <IGH_Goo> SingleDataStructrue(object value) { GH_Structure <IGH_Goo> m_data = new GH_Structure <IGH_Goo>(); GH_Number castNumber = null; GH_String castString = null; GH_Curve castCurve = null; if (GH_Convert.ToGHCurve(value, GH_Conversion.Both, ref castCurve)) { m_data.Append(new GH_ObjectWrapper(castCurve)); } else if (GH_Convert.ToGHNumber(value, GH_Conversion.Both, ref castNumber)) { m_data.Append(new GH_ObjectWrapper(castNumber)); } else if (GH_Convert.ToGHString(value, GH_Conversion.Both, ref castString)) { m_data.Append(new GH_ObjectWrapper(castString)); } else { m_data.Append((IGH_Goo)value); } return(m_data); } }
public static Individual CreateRandomIndividual(ChihuahuaComponent comp) { GH_Document docu = comp.OnPingDocument(); //Change value of sliders List <decimal> genome = new List <decimal>(); List <decimal> Ngenome = new List <decimal>(); IList <IGH_Param> sliders = comp.Params.Input[0].Sources; foreach (IGH_Param param in sliders) { Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider; if (slider != null) { decimal N_gene_value = (decimal)random.NextDouble(); decimal gene_value = N_gene_value.Remap(0, 1, slider.Slider.Minimum, slider.Slider.Maximum); slider.SetSliderValue(gene_value); Ngenome.Add(N_gene_value); genome.Add(gene_value); } else { Rhino.RhinoApp.WriteLine("At least one of the input parameters is not a number slider" + Environment.NewLine); throw new System.ArgumentException("At least one of the input parameters is not a number slider", "Genome"); } } // Get a new solution docu.NewSolution(false); //Read new fitness value decimal fitness = 0; if (comp.Params.Input[1].SourceCount != 1) { Rhino.RhinoApp.Write("Fitness input must be a unique value" + Environment.NewLine); throw new System.ArgumentException("Fitness input must be a unique value", "Fitness"); } else { IGH_Param param = comp.Params.Input[1].Sources[0]; GH_Structure <GH_Number> outcome = comp.Params.Input[1].Sources[0].VolatileData as GH_Structure <GH_Number>; if (outcome == null) { Rhino.RhinoApp.WriteLine("Fitness input is not a number" + Environment.NewLine); throw new System.ArgumentException("Fitness input is not a number", "Fitness"); } if (outcome != null) { fitness = (decimal)outcome.Branches[0][0].Value; } } Individual ind = new Individual(fitness, genome, Ngenome); return(ind); }
private void UpdateData(bool recomputeOnTheEnd, bool restore = false) { if (dataList.Count == 0 || dataList == null) { return; } GH_DocumentServer doc_server = Instances.DocumentServer; if (doc_server == null) { ErrorEvent(this, "No Document Server exist!"); return; } GH_Document doc = doc_server.ToList().Find(x => x.Properties.ProjectFileName == ID.ToString()); if (doc == null) { return; } var hooks = doc.ClusterInputHooks(); if (!restore) { var rndData = dataList.FindAll(data => data.type == "4" || data.type == "5"); history.Add(new TaskRecord { name = name, TaskID = ID, HistoryID = Guid.NewGuid(), date = DateTime.Now, table = dataTable, taskDatas = JsonConvert.SerializeObject(rndData) }); } foreach (var hook in hooks) { TaskData data = dataList.Find(x => x.name == hook.CustomNickName || x.dataID == hook.CustomNickName); if (data == null) { continue; } GH_Structure <IGH_Goo> m_data; if (data.type == "5") { m_data = IO.DeserializeGrasshopperData(Convert.FromBase64String((string)data.value)); } else { m_data = SingleDataStructrue(data.value); } hook.ClearPlaceholderData(); // if (Equals(hook.VolatileData, m_data)) continue; if (!m_data.IsEmpty) { hook.SetPlaceholderData(m_data); } if (!recomputeOnTheEnd) { hook.ExpireSolution(true); } } // for data placeholder inside cluster (deep = 1) var clusters = new List <GH_Cluster>(); foreach (var obj in doc.Objects) { if (!(obj is GH_Cluster cluster)) { continue; } clusters.Add(cluster); } if (clusters.Count == 0) { return; } foreach (var cluster in clusters) { foreach (var obj in cluster.Document("").Objects) { if (!(obj is IGH_Param param)) { continue; } string nickname = param.NickName; if (!nickname.StartsWith("@", StringComparison.Ordinal)) { continue; } TaskData data = dataList.Find(x => x.name == nickname || x.dataID == nickname); if (data == null) { continue; } Utility.InvokeMethod(param, "Script_ClearPersistentData"); Utility.InvokeMethod(param, "Script_AddPersistentData", new List <object>() { data.value }); if (!recomputeOnTheEnd) { param.ExpireSolution(true); } if (!recomputeOnTheEnd) { cluster.ExpireSolution(true); } } } if (recomputeOnTheEnd) { doc.NewSolution(true); } GH_Canvas activeCanvas = Instances.ActiveCanvas; if (activeCanvas == null) { ErrorEvent(this, "No Active Canvas exist!"); return; } activeCanvas.Document.IsModified = false; activeCanvas.Refresh(); dataList.Clear(); }
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); } }
// response to Button event private void OnMouseDownEvent(object sender) { if (this._doc == null) { this._doc = GH.Instances.ActiveCanvas.Document; } if (this.RuntimeMessageLevel == GH_RuntimeMessageLevel.Error) { return; } //Clean first this._flyParam = null; //recollect all params this._filteredSources = gatherSources(); this._filteredSources.RemoveAll(item => item == null); this._filteredSources.RemoveAll(item => item.GHType == InputType.Unsupported); //string Para //checked if Aggregator is recording and the last if (!isAggregatorReady()) { return; } //check if any vaild input source connected to Iteratior if (this._filteredSources.Count() > 0) { this._flyParam = new IteratorFlyParam(_filteredSources, this._selections, this._studyFolder, this._mode); } else { MessageBox.Show("No Slider, ValueList, or Panel connected!"); return; } long testIterationNumber = this._selectedCount; //int totalIterationNumber = _totalCount; if (this._isTestFly) { testIterationNumber = 3; } string msgString = _flyParam.InputParams.Count() + " input(s) connected." + "\n" + testIterationNumber + " (out of " + _totalCount + ") iterations will be done. \n\nContinue?" + "\n\n-------------------------------------------------------- " + "\nTo pause during progressing?\n 1.Press ESC."; if (!String.IsNullOrWhiteSpace(this._studyFolder)) { msgString += "\n 2.Or remove \"running\" file located in foler:\n\t" + this._studyFolder; } var userClick = MessageBox.Show(msgString, "Start?", MessageBoxButtons.YesNo); if (userClick == DialogResult.Yes) { _run = true; _doc.SolutionEnd += OnSolutionEnd; // only recompute those are expired flagged _doc.NewSolution(false); } else { _run = false; _isTestFly = false; _flyParam = null; } }
public void NewGHSolution() { GH_Document doc = new GH_Document(); doc.NewSolution(true); }
public void Export() { if (INSTANCECOUNT > 4242) { string message = "Warning: There are " + INSTANCECOUNT + " iterations.\nIt might take a lot of time and / or Rhino might crash.\nAre you sure you want to proceed?"; DialogResult largeinstancewarning = MessageBox.Show(message, "Warning", MessageBoxButtons.YesNo); if (largeinstancewarning == DialogResult.No) { EMERGENCY_BREAK = true; return; } } FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "Please select an empty folder where the export file should be saved."; DialogResult result = fbd.ShowDialog(); if (result == DialogResult.OK) { string[] files = Directory.GetFiles(fbd.SelectedPath); if (files.Length > 0) { System.Windows.Forms.MessageBox.Show("This is not an empty folder!"); } else { this.PATHISSET = true; this.FOLDERLOCATION = fbd.SelectedPath; GHDEFNAME = new DirectoryInfo(fbd.SelectedPath).Name; EMERGENCY_BREAK = false; } } if (result == DialogResult.Cancel) { EMERGENCY_BREAK = true; return; } // Sanity checks IGH_Component component = Component; GH_Document doc = GrasshopperDocument; if (!PATHISSET) { return; } if (component == null) { return; } if (doc == null) { return; } /// flushing up them arrays geometries = new List <List <System.Object> >(); geometrySets = new List <string>(); sliderNames = new List <string>(); currentCount = 0; // Collect all sliders that are plugged into the first input parameter of the script component. List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>(); foreach (IGH_Param param in component.Params.Input[0].Sources) { Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider; if (slider != null) { sliders.Add(slider); sliderNames.Add(slider.NickName); } } if (sliders.Count == 0) { return; } // generate the Matrix File myMatrix = constructMatrixFromSliders((GH_Component)component); // update the instance count INSTANCECOUNT = myMatrix.Count; // go generate stuff foreach (List <double> instance in myMatrix) { // pause the solver while set up the sliders doc.Enabled = false; // update the currentInstanceName - top level var currentInstanceName = ""; foreach (double tempvar in instance) { currentInstanceName += tempvar + ","; } // set sliders up for (int i = 0; i < sliders.Count; i++) { Grasshopper.Kernel.Special.GH_NumberSlider mySlider = sliders[i]; mySlider.Slider.Value = (decimal)instance[i]; } //renable solver doc.Enabled = true; //compute new solution doc.NewSolution(false); } }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { Component = this; doc = Component.OnPingDocument(); var x = new List <double>(); double fx = new double(); double h = new double(); int step = 0; double alpha = new double(); var eps = 1e-4; if (!DA.GetData("f(x)", ref fx)) { return; } if (!DA.GetDataList("x", x)) { return; } if (!DA.GetData("h", ref h)) { return; } if (!DA.GetData("alpha", ref alpha)) { return; } if (!DA.GetData("step", ref step)) { return; } if (!DA.GetData("eps", ref eps)) { return; } if (start == 0) { return; } if (counter == -1) { y = x; } List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>(); for (int i = 0; i < x.Count; i++) { Grasshopper.Kernel.Special.GH_NumberSlider slider = Params.Input[1].Sources[i] as Grasshopper.Kernel.Special.GH_NumberSlider; sliders.Add(slider); if (counter == -1) { minrange.Add((double)slider.Slider.Minimum); maxrange.Add((double)slider.Slider.Maximum); } } doc.NewSolution(false); if (agm == 1) { for (int i = 0; i < y.Count; i++) { y[i] = Math.Min(Math.Max(y[i], minrange[i]), maxrange[i]); } //force y inside slider range var df = Sensitivity(sliders, y, h); dk = df; for (int i = 0; i < dk.Length; i++) { dk[i] = -dk[i]; } //dk=-df if (golden == 1) { alpha = line_search_golden_section(sliders, y, dk); } var x_prev = x; for (int i = 0; i < x.Count; i++) { x[i] = y[i] + alpha * dk[i]; } //x=y+alpha*dk var dk_norm = Math.Sqrt(vec_multiply(dk, dk)); var t_prev = t; var reset_value = 0.0; for (int i = 0; i < dk.Length; i++) { reset_value += -dk[i] * (x[i] - x_prev[i]); } //np.dot(-dk,x-x_prev) if (reset_value <= 0.0) { t = 0.5 * (1.0 + Math.Sqrt(1.0 + 4.0 * Math.Pow(t_prev, 2)));//t=0.50*(1.0+np.sqrt(1.0+4.0*t**2)) for (int i = 0; i < x.Count; i++) { y[i] = x[i] + (t_prev - 1.0) / t * (x[i] - x_prev[i]); } //y=x+(t_prev-1.0)/t*(x-x_prev) } else { t = 1.0; y = x; } DA.SetDataList("df(x)", df); DA.SetData("|df(x)|", dk_norm); DA.SetData("alpha", alpha); counter += 1; if (start == 1 && counter < step && dk_norm > eps) { doc.ScheduleSolution(1, ScheduleCallback); } } else if (cg == 1) { if (counter == -1) { dk = Sensitivity(sliders, x, h); for (int i = 0; i < dk.Length; i++) { dk[i] = -dk[i]; } ; pk = dk; } //dk=-df for (int i = 0; i < pk.Length; i++) { pk[i] = dk[i] + beta * pk[i]; } //pk=dk+beta*pk if (golden == 1) { alpha = line_search_golden_section(sliders, x, pk); } for (int i = 0; i < x.Count; i++) { x[i] = x[i] + alpha * pk[i]; } //x=x+alpha*pk var dk_prev = dk; dk = Sensitivity(sliders, x, h); for (int i = 0; i < dk.Length; i++) { dk[i] = -dk[i]; } //dk=-df beta = vec_multiply(dk, dk) / vec_multiply(dk_prev, dk_prev); var dk_norm = Math.Sqrt(vec_multiply(dk, dk)); DA.SetDataList("df(x)", dk); DA.SetData("|df(x)|", dk_norm); DA.SetData("alpha", alpha); counter += 1; if (start == 1 && counter < step && dk_norm > eps) { doc.ScheduleSolution(1, ScheduleCallback); } } }