Ejemplo n.º 1
0
        //
        //         A private method to add vertices to the terrain tile topology.
        //
        public virtual object _addVertices(object vertices)
        {
            vertices = this._assureCounterClockWise(vertices);
            var face = new List <object>();

            foreach (var vertex in vertices)
            {
                var lookupKey = ",".join(new List <string> {
                    "{:.14f}".format(vertex[0]),
                    "{:.14f}".format(vertex[1]),
                    "{:.14f}".format(vertex[2])
                });
                var faceIndex = this._lookupVertexIndex(lookupKey);
                if (faceIndex != null)
                {
                    // Sometimes we can have triangles with zero area
                    // (due to unfortunate clipping)
                    // In that case skip them
                    // if faceIndex in face:
                    //    break
                    face.append(faceIndex);
                }
                else
                {
                    this.vertices.append(vertex);
                    this.cartesianVertices.append(LLH2ECEF(vertex[0], vertex[1], vertex[2]));
                    faceIndex = this.vertices.Count - 1;
                    this.verticesLookup[lookupKey] = faceIndex;
                    face.append(faceIndex);
                }
            }
            // if len(face) == 3:
            this.faces.append(face);
        }
Ejemplo n.º 2
0
        public PythonScriptHost(bool debugmode = false)
        {
            ResetEngine(debugmode);
            //ScriptRuntimeSetup setup = new ScriptRuntimeSetup();
            //setup.DebugMode = debugmode;
            //setup.LanguageSetups.Add(Python.CreateLanguageSetup(null));
            //ScriptRuntime runtime = new ScriptRuntime(setup);


            //_python = runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName);
            List path = _python.Runtime.GetSysModule().GetVariable("path");

            string standardlib = @"C:\Program Files\IronPython 2.7\Lib";

            if (!path.Contains(standardlib))
            {
                path.append(standardlib);
            }

            standardlib = standardlib + @"\site-packages";
            if (!path.Contains(standardlib))
            {
                path.append(standardlib);
            }

            standardlib = @"C:\Python27\Lib";

            if (!path.Contains(standardlib))
            {
                path.append(standardlib);
            }


            //_python.Runtime.GetClrModule().GetVariable("AddReference")("Prefab");
        }
Ejemplo n.º 3
0
        public void updateTasks(List creates, List updates)
        {
            List batch = new List();

            foreach (PythonDictionary task in creates)
            {
                task["project"] = new PythonDictionary()
                {
                    { "type", "Project" }, { "id", Properties.Settings.Default.ShotgunProject }
                };
                batch.append(new PythonDictionary()
                {
                    { "request_type", "create" },
                    { "entity_type", "Task" },
                    { "data", task }
                });
            }
            foreach (PythonDictionary task in updates)
            {
                int id = (int)task["id"];
                task.Remove("id");
                batch.append(new PythonDictionary()
                {
                    { "request_type", "update" },
                    { "entity_type", "Task" },
                    { "entity_id", id },
                    { "data", task }
                });
            }
            dynamic connection = connect();
            // record this most-recent activity timestamp on the 'project_plugin' script in Shotgun
            List filter = new List()
            {
                new List()
                {
                    "salted_password", "is", connection.config.api_key
                }
            };
            List fields = new List()
            {
                "type", "id"
            };
            PythonDictionary script    = connection.find_one("ApiUser", filter, fields: fields);
            String           now       = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
            PythonDictionary timestamp = new PythonDictionary()
            {
                { "sg_last_run", now }
            };

            batch.append(new PythonDictionary()
            {
                { "request_type", "update" },
                { "entity_type", script["type"] },
                { "entity_id", script["id"] },
                { "data", timestamp }
            });
            connection.batch(batch);
        }
Ejemplo n.º 4
0
 public override void GetValues(List lst)
 {
     lst.append(First);
     foreach (var item in this)
     {
         item.GetValues(lst);
     }
     lst.append(Last);
 }
Ejemplo n.º 5
0
        public tuple get_juice()
        {
            // return juice level of (face, FrontUp, BackUp, FrontDown, BackDown) in tuple
            var jInfo = new List <object>();

            jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruKao));
            jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruFrontUp));
            jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruBackUp));
            jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruFrontDown));
            jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruBackDown));
            return(tuple(jInfo));
        }
