protected override void SafeSolveInstance(IGH_DataAccess da)
        {
            if (m_py == null)
              {
            da.SetData(0, "No Python engine available. This component needs Rhino v5");
            return;
              }

              if(!HiddenOutOutput)
            da.DisableGapLogic(0);

              m_py_output.Reset();

              var rhdoc = RhinoDoc.ActiveDoc;
              var prevEnabled = (rhdoc != null) && rhdoc.Views.RedrawEnabled;

              try
              {
            // set output variables to "None"
            for (int i = HiddenOutOutput ? 0 : 1; i < Params.Output.Count; i++)
            {
              string varname = Params.Output[i].NickName;
              m_py.SetVariable(varname, null);
            }

            // caching variable to keep things as fast as possible
            bool showing_code_input = !HiddenCodeInput;
            // Set all input variables. Even null variables may be used in the
            // script, so do not attempt to skip these for optimization purposes.
            // Skip "Code" input parameter
            // Please pay attention to the input data structure type
            for (int i = showing_code_input ? 1 : 0; i < Params.Input.Count; i++)
            {
              string varname = Params.Input[i].NickName;
              object o = m_marshal.GetInput(da, i);
              m_py.SetVariable(varname, o);
              m_py.SetIntellisenseVariable(varname, o);
            }

            // the "code" string could be embedded in the component itself
            if (showing_code_input || m_compiled_py == null)
            {
              string script;
              if (!showing_code_input)
            script = Code;
              else
              {
            script = null;
            da.GetData(0, ref script);
              }

              if (string.IsNullOrWhiteSpace(script))
              {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No script to execute");
            return;
              }

              if (m_compiled_py == null ||
              string.Compare(script, m_previousRunCode, StringComparison.InvariantCulture) != 0)
              {
            if (!(m_inDocStringsMode = DocStringUtils.FindApplyDocString(script, this)))
              ResetAllDescriptions();
            m_compiled_py = m_py.Compile(script);
            m_previousRunCode = script;
              }
            }

            if (m_compiled_py != null)
            {
              string localPath;
              bool added = AddLocalPath(out localPath);

              m_compiled_py.Execute(m_py);

              if (added) RemoveLocalPath(localPath);

              // Python script completed, attempt to set all of the
              // output paramerers
              for (int i = HiddenOutOutput ? 0 : 1; i < Params.Output.Count; i++)
              {
            string varname = Params.Output[i].NickName;
            object o = m_py.GetVariable(varname);
            m_marshal.SetOutput(o, da, i);
              }
            }
            else
            {
              m_py_output.Write("There was a permanent error parsing this script. Please report to [email protected].");
            }
              }
              catch (Exception ex)
              {
            AddErrorNicely(m_py_output, ex);
            SetFormErrorOrClearIt(da, m_py_output);
            throw;
              }
              finally
              {
            if (rhdoc != null && prevEnabled != rhdoc.Views.RedrawEnabled)
              rhdoc.Views.RedrawEnabled = true;
              }
              SetFormErrorOrClearIt(da, m_py_output);
        }
Example #2
0
        public static Rhino.Collections.ArchivableDictionary Evaluate(string script,
                                                                      Rhino.Collections.ArchivableDictionary input,
                                                                      string[] outputNames)
        {
            var py = Rhino.Runtime.PythonScript.Create();

            foreach (var kv in input)
            {
                py.SetVariable(kv.Key, kv.Value);
            }
            if (!script.Equals(_previousScript))
            {
                // Don't allow certain words in the script to attempt to avoid
                // malicious attacks
                string[] badwords = { "exec", "Assembly", "GetType", "Activator", "GetMethod", "GetPropert" };
                foreach (var word in badwords)
                {
                    if (script.IndexOf(word) >= 0)
                    {
                        throw new Exception($"Script is not allowed to contain the word {word}");
                    }
                }

                // validate that only Rhino namespaces are imported
                const string import      = "import ";
                int          importIndex = script.IndexOf(import);
                while (importIndex >= 0)
                {
                    importIndex += import.Length;
                    while (importIndex < script.Length)
                    {
                        char c = script[importIndex];
                        if (c == ' ')
                        {
                            importIndex++;
                            continue;
                        }
                        break;
                    }
                    if (script.IndexOf("Rhino", importIndex) != importIndex && script.IndexOf("rhinoscript", importIndex) != importIndex)
                    {
                        throw new Exception("Attempt to import module that is not permitted");
                    }

                    int commaAndContinuationIndex = script.IndexOfAny(new char[] { ',', '\\' }, importIndex);
                    if (commaAndContinuationIndex > 0)
                    {
                        int newlineIndex = script.IndexOf('\n', importIndex);
                        if (commaAndContinuationIndex < newlineIndex)
                        {
                            throw new Exception("Do not import multiple packages with a single import statement");
                        }
                    }

                    importIndex = script.IndexOf(import, importIndex);
                }
                _previousCompile = py.Compile(script);
                _previousScript  = script;
            }
            _previousCompile.Execute(py);

            var rc = new Rhino.Collections.ArchivableDictionary();

            foreach (var name in outputNames)
            {
                rc[name] = py.GetVariable(name);
            }
            return(rc);
        }
Example #3
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            bool SelectType = false;
            List<double> v_list = new List<double>();
            Random rnd = new Random();

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            string spyString = "";
            if (!DA.GetData(1, ref spyString)) return;
            if (!DA.GetData(2, ref SelectType)) return;
            if (!DA.GetData(3, ref pyString)) return;
            if (!DA.GetDataList(4, v_list)) return;
            if (!DA.GetData(5, ref nGen)) return;

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            double[] val_list = new double[gph.nodes.Count];
            int v_i = 0;
            for (int i = 0; i < gph.nodes.Count; i++)
            {
                if (v_i == v_list.Count) v_i = 0;
                val_list[i] = v_list[v_i];
                v_i++;
            }

            AWorld wrld = new AWorld(gph, val_list);

            // evaluation function
            _py = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_py = _py.Compile(pyString);

            // selection function
            _spy = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_spy = _py.Compile(spyString);

            // console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            // Main evaluation cycle
            // Should move code into the Antsworld Class
            for (int g = 0; g < nGen; g++)
            {
                // console out
                this.m_py_output.Reset();
                double[] new_vals = new double[wrld.NodeCount];

                // build list to test
                List<int> nodes_to_test = new List<int>();

                for (int i = 0; i < wrld.NodeCount; i++)
                {
                    // build this now since we will only change a few of them later
                    new_vals[i] = wrld.LatestGen[i];

                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);
                    double[] n_wts = wrld.gph.NeighboringWeightsOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    bool test = SelectCell(i, wrld.LatestGen[i], neighboring_vals, n_wts);

                    if (test) nodes_to_test.Add(i);

                }

                if (SelectType)
                {
                    int trial = rnd.Next(nodes_to_test.Count);
                    int new_index = nodes_to_test[trial];
                    nodes_to_test[0] = new_index;
                    nodes_to_test.RemoveRange(1, nodes_to_test.Count - 1);
                }

                // evaluate list of cells
                for (int j = 0; j < nodes_to_test.Count; j++)
                {
                    int i = nodes_to_test[j];
                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals, wrld.gph.NeighboringWeightsOf(i));
                    //double d = g + i + 0.0;

                    new_vals[i] = d;
                }
                wrld.AddGen(new_vals);

                // console out
                Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
                List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
                foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
                consoleOut.AppendRange(gh_strs, key_path);

            }

            DA.SetDataTree(0, consoleOut);
            DA.SetData(1, wrld);
        }
Example #4
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            List<double> v_list = new List<double>();
            //GH_Dict test = GH_Dict.create("a", 1.0);

            //if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            //AWorld wrld = new AWorld(refwrld);

            SpatialGraph gph = new SpatialGraph();
            if (!DA.GetData(0, ref gph)) return;

            int nGen = 0;
            string pyString = "";
            if (!DA.GetData(1, ref pyString)) return;
            if (!DA.GetDataList(2, v_list)) return;
            if (!DA.GetData(3, ref nGen)) return;

            // Sets the initial Generation by using the input v_list
            // if it runs out of values, it starts over (wraps)
            double[] val_list = new double[gph.nodes.Count];
            int v_i = 0;
            for (int i = 0; i < gph.nodes.Count; i++)
            {
                if (v_i == v_list.Count) v_i = 0;
                val_list[i] = v_list[v_i];
                v_i++;
            }

            AWorld wrld = new AWorld(gph, val_list);

            _py = PythonScript.Create();
            _py.Output = this.m_py_output.Write;
            _compiled_py = _py.Compile(pyString);

            // console out
            Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String> consoleOut = new Grasshopper.Kernel.Data.GH_Structure<Grasshopper.Kernel.Types.GH_String>();

            // Main evaluation cycle
            // Should move code into the Antsworld Class
            for (int g = 0; g < nGen; g++)
            {
                // console out
                this.m_py_output.Reset();

                double[] new_vals = new double[wrld.NodeCount];
                for (int i = 0; i < wrld.NodeCount; i++)
                {
                    int[] neighboring_indices = wrld.gph.NeighboringIndexesOf(i);

                    // build list of neighboring values
                    List<double> neighboring_vals = new List<double>();
                    for (int k = 0; k < neighboring_indices.Length; k++) neighboring_vals.Add(wrld.LatestGen[neighboring_indices[k]]);

                    double d = EvaluateCell(i, wrld.LatestGen[i], neighboring_vals);
                    //double d = g + i + 0.0;

                    new_vals[i] = d;
                }
                wrld.AddGen(new_vals);

                // console out
                Grasshopper.Kernel.Data.GH_Path key_path = new Grasshopper.Kernel.Data.GH_Path(g);
                List<Grasshopper.Kernel.Types.GH_String> gh_strs = new List<Grasshopper.Kernel.Types.GH_String>();
                foreach (String str in this.m_py_output.Result) gh_strs.Add(new Grasshopper.Kernel.Types.GH_String(str));
                consoleOut.AppendRange(gh_strs, key_path);

            }

            DA.SetDataTree(0, consoleOut);
            DA.SetData(1, wrld);
        }
        protected override void SafeSolveInstance(IGH_DataAccess DA)
        {
            if (_py == null)
              {
            DA.SetData(0, "No Python engine available. This component needs Rhino v5");
            return;
              }

              DA.DisableGapLogic(0);

              m_py_output.Reset();

              var rhdoc = RhinoDoc.ActiveDoc;
              var prevEnabled = (rhdoc != null) && rhdoc.Views.RedrawEnabled;

              try
              {
            // set output variables to "None"
            for (int i = HideCodeOutput ? 0 : 1; i < Params.Output.Count; i++)
            {
              string varname = Params.Output[i].NickName;
              _py.SetVariable(varname, null);
            }

            // caching variable to keep things as fast as possible
            bool showing_code_input = CodeInputVisible;
            // Set all input variables. Even null variables may be used in the
            // script, so do not attempt to skip these for optimization purposes.
            // Skip "Code" input parameter
            // Please pay attention to the input data structure type
            for (int i = showing_code_input ? 1 : 0; i < Params.Input.Count; i++)
            {
              string varname = Params.Input[i].Name; // ksteinfe: changed from Params.Input[i].Nickname
              object o = _marshal.GetInput(DA, i);
              _py.SetVariable(varname, o);
            //_py.SetIntellisenseVariable(varname, o); // ksteinfe: i think this set the Intellisense thingos for all the input variables.  we are converting, so Intellisense would just be confusing.
            }

            // the "code" string could be embedded in the component itself
            if (showing_code_input || _compiled_py == null)
            {
              string script;
              if (!showing_code_input)
            script = CodeInput;
              else
              {
            script = null;
            DA.GetData(0, ref script);
              }

              if (string.IsNullOrWhiteSpace(script))
              {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No script to execute");
            return;
              }

            // ksteinfe - i think we put our hack here.
              //_py.ExecuteScript(DcPython.Decodes.DecodesAppendedCode.header);
              //script = script + DcPython.Decodes.DecodesAppendedCode.footer;
              script = DcPython.Decodes.DecodesAppendedCode.header + script + DcPython.Decodes.DecodesAppendedCode.footer;

              if (_compiled_py == null ||
              string.Compare(script, _previousRunCode, StringComparison.InvariantCulture) != 0)
              {
            if (!(_inDocStringsMode = DocStringUtils.FindApplyDocString(script, this)))
              ResetAllDescriptions();
            _compiled_py = _py.Compile(script);
            _previousRunCode = script;
              }
            }

            if (_compiled_py != null)
            {
              _compiled_py.Execute(_py);
              // Python script completed, attempt to set all of the
              // output paramerers
              for (int i = HideCodeOutput ? 0 : 1; i < Params.Output.Count; i++)
              {
            string varname = Params.Output[i].NickName;
            object o = _py.GetVariable(varname); // ksteinfe: this is a tree coming in from gh python out.  can we just scan the tree and grab the attributes to store somewhere, then bake each param?
            _marshal.SetOutput(o, DA, i);
              }
            }
            else
            {
              m_py_output.Write("There was a permanent error parsing this script. Please report to [email protected].");
            }
              }
              catch (Exception ex)
              {
            AddErrorNicely(m_py_output, ex);
            SetFormErrorOrClearIt(DA, m_py_output);
            throw;
              }
              finally
              {
            if (rhdoc != null && prevEnabled != rhdoc.Views.RedrawEnabled)
              rhdoc.Views.RedrawEnabled = true;
              }
              SetFormErrorOrClearIt(DA, m_py_output);
        }