示例#1
0
    internal PythonEnvironment(Grasshopper.Kernel.GH_Component component, PythonScript script)
    {
      Component = component;
      Script = script;

      if (script != null)
      {
        Type scriptType = script.GetType();

        var scopeField = scriptType.GetField("m_scope");
        if (scopeField != null)
        {
          LocalScope = scopeField.GetValue(script);
        }

        var baseType = scriptType.BaseType;
        if (baseType != null && baseType != typeof (object))
        {
          var hostType = baseType.Assembly.GetType("RhinoPython.Host");
          if (hostType != null)
          {
            var engineInfo = hostType.GetProperty("Engine");
            if (engineInfo != null)
              Engine = engineInfo.GetValue(null, null);

            var scopeInfo = hostType.GetProperty("Scope", System.Reflection.BindingFlags.NonPublic |
                                                          System.Reflection.BindingFlags.GetProperty |
                                                          System.Reflection.BindingFlags.Static);
            if (scopeInfo != null)
              ScriptScope = scopeInfo.GetValue(null, null);
          }
        }
      }

    }
示例#2
0
 /// <summary>
 /// Constructs a new Python script context.
 /// </summary>
 /// <returns>A new Python script, or null if none could be created. Rhino 4 always returns null.</returns>
 public static PythonScript Create()
 {
   Guid ip_id = new Guid("814d908a-e25c-493d-97e9-ee3861957f49");
   object obj = Rhino.RhinoApp.GetPlugInObject(ip_id);
   if (null == obj)
     return null;
   PythonScript pyscript = obj as PythonScript;
   return pyscript;
 }