Ejemplo n.º 6
0
    private const int RIGHT_ABOVE = 4; // Diagonal /^

    /// <sumary>
    ///   Finds all legal attack moves for the current player with
    /// king pieces
    /// </sumary>
    /// <param name="lastPos">
    ///   All piece movents until now
    /// </param>
    /// <param name="pos">
    ///   Current position
    /// </param>
    /// <param name="dir">
    ///   Last direction
    /// </param>
    /// <param name="color">
    ///  Current player color
    /// </param>
    /// <param name="enemy">
    ///  Enemy piece's color
    /// </param>
    /// <value>
    ///  A list with all the valid attack moves
    /// </value>
    private List kingAttack(List lastPos, int pos, int dir, int color, int enemy)
    {
        List tempMoves, moves = new List();

        if (dir != RIGHT_BELOW)
        {
            tempMoves = kingDiagAttack(lastPos, pos, color, enemy, 1, 1);

            if (notNull(tempMoves))
            {
                moves.append(tempMoves);
            }
        }

        if (dir != LEFT_ABOVE)
        {
            tempMoves = kingDiagAttack(lastPos, pos, color, enemy, -1, -1);

            if (notNull(tempMoves))
            {
                moves.append(tempMoves);
            }
        }


        if (dir != RIGHT_ABOVE)
        {
            tempMoves = kingDiagAttack(lastPos, pos, color, enemy, 1, -1);

            if (notNull(tempMoves))
            {
                moves.append(tempMoves);
            }
        }

        if (dir != LEFT_BELOW)
        {
            tempMoves = kingDiagAttack(lastPos, pos, color, enemy, -1, 1);

            if (notNull(tempMoves))
            {
                moves.append(tempMoves);
            }
        }


        return(moves);
    }
Ejemplo n.º 7
0
    /// <sumary>
    ///   Finds all legal attack moves for the current player
    ///  with simple pieces
    /// </sumary>
    /// <param name="pos">
    ///  Current piece position
    /// </param>
    /// <param name="color">
    ///  Current player color
    /// </param>
    /// <param name="enemy">
    ///  Enemy piece's color
    /// </param>
    /// <value>
    ///  A list with all the valid attack moves
    /// </value>
    private List simpleAttack(int pos, int color, int enemy)
    {
        int  x = posToCol(pos);
        int  y = posToLine(pos);
        int  i;
        List moves = new List();
        List tempMoves;
        int  enemyPos, nextPos;



        i = (color == WHITE) ? -1 : 1;


        // See the diagonals /^ e \v
        if (x < 6 && y + i > 0 && y + i < 7)
        {
            enemyPos = colLineToPos(x + 1, y + i);
            nextPos  = colLineToPos(x + 2, y + 2 * i);

            if ((pieces [enemyPos] & ~KING) == enemy && pieces [nextPos] == EMPTY)
            {
                tempMoves = simpleAttack(nextPos, color, enemy);
                moves.append(addMove(new Move(pos, nextPos), tempMoves));
            }
        }


        // See the diagonals v/ e ^\
        if (x > 1 && y + i > 0 && y + i < 7)
        {
            enemyPos = colLineToPos(x - 1, y + i);
            nextPos  = colLineToPos(x - 2, y + 2 * i);

            if ((pieces [enemyPos] & ~KING) == enemy && pieces [nextPos] == EMPTY)
            {
                tempMoves = simpleAttack(nextPos, color, enemy);
                moves.append(addMove(new Move(pos, nextPos), tempMoves));
            }
        }

        if (moves.isEmpty())
        {
            moves.push_back(new List());
        }

        return(moves);
    }
Ejemplo n.º 8
0
        public static (float ade, float fde) calculate_ADE_FDE_numpy(NDArray pred, NDArray GT)
        {
            float ade, fde;

            if (len(pred.shape) == 3)
            {    // [K, pred, 2]
                var ade_list = new List <float>();
                var fde_list = new List <float>();
                for (int index = 0; index < len(pred); index++)
                {
                    var p        = pred[index];
                    var all_loss = np.mean(np.sqrt(np.square(p - GT)), axis: 1);
                    ade_list.append(np.mean(all_loss));
                    fde_list.append(all_loss[-1]);
                }

                var min_index = np.argmin(np.array(ade_list));
                ade = ade_list[min_index];
                fde = fde_list[min_index];

                // # # ADE of the mean traj
                // # mean_traj = np.mean(pred, axis=0)
                // # mean_traj_loss = np.linalg.norm(mean_traj - GT, ord=2, axis=1)
                // # ade = np.mean(mean_traj_loss)
                // # fde = mean_traj_loss[-1]
            }
            else
            {
                var all_loss = np.mean(np.sqrt(np.square(pred - GT)), axis: 1);
                ade = np.mean(all_loss);
                fde = all_loss[-1];
            }

            return(ade, fde);
        }
Ejemplo n.º 9
0
        private static ITensorOrOperation[] _GatherReturnElements(string[] requested_return_elements,
                                                                  Graph graph,
                                                                  TF_ImportGraphDefResults results)
        {
            var return_outputs = results.return_tensors;
            var return_opers   = results.return_opers;

            var combined_return_elements = new List <ITensorOrOperation>();
            int outputs_idx = 0;
            int opers_idx   = 0;

            foreach (var name in requested_return_elements)
            {
                if (name.Contains(":"))
                {
                    combined_return_elements.append(graph.get_tensor_by_tf_output(return_outputs[outputs_idx]));
                    outputs_idx += 1;
                }
                else
                {
                    throw new NotImplementedException("_GatherReturnElements");
                    // combined_return_elements.append(graph._get_operation_by_tf_operation(return_opers[opers_idx]));
                }
            }

            return(combined_return_elements.ToArray());
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Computes the overall loss.
        /// </summary>
        /// <param name="y_true"></param>
        /// <param name="y_pred"></param>
        public Tensor Call(Tensor y_true, Tensor y_pred)
        {
            if (!_built)
            {
                Build(y_pred);
            }
            var loss_value        = _losses.Call(y_true, y_pred);
            var loss_metric_value = loss_value;
            var batch_dim         = array_ops.shape(y_true)[0];

            var loss_values        = new List <Tensor>();
            var loss_metric_values = new List <Tensor>();

            /*if (_losses.Reduction == ReductionV2.SUM_OVER_BATCH_SIZE
            || _losses.Reduction == ReductionV2.AUTO)
            ||  loss_value = losses_utils.scale_loss_for_distribution(loss_value);*/
            loss_values.append(loss_value);
            loss_metric_values.append(loss_metric_value);

            if (loss_values.Count > 0)
            {
                var total_loss_metric_value = math_ops.add_n(loss_metric_values.ToArray());
                _loss_metric.update_state(total_loss_metric_value, batch_dim);
                // loss_values = losses_utils.cast_losses_to_common_dtype(loss_values);
                var total_loss = math_ops.add_n(loss_values.ToArray());
                return(total_loss);
            }
            else
            {
                // Ok for a model to have no compiled loss.
                return(array_ops.zeros(new TensorShape()));
            }
        }
Ejemplo n.º 11
0
        void _init_graph_network(Tensors inputs, Tensors outputs)
        {
            _is_graph_network  = true;
            this.inputs        = inputs;
            this.outputs       = outputs;
            built              = true;
            _build_input_shape = inputs.shape;
            _compute_output_and_mask_jointly = true;
            _expects_training_arg            = true;
            _expects_mask_arg = true;
            // A graph network does not autocast inputs, as its layers will cast them instead.
            _autocast = false;

            if (outputs.Any(x => x.KerasHistory == null))
            {
                base_layer_utils.create_keras_history(outputs);
            }

            // Build self._output_layers:
            foreach (var x in outputs)
            {
                var(layer, node_index, tensor_index) = x.KerasHistory;
                _output_layers.append(layer);
                _output_coordinates.append(new KerasHistory(layer, node_index, tensor_index, x));
            }

            // Build self._input_layers:
            foreach (var x in inputs)
            {
                var(layer, node_index, tensor_index) = x.KerasHistory;
                _input_layers.append(layer);
                _input_coordinates.append(new KerasHistory(layer, node_index, tensor_index, x));
            }
        }
Ejemplo n.º 12
0
 public static Tensors get_source_inputs(Tensor tensor, ILayer layer = null, int node_index = -1)
 {
     if (layer == null)
     {
         (layer, node_index, _) = tensor.KerasHistory;
     }
     if (layer.InboundNodes == null || layer.InboundNodes.Count == 0)
     {
         return(tensor);
     }
     else
     {
         var node = layer.InboundNodes[node_index];
         if (node.is_input)
         {
             return(node.input_tensors);
         }
         else
         {
             var source_tensors = new List <Tensor>();
             foreach (var _layer in node.iterate_inbound())
             {
                 (layer, node_index, tensor) = (_layer.Item1, _layer.Item2, _layer.Item4);
                 var previous_sources = get_source_inputs(tensor, layer, node_index);
                 foreach (var x in previous_sources)
                 {
                     // should be check if exist?
                     source_tensors.append(x);
                 }
             }
             return(source_tensors);
         }
     }
 }
Ejemplo n.º 13
0
        private static ITensorOrOperation[] _GatherReturnElements(string[] requested_return_elements, 
            Graph graph, 
            TF_ImportGraphDefResults results)
        {
            var return_outputs = results.return_tensors;
            var return_opers = results.return_opers;

            var combined_return_elements = new List<ITensorOrOperation>();
            int outputs_idx = 0;
#pragma warning disable CS0219 // Variable is assigned but its value is never used
            int opers_idx = 0;
#pragma warning restore CS0219 // Variable is assigned but its value is never used
            foreach(var name in requested_return_elements)
            {
                if (name.Contains(":"))
                {
                    combined_return_elements.append(graph.get_tensor_by_tf_output(return_outputs[outputs_idx]));
                    outputs_idx += 1;
                }
                else
                {
                    throw new NotImplementedException("_GatherReturnElements");
                    // combined_return_elements.append(graph._get_operation_by_tf_operation(return_opers[opers_idx]));
                }
            }

            return combined_return_elements.ToArray();
        }
Ejemplo n.º 14
0
        public static List nlargest(CodeContext /*!*/ context, int n, object iterable)
        {
            if (n <= 0)
            {
                return(new List());
            }

            List        ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge
            IEnumerator en  = PythonOps.GetEnumerator(iterable);

            // populate list with first n items
            for (int i = 0; i < n; i++)
            {
                if (!en.MoveNext())
                {
                    // fewer than n items; finish up here
                    HeapSort(context, ret, true);
                    return(ret);
                }
                ret.append(en.Current);
            }

            // go through the remainder of the iterator, maintaining a min-heap of the n largest values
            DoHeapify(context, ret);
            while (en.MoveNext())
            {
                DoPushPop(context, ret, en.Current);
            }

            // return the largest items, in descending order
            HeapSort(context, ret, true);
            return(ret);
        }
Ejemplo n.º 15
0
        //  def AddWhileContext(self, op, between_op_list, between_ops):
        //    """Add the grad state for the while loop that op belongs to.

        //    Note that op is an Exit, and this method must be called in
        //    the control flow context where gradients() is called.

        //    Note that this method modifies `between_op_list` and `between_ops`.
        //    """
        //    forward_ctxt = _GetWhileContext(op)
        //    grad_state = self._map.get(forward_ctxt)
        //    if grad_state is None:
        //      # This is a new while loop so create a grad state for it.
        //      outer_forward_ctxt = forward_ctxt.outer_context
        //      if outer_forward_ctxt:
        //        outer_forward_ctxt = outer_forward_ctxt.GetWhileContext()
        //      outer_grad_state = None
        //      if outer_forward_ctxt:
        //        outer_grad_state = self._map.get(outer_forward_ctxt)
        //      grad_state = GradLoopState(forward_ctxt, outer_grad_state)
        //      self._map[forward_ctxt] = grad_state

        //      # We need to include all exits of a loop for backprop.
        //      for loop_exit in grad_state.forward_loop_exits:
        //        if loop_exit.op not in between_ops:
        //          between_ops.add(loop_exit.op)
        //          between_op_list.append(loop_exit.op)
        public void AddWhileContext(Operation op, List <Operation> between_op_list, List <Operation> between_ops)
        {
            var forward_ctxt = op.GetWhileContext();
            var grad_state   = _map.ContainsKey(forward_ctxt) ? _map[forward_ctxt] : null;

            if (grad_state == null)
            {
                GradLoopState outer_grad_state   = null;
                var           outer_forward_ctxt = forward_ctxt.outer_context;
                if (outer_forward_ctxt != null)
                {
                    outer_forward_ctxt = outer_forward_ctxt.GetWhileContext();
                }
                if (outer_forward_ctxt != null)
                {
                    outer_grad_state = _map[outer_forward_ctxt];
                }
                grad_state         = new GradLoopState(forward_ctxt, outer_grad_state);
                _map[forward_ctxt] = grad_state;

                // We need to include all exits of a loop for backprop.
                foreach (var loop_exit in grad_state.forward_loop_exits)
                {
                    if (!between_ops.Contains(loop_exit.op))
                    {
                        between_ops.add(loop_exit.op);
                        between_op_list.append(loop_exit.op);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        Py_InitModule4(string name, IntPtr methodsPtr, string doc, IntPtr selfPtr, int apiver)
        {
            name = this.FixImportName(name);

            PythonDictionary methodTable = new PythonDictionary();
            PythonModule     module      = new PythonModule();

            this.AddModule(name, module);
            this.CreateModulesContaining(name);

            PythonDictionary __dict__ = module.Get__dict__();

            __dict__["__doc__"]  = doc;
            __dict__["__name__"] = name;
            string __file__ = this.importFiles.Peek();

            __dict__["__file__"] = __file__;
            List __path__ = new List();

            if (__file__ != null)
            {
                __path__.append(Path.GetDirectoryName(__file__));
            }
            __dict__["__path__"]    = __path__;
            __dict__["_dispatcher"] = new Dispatcher(this, methodTable, selfPtr);

            StringBuilder moduleCode = new StringBuilder();

            moduleCode.Append(CodeSnippets.USEFUL_IMPORTS);
            CallableBuilder.GenerateFunctions(moduleCode, methodsPtr, methodTable);
            this.ExecInModule(moduleCode.ToString(), module);

            return(this.Store(module));
        }
Ejemplo n.º 17
0
 public virtual object dropEvent(object @event)
 {
     if (@event.mimeData().hasUrls)
     {
         @event.setDropAction(QtCore.Qt.CopyAction);
         @event.accept();
         // to get a list of files:
         var drop_list = new List <object>();
         foreach (var url in @event.mimeData().urls())
         {
             drop_list.append(str(url.toLocalFile()));
         }
         // handle the list here
         foreach (var f in drop_list)
         {
             try {
                 if (!f.endswith(".cbr") && !f.endswith(".cbz") && !f.endswith(".zip") && !f.endswith(".rar"))
                 {
                     Image.open(f);
                 }
                 shutil.copy(f, this._tmpinputfolder);
             } catch {
             }
         }
     }
     else
     {
         @event.ignore();
     }
 }
Ejemplo n.º 18
0
    /// <sumary>
    ///   Finds all legal attack moves for the current player.
    /// </sumary>
    /// <param name="color">
    ///  Current player color
    /// </param>
    /// <param name="enemy">
    ///  Enemy piece's color
    /// </param>
    /// <value>
    ///  A list with all the valid attack moves
    /// </value>
    private List generateAttackMoves(int color, int enemy)
    {
        List moves = new List();
        List tempMoves;


        for (int k = 0; k < 32; k++)
        {
            if ((pieces [k] & ~KING) == currentPlayer)
            {
                if ((pieces [k] & KING) == 0) // Simple piece
                {
                    tempMoves = simpleAttack(k, color, enemy);
                }
                else // It's a king piece
                {
                    List lastPos = new List();

                    lastPos.push_back(k);

                    tempMoves = kingAttack(lastPos, k, NONE, color, enemy);
                }

                if (notNull(tempMoves))
                {
                    moves.append(tempMoves);
                }
            }
        }

        return(moves);
    }
Ejemplo n.º 19
0
        Py_InitModule4(string name, IntPtr methodsPtr, string doc, IntPtr selfPtr, int apiver)
        {
            name = this.FixImportName(name);
            
            PythonDictionary methodTable = new PythonDictionary();
            PythonModule module = new PythonModule();
            this.AddModule(name, module);
            this.CreateModulesContaining(name);

            PythonDictionary __dict__ = module.Get__dict__();
            __dict__["__doc__"] = doc;
            __dict__["__name__"] = name;
            string __file__ = this.importFiles.Peek();
            __dict__["__file__"] = __file__;
            List __path__ = new List();
            if (__file__ != null)
            {
                __path__.append(Path.GetDirectoryName(__file__));
            }
            __dict__["__path__"] = __path__;
            __dict__["_dispatcher"] = new Dispatcher(this, methodTable, selfPtr);

            StringBuilder moduleCode = new StringBuilder();
            moduleCode.Append(CodeSnippets.USEFUL_IMPORTS);
            CallableBuilder.GenerateFunctions(moduleCode, methodsPtr, methodTable);
            this.ExecInModule(moduleCode.ToString(), module);
            
            return this.Store(module);
        }
Ejemplo n.º 20
0
    public static object meshgrid2(params object [] arrs)
    {
        arrs = tuple(reversed(arrs));
        var lens = map(len, arrs);
        var dim  = arrs.Count;
        var sz   = 1;

        foreach (var s in lens)
        {
            sz *= s;
        }
        var ans = new List <object>();

        foreach (var _tup_1 in arrs.Select((_p_1, _p_2) => Tuple.Create(_p_2, _p_1)))
        {
            var i = _tup_1.Item1;
            var arr = _tup_1.Item2;
            var slc = new List <int> {
                1
            } *dim;
            slc[i] = lens[i];
            var arr2 = asarray(arr).reshape(slc);
            foreach (var _tup_2 in lens.Select((_p_3, _p_4) => Tuple.Create(_p_4, _p_3)))
            {
                var j = _tup_2.Item1;
                sz = _tup_2.Item2;
                if (j != i)
                {
                    arr2 = arr2.repeat(sz, axis: j);
                }
            }
            ans.append(arr2);
        }
        return(tuple(ans));
    }
Ejemplo n.º 21
0
 public static object checkByColumn()
 {
     foreach (var i in Enumerable.Range(0, 9))
     {
         var numbers   = Enumerable.Range(1, 10 - 1);
         var locations = new List <object>();
         foreach (var j in Enumerable.Range(0, 9))
         {
             if (b[j][i] == 0)
             {
                 locations.append(new List <int> {
                     i,
                     j
                 });
             }
             else
             {
                 numbers.remove(b[j][i]);
             }
         }
         foreach (var n in numbers)
         {
             var l = findLocationColumn(n, locations);
             if (l != 0)
             {
                 writeNumber(n, l);
             }
         }
     }
 }
Ejemplo n.º 22
0
        PyList_Append(IntPtr listPtr, IntPtr itemPtr)
        {
            PyListObject listStruct = (PyListObject)Marshal.PtrToStructure(listPtr, typeof(PyListObject));

            if (listStruct.ob_type != this.PyList_Type)
            {
                this.LastException = PythonOps.TypeError("PyList_Append: not a list");
                return(-1);
            }

            if (listStruct.ob_item == IntPtr.Zero)
            {
                this.IC_PyList_Append_Empty(listPtr, ref listStruct, itemPtr);
            }
            else
            {
                this.IC_PyList_Append_NonEmpty(listPtr, ref listStruct, itemPtr);
            }

            List list = (List)this.Retrieve(listPtr);

            list.append(this.Retrieve(itemPtr));
            this.IncRef(itemPtr);
            return(0);
        }
Ejemplo n.º 23
0
        public static object _iterUnpackWatermaskRow(object f, object extensionLength, object structType)
        {
            var i       = 0;
            var xyCount = 0;
            var row     = new List <object>();

            while (xyCount != extensionLength)
            {
                row.append(unpackEntry(f, structType));
                if (i == 255)
                {
                    yield return(row);

                    i   = 0;
                    row = new List <object>();
                }
                else
                {
                    i += 1;
                }
                xyCount += 1;
            }
            if (row)
            {
                yield return(row);
            }
        }
Ejemplo n.º 24
0
 void _create_ordered_metrics()
 {
     _metrics_in_order = new List <Metric>();
     foreach (var m in _metrics)
     {
         _metrics_in_order.append(m);
     }
 }
Ejemplo n.º 25
0
        public void AddPath(string path)
        {
            List pythonpaths = _python.Runtime.GetSysModule().GetVariable("path");

            if (!pythonpaths.Contains(path))
            {
                pythonpaths.append(path);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Reconstructs graph from config object.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        static (Tensors, Tensors, Dictionary <string, ILayer>) reconstruct_from_config(ModelConfig config)
        {
            // Layer instances created during the graph reconstruction process.
            var created_layers      = new Dictionary <string, ILayer>();
            var node_index_map      = new Dictionary <(string, int), int>();
            var node_count_by_layer = new Dictionary <ILayer, int>();
            var unprocessed_nodes   = new Dictionary <ILayer, NodeConfig>();

            // First, we create all layers and enqueue nodes to be processed
            foreach (var layer_data in config.Layers)
            {
                process_layer(created_layers, layer_data, unprocessed_nodes, node_count_by_layer);
            }

            // Then we process nodes in order of layer depth.
            // Nodes that cannot yet be processed (if the inbound node
            // does not yet exist) are re-enqueued, and the process
            // is repeated until all nodes are processed.
            while (unprocessed_nodes.Count > 0)
            {
                foreach (var layer_data in config.Layers)
                {
                    var layer = created_layers[layer_data.Name];
                    if (unprocessed_nodes.ContainsKey(layer))
                    {
                        var node_data = unprocessed_nodes[layer];
                        // foreach (var node_data in unprocessed_nodes[layer])
                        {
                            process_node(layer, node_data, created_layers, node_count_by_layer, node_index_map);
                            unprocessed_nodes.Remove(layer);
                        }
                    }
                }
            }

            var input_tensors = new List <Tensor>();

            foreach (var layer_data in config.InputLayers)
            {
                var(layer_name, node_index, tensor_index) = (layer_data.Name, layer_data.NodeIndex, layer_data.TensorIndex);
                var layer = created_layers[layer_name];
                var layer_output_tensors = layer.InboundNodes[node_index].Outputs;
                input_tensors.append(layer_output_tensors[tensor_index]);
            }

            var output_tensors = new List <Tensor>();

            foreach (var layer_data in config.OutputLayers)
            {
                var(layer_name, node_index, tensor_index) = (layer_data.Name, layer_data.NodeIndex, layer_data.TensorIndex);
                var layer = created_layers[layer_name];
                var layer_output_tensors = layer.InboundNodes[node_index].Outputs;
                output_tensors.append(layer_output_tensors[tensor_index]);
            }

            return(input_tensors, output_tensors, created_layers);
        }
Ejemplo n.º 27
0
        ///FUNCTION_NAME: getForwardDataset_onlyTraj
        ///<summary>
        ///    Get inputs for models who only takes `obs_traj` as input.
        ///
        ///</summary>
        ///<param name="input_agents"> a list of input agents, type = `List[Agent]` </param>
        public static Tensors getForwardDataset_onlyTraj(List <TrainAgentManager> input_agents)
        {
            var trajs = new List <NDArray>();

            foreach (var agent in input_agents)
            {
                trajs.append(agent.traj);
            }
            return(new Tensor(np.stack(trajs.ToArray()), tf.float32));
        }
Ejemplo n.º 28
0
    // 座標追加
    private void append()
    {
        optiP.append(optiP());
        optiR.append(optiR());

        Vector3[] axi = axiDrawClient.GetVec();

        axiP.append(axi[0]);
        axiR.append(axi[1]);
    }
Ejemplo n.º 29
0
        public List <NDArray> get_neighbor_traj_linear_linear()
        {
            var results = new List <NDArray>();

            foreach (var item in this._neighbor_traj_linear_pred)
            {
                results.append(np.array(item).astype(np.float32));
            }
            return(results);
        }
Ejemplo n.º 30
0
    public static object squaredDistances(object coordsPairs)
    {
        var sDistances = new List <object>();

        foreach (var coordsPair in coordsPairs)
        {
            sDistances.append(c3d.distanceSquared(coordsPair[0], coordsPair[1]));
        }
        return(sDistances);
    }
Ejemplo n.º 31
0
        public static Tensor tf_batch_matmul(Tensor left_low, Tensor right_high)
        {
            var temp = new List <Tensor>();

            for (int index = 0; index < right_high.shape[0]; index++)
            {
                temp.append(tf.matmul(left_low, right_high[index]));
            }
            return(tf.stack(temp.ToArray()));
        }
Ejemplo n.º 32
0
        public static object Get__file__(NamespaceTracker self) {
            if (self.PackageAssemblies.Count == 1) {
                return self.PackageAssemblies[0].FullName;
            }

            List res = new List();
            for (int i = 0; i < self.PackageAssemblies.Count; i++) {
                res.append(self.PackageAssemblies[i].FullName);
            }
            return res;                        
        }
Ejemplo n.º 33
0
        public static List getaddrinfo(
            CodeContext/*!*/ context,
            string host,
            object port,
            [DefaultParameterValue((int)AddressFamily.Unspecified)] int family,
            [DefaultParameterValue(0)] int socktype,
            [DefaultParameterValue((int)ProtocolType.IP)] int proto,
            [DefaultParameterValue((int)SocketFlags.None)] int flags
        ) {
            int numericPort;
            
            if (port == null) {
                numericPort = 0;
            } else if (port is int) {
                numericPort = (int)port;
            } else if (port is Extensible<int>) {
                numericPort = ((Extensible<int>)port).Value;
            } else if (port is string) {
                if (!Int32.TryParse((string)port, out numericPort)) {
                    // TODO: also should consult GetServiceByName                    
                    throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed");
                }
            } else if (port is ExtensibleString) {
                if (!Int32.TryParse(((ExtensibleString)port).Value, out numericPort)) {
                    // TODO: also should consult GetServiceByName                    
                    throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed");
                }
            } else {
                throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed");
            }

            if (socktype != 0) {
                // we just use this to validate; socketType isn't actually used
                System.Net.Sockets.SocketType socketType = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socktype);
                if (socketType == System.Net.Sockets.SocketType.Unknown || !Enum.IsDefined(typeof(System.Net.Sockets.SocketType), socketType)) {
                    throw PythonExceptions.CreateThrowable(gaierror(context), PythonTuple.MakeTuple((int)SocketError.SocketNotSupported, "getaddrinfo failed"));
                }
            }

            AddressFamily addressFamily = (AddressFamily)Enum.ToObject(typeof(AddressFamily), family);
            if (!Enum.IsDefined(typeof(AddressFamily), addressFamily)) {
                throw PythonExceptions.CreateThrowable(gaierror(context), PythonTuple.MakeTuple((int)SocketError.AddressFamilyNotSupported, "getaddrinfo failed"));
            }

            // Again, we just validate, but don't actually use protocolType
            Enum.ToObject(typeof(ProtocolType), proto);

            IPAddress[] ips = HostToAddresses(context, host, addressFamily);

            List results = new List();

            foreach (IPAddress ip in ips) {
                results.append(PythonTuple.MakeTuple(
                    (int)ip.AddressFamily,
                    socktype,
                    proto,
                    "",
                    EndPointToTuple(new IPEndPoint(ip, numericPort))
                ));
            }

            return results;
        }
Ejemplo n.º 34
0
 public List getRGB()
 {
     List list = new List();
     list.append(this.red);
     list.append(this.green);
     list.append(this.blue);
     return list;
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Process a sequence of objects that are compatible with ObjectToSocket(). Return two
        /// things as out params: an in-order List of sockets that correspond to the original
        /// objects in the passed-in sequence, and a mapping of these socket objects to their
        /// original objects.
        /// 
        /// The socketToOriginal mapping is generated because the CPython select module supports
        /// passing to select either file descriptor numbers or an object with a fileno() method.
        /// We try to be faithful to what was originally requested when we return.
        /// </summary>
        private static void ProcessSocketSequence(CodeContext context, object sequence, out List socketList, out Dictionary<Socket, object> socketToOriginal) {
            socketToOriginal = new Dictionary<Socket, object>();
            socketList = new List();

            IEnumerator cursor = PythonOps.GetEnumerator(sequence);
            while (cursor.MoveNext()) {
                object original = cursor.Current;
                Socket socket = ObjectToSocket(context, original);
                socketList.append(socket);
                socketToOriginal[socket] = original;
            }
        }
Ejemplo n.º 36
0
            public List readlines([DefaultParameterValue(-1)]int size) {
                EnsureOpen();

                List lines = new List();
                for (Bytes line = readline(-1); line.Count > 0; line = readline(-1)) {
                    lines.append(line); 
                    if (size > 0) {
                        size -= line.Count;
                        if (size <= 0) {
                            break;
                        }
                    }
                }

                return lines;
            }
Ejemplo n.º 37
0
        public static List nsmallest(CodeContext/*!*/ context, int n, object iterable) {
            if (n <= 0) {
                return new List();
            }

            List ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge
            IEnumerator en = PythonOps.GetEnumerator(iterable);

            // populate list with first n items
            for (int i = 0; i < n; i++) {
                if (!en.MoveNext()) {
                    // fewer than n items; finish up here
                    HeapSort(context, ret);
                    return ret;
                }
                ret.append(en.Current);
            }

            // go through the remainder of the iterator, maintaining a max-heap of the n smallest values
            DoHeapifyMax(context, ret);
            while (en.MoveNext()) {
                DoPushPopMax(context, ret, en.Current);
            }

            // return the smallest items, in ascending order
            HeapSort(context, ret);
            return ret;
        }
Ejemplo n.º 38
0
            public override List readlines([DefaultParameterValue(null)]object hint) {
                _checkClosed();
                int size = GetInt(hint, -1);

                List lines = new List();
                for (Bytes line = readline(-1); line.Count > 0; line = readline(-1)) {
                    lines.append(line); 
                    if (size > 0) {
                        size -= line.Count;
                        if (size <= 0) {
                            break;
                        }
                    }
                }

                return lines;
            }
Ejemplo n.º 39
0
            public IEnumerator GetEnumerator()
            {
                List results = new List();
                try
                {
                    while(true)
                        results.append(this.next(this.context));
                }
                catch(StopIterationException) { }

                return results.GetEnumerator();
            }
Ejemplo n.º 40
0
            public List keys()
            {
                List list = new List();

                for(int i = 0; i < data.Count; ++i)
                {
                    list.append(((PythonTuple)description[i])[0]);
                }

                return list;
            }
Ejemplo n.º 41
0
 public List getRGB(int x, int y)
 {
     /*
       Returns a triple (r,g,b) of the red, green, and blue
       intensities of the pixel at (x,y). Intensity values are
       in range(256).
     */
     byte r, g, b;
     unsafe {
     byte *pixels = (byte *)this.pixbuf.Pixels;
     r = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 0];
     g = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 1];
     b = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 2];
     }
     List list = new List();
     list.append((int)r);
     list.append((int)g);
     list.append((int)b);
     return list;
 }
Ejemplo n.º 42
0
        private void ActualiseList(IntPtr ptr)
        {
            if (this.listsBeingActualised.ContainsKey(ptr))
            {
                throw new Exception("Fatal error: PythonMapper.listsBeingActualised is somehow corrupt");
            }

            List newList = new List();
            this.listsBeingActualised[ptr] = newList;

            int length = CPyMarshal.ReadIntField(ptr, typeof(PyListObject), "ob_size");
            if (length != 0)
            {
                IntPtr itemPtrPtr = CPyMarshal.ReadPtrField(ptr, typeof(PyListObject), "ob_item");
                for (int i = 0; i < length; i++)
                {
                    IntPtr itemPtr = CPyMarshal.ReadPtr(itemPtrPtr);
                    if (itemPtr == IntPtr.Zero)
                    {
                        // We have *no* idea what to do here.
                        throw new ArgumentException("Attempted to Retrieve uninitialised PyListObject -- expect strange bugs");
                    }

                    if (this.listsBeingActualised.ContainsKey(itemPtr))
                    {
                        newList.append(this.listsBeingActualised[itemPtr]);
                    }
                    else
                    {
                        newList.append(this.Retrieve(itemPtr));
                    }

                    itemPtrPtr = CPyMarshal.Offset(itemPtrPtr, CPyMarshal.PtrSize);
                }
            }
            this.listsBeingActualised.Remove(ptr);
            this.incompleteObjects.Remove(ptr);
            this.map.Associate(ptr, newList);
        }