示例#3
0
        internal PythonEnvironment(GH_Component component, PythonScript script)
        {
            Component = component;
              Script = script;

              if (script != null)
              {
            Type scriptType = script.GetType();

            var scopeField = scriptType.GetField("m_scope");
            if (scopeField != null)
            {
              LocalScope = scopeField.GetValue(script);
            }

            var intellisenseField = scriptType.GetField("m_intellisense",
              BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
            if (intellisenseField != null)
            {
              Intellisense = intellisenseField.GetValue(script);
              if (Intellisense != null)
              {
            var intellisenseType = Intellisense.GetType();
            var scopeProperty = intellisenseType.GetProperty("Scope");
            IntellisenseScope = scopeProperty.GetValue(Intellisense, null);
              }
            }

            var baseType = scriptType.BaseType;
            if (baseType != null && baseType != typeof(object))
            {
              var hostType = baseType.Assembly.GetType("RhinoPython.Host");
              if (hostType != null)
              {
            var engineInfo = hostType.GetProperty("Engine");
            if (engineInfo != null)
            {
              Engine = engineInfo.GetValue(null, null);

              if (Engine != null)
              {
                var runtimeInfo = Engine.GetType().GetProperty("Runtime");
                Runtime = runtimeInfo.GetValue(Engine, null);
              }
            }

            var scopeInfo = hostType.GetProperty("Scope", BindingFlags.NonPublic |
                                                          BindingFlags.GetProperty |
                                                          BindingFlags.Static);
            if (scopeInfo != null)
              ScriptScope = scopeInfo.GetValue(null, null);
              }
            }
              }
        }
    public static Rhino.Commands.Result CustomPython(RhinoDoc doc)
    {
        if (null == m_python)
        {
          m_python = Rhino.Runtime.PythonScript.Create();
          if (null == m_python)
          {
        RhinoApp.WriteLine("Error: Unable to create an instance of the python engine");
        return Rhino.Commands.Result.Failure;
          }
        }
        m_python.ScriptContextDoc = new CustomPythonDoc(doc);

        const string script = @"
        import rhinoscriptsyntax as rs
        rs.AddLine((0,0,0), (10,10,10))
        ";
        m_python.ExecuteScript(script);
        return Rhino.Commands.Result.Success;
    }
示例#5
0
 /// <summary>
 /// Executes the script in a specific scope.
 /// </summary>
 /// <param name="scope">The scope where the script should be executed.</param>
 public abstract void Execute(PythonScript scope);
示例#6
0
    static int EvaluateExpressionHelper(IntPtr statementsAsStringHolder, IntPtr expressionAsStringHolder, int rhinoDocId, IntPtr pResultString)
    {
      int rc = 0;
#if RHINO_SDK
      try
      {
        string state = StringHolder.GetString(statementsAsStringHolder);
        string expr = StringHolder.GetString(expressionAsStringHolder);
        PythonScript py = PythonScript.Create();
        object eval_result = py.EvaluateExpression(state, expr);
        if (null != eval_result)
        {
          string s = null;
          RhinoDoc doc = RhinoDoc.FromId(rhinoDocId);
          if (eval_result is double || eval_result is float)
          {
            if (doc != null)
            {
              int display_precision = doc.DistanceDisplayPrecision;
              string format = "{0:0.";
              format = format.PadRight(display_precision + format.Length, '0') + "}";
              s = string.Format(format, eval_result);
            }
            else
              s = eval_result.ToString();
          }
          else if (eval_result is string)
          {
            s = eval_result.ToString();
          }
          System.Collections.IEnumerable enumerable = eval_result as System.Collections.IEnumerable;
          if (string.IsNullOrEmpty(s) && enumerable != null)
          {
            string format = null;
            if (doc != null)
            {
              int display_precision = doc.DistanceDisplayPrecision;
              format = "{0:0.";
              format = format.PadRight(display_precision + format.Length, '0') + "}";
            }
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (object obj in enumerable)
            {
              if (sb.Length > 0)
                sb.Append(", ");
              if ( (obj is double || obj is float) && !string.IsNullOrEmpty(format) )
              {
                sb.AppendFormat(format, obj);
              }
              else
              {
                sb.Append(obj);
              }
            }
            s = sb.ToString();
          }
          if (string.IsNullOrEmpty(s))
            s = eval_result.ToString();
          UnsafeNativeMethods.ON_wString_Set(pResultString, s);
        }
        rc = 1;
      }
      catch (Exception ex)
      {
        UnsafeNativeMethods.ON_wString_Set(pResultString, ex.Message);
        rc = 0;
      }
#endif
      return rc;
    }
示例#7
0
 /// <summary>
 /// Executes the script in a specific scope.
 /// </summary>
 /// <param name="scope">The scope where the script should be executed.</param>
 public abstract void Execute(PythonScript scope);
        protected override void Initialize()
        {
            base.Initialize();

              if (Doc != null)
            Doc.SolutionEnd += OnDocSolutionEnd;

              m_py = PythonScript.Create();
              if (m_py != null)
              {
            //UnpackScriptResources();
            SetScriptTransientGlobals();
            m_py.Output = m_py_output.Write;
            m_py.SetVariable("__name__", "__main__");
            m_env = new PythonEnvironment(this, m_py);

            m_py.SetVariable(PARENT_ENVIRONMENT_NAME, m_env);
            m_py.SetIntellisenseVariable(PARENT_ENVIRONMENT_NAME, m_env);

            m_py.ContextId = 2; // 2 is Grasshopper

            m_env.LoadAssembly(typeof(GH_Component).Assembly); //add Grasshopper.dll reference
              }
        }
        protected override void Initialize()
        {
            base.Initialize();

              if (Doc != null)
            Doc.SolutionEnd += OnDocSolutionEnd;

              _py = PythonScript.Create();
              if (_py != null)
              {
            SetScriptTransientGlobals();
            _py.Output = m_py_output.Write;
            _py.SetVariable("__name__", "__main__");
            _env = new PythonEnvironment(this, _py);
            _py.SetVariable(PARENT_ENVIRONMENT_NAME, _env);
            _py.SetIntellisenseVariable(PARENT_ENVIRONMENT_NAME, _env);

            _py.ContextId = 2; // 2 is Grasshopper
              }
        }
示例#10
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);
        }
示例#11
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);
        }