示例#1
0
        public float norm(NDarray x, Constants ord)
        {
            if (ord != Constants.inf && ord != Constants.neg_inf)
            {
                throw  new ArgumentException("ord must be either inf or neg_inf");
            }

            var pyargs = ToTuple(new object[] { x, });
            var kwargs = new PyDict();

            if (ord != null)
            {
                kwargs["ord"] = ord == Constants.inf ? self.inf : -(self.inf);
            }
            var     linalg = self.GetAttr("linalg");
            dynamic py     = linalg.InvokeMethod("norm", pyargs, kwargs);

            return(ToCsharp <float>(py));
        }
示例#2
0
        /// <summary>
        /// Create a data type object.
        ///
        /// A numpy array is homogeneous, and contains elements described by a
        /// dtype object. A dtype object can be constructed from different
        /// combinations of fundamental numeric types.
        /// </summary>
        /// <param name="align">
        /// Add padding to the fields to match what a C compiler would output
        /// for a similar C-struct. Can be True only if obj is a dictionary
        /// or a comma-separated string. If a struct dtype is being created,
        /// this also sets a sticky alignment flag isalignedstruct.
        /// </param>
        /// <param name="copy">
        /// Make a new copy of the data-type object. If False, the result
        /// may just be a reference to a built-in data-type object.
        /// </param>
        public void dtype(bool?align = null, bool?copy = null)
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
            });
            var kwargs = new PyDict();

            if (align != null)
            {
                kwargs["align"] = ToPython(align);
            }
            if (copy != null)
            {
                kwargs["copy"] = ToPython(copy);
            }
            dynamic py = __self__.InvokeMethod("dtype", pyargs, kwargs);
        }
示例#3
0
        /// <summary>
        ///	Compute tensor dot product along specified axes for arrays &gt;= 1-D.<br></br>
        ///
        ///	Given two tensors (arrays of dimension greater than or equal to one),
        ///	a and b, and an array_like object containing two array_like
        ///	objects, (a_axes, b_axes), sum the products of a’s and b’s
        ///	elements (components) over the axes specified by a_axes and
        ///	b_axes.<br></br>
        ///	 The third argument can be a single non-negative
        ///	integer_like scalar, N; if it is such, then the last N
        ///	dimensions of a and the first N dimensions of b are summed
        ///	over.<br></br>
        ///
        ///	Notes
        ///
        ///	When axes is integer_like, the sequence for evaluation will be: first
        ///	the -Nth axis in a and 0th axis in b, and the -1th axis in a and
        ///	Nth axis in b last.<br></br>
        ///
        ///	When there is more than one axis to sum over - and they are not the last
        ///	(first) axes of a (b) - the argument axes should consist of
        ///	two sequences of the same length, with the first axis to sum over given
        ///	first in both sequences, the second axis second, and so forth.
        /// </summary>
        /// <param name="b">
        ///	Tensors to “dot”.
        /// </param>
        /// <param name="a">
        ///	Tensors to “dot”.
        /// </param>
        public static NDarray tensordot(NDarray b, NDarray a, int[] axes = null)
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
                b,
                a,
            });
            var kwargs = new PyDict();

            if (axes != null)
            {
                kwargs["axes"] = ToPython(axes);
            }
            dynamic py = __self__.InvokeMethod("tensordot", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#4
0
        public void Download_With_Python_Parameter_Successfully()
        {
            var algo = new QCAlgorithm();

            var byteKey = Encoding.ASCII.GetBytes($"UserName:Password");
            var value   = $"Basic ({Convert.ToBase64String(byteKey)})";

            var headers = new PyDict();

            using (Py.GIL())
            {
                headers.SetItem("Authorization".ToPython(), value.ToPython());
            }

            var content = string.Empty;

            Assert.DoesNotThrow(() => content = algo.Download("https://www.quantconnect.com/", headers));
            Assert.IsNotEmpty(content);
        }
                public AdaptiveMaxPool1d(int output_size, bool return_indices = false)
                {
                    //auto-generated code, do not change
                    var nn       = self.GetAttr("nn");
                    var __self__ = nn;
                    var pyargs   = ToTuple(new object[]
                    {
                        output_size,
                    });
                    var kwargs = new PyDict();

                    if (return_indices != false)
                    {
                        kwargs["return_indices"] = ToPython(return_indices);
                    }
                    dynamic py = __self__.InvokeMethod("AdaptiveMaxPool1d", pyargs, kwargs);

                    self = py as PyObject;
                }
示例#6
0
        public void FullTrain(TrainArgument args)
        {
            using (Py.GIL())
            {
                dynamic train = Py.Import("ludwig.train");

                var pyargs = Util.ToTuple(new object[]
                {
                    args.ModelDefinition
                });
                var kwargs = new PyDict();
                if (args.DataCsv != null)
                {
                    kwargs["data_csv"] = Util.ToPython(args.DataCsv);
                }
                //if (order != null) kwargs["order"] = ToPython(order);
                dynamic py = train.InvokeMethod("full_train", pyargs, kwargs);
            }
        }
        /// <summary>
        ///	Find the set exclusive-or of two arrays.<br></br>
        ///
        ///	Return the sorted, unique values that are in only one (not both) of the
        ///	input arrays.
        /// </summary>
        /// <param name="ar2">
        ///	Input arrays.
        /// </param>
        /// <param name="ar1">
        ///	Input arrays.
        /// </param>
        /// <param name="assume_unique">
        ///	If True, the input arrays are both assumed to be unique, which
        ///	can speed up the calculation.<br></br>
        ///	Default is False.
        /// </param>
        /// <returns>
        ///	Sorted 1D array of unique values that are in only one of the input
        ///	arrays.
        /// </returns>
        public NDarray setxor1d(NDarray ar2, NDarray ar1, bool assume_unique = false)
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
                ar2,
                ar1,
            });
            var kwargs = new PyDict();

            if (assume_unique != false)
            {
                kwargs["assume_unique"] = ToPython(assume_unique);
            }
            dynamic py = __self__.InvokeMethod("setxor1d", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#8
0
        /// <summary>
        ///	Compute the outer product of two vectors.<br></br>
        ///
        ///	Given two vectors, a = [a0, a1, ..., aM] and
        ///	b = [b0, b1, ..., bN],
        ///	the outer product [1] is:
        ///
        ///	References
        /// </summary>
        /// <param name="a">
        ///	First input vector.<br></br>
        ///	Input is flattened if
        ///	not already 1-dimensional.
        /// </param>
        /// <param name="b">
        ///	Second input vector.<br></br>
        ///	Input is flattened if
        ///	not already 1-dimensional.
        /// </param>
        /// <param name="out">
        ///	A location where the result is stored
        /// </param>
        /// <returns>
        ///	out[i, j] = a[i] * b[j]
        /// </returns>
        public NDarray outer(NDarray a, NDarray b, NDarray @out = null)
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
                a,
                b,
            });
            var kwargs = new PyDict();

            if (@out != null)
            {
                kwargs["out"] = ToPython(@out);
            }
            dynamic py = __self__.InvokeMethod("outer", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#9
0
        /// <summary>
        /// The inverse of fftshift. Although identical for even-length x, the
        /// functions differ by one sample for odd-length x.
        /// </summary>
        /// <param name="x">
        /// Input array.
        /// </param>
        /// <param name="axes">
        /// Axes over which to calculate.  Defaults to None, which shifts all axes.
        /// </param>
        /// <returns>
        /// The shifted array.
        /// </returns>
        public NDarray fft_ifftshift(NDarray x, int[] axes = null)
        {
            //auto-generated code, do not change
            var fft      = self.GetAttr("fft");
            var __self__ = fft;
            var pyargs   = ToTuple(new object[]
            {
                x,
            });
            var kwargs = new PyDict();

            if (axes != null)
            {
                kwargs["axes"] = ToPython(axes);
            }
            dynamic py = __self__.InvokeMethod("ifftshift", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#10
0
        /// <summary>
        /// Get an equity curve for an alpha.
        /// </summary>
        /// <param name="alphaId">Alpha Id for strategy we're downloading.</param>
        /// <param name="dateFormat">Preferred date format</param>
        /// <param name="format">Preferred format of returned equity curve</param>
        /// <returns>Equity curve list of points</returns>
        public PyObject GetAlphaEquityCurve(string alphaId, string dateFormat = "date", string format = "json")
        {
            var equityCurve = GetAlphaEquityCurveCSharp(alphaId, dateFormat, format);

            using (Py.GIL())
            {
                dynamic pandas = Py.Import("pandas");

                var index  = equityCurve.Select(x => x.Time).ToList();
                var equity = equityCurve.Select(x => x.Equity);
                var sample = equityCurve.Select(x => x.Sample);

                var pyDict = new PyDict();
                pyDict.SetItem("equity", pandas.Series(equity, index));
                pyDict.SetItem("sample", pandas.Series(sample, index));

                return(pandas.DataFrame(pyDict));
            }
        }
示例#11
0
        /// <summary>
        /// Return the Discrete Fourier Transform sample frequencies
        /// (for usage with rfft, irfft).
        ///
        /// The returned float array f contains the frequency bin centers in cycles
        /// per unit of the sample spacing (with zero at the start).  For instance, if
        /// the sample spacing is in seconds, then the frequency unit is cycles/second.
        ///
        /// Given a window length n and a sample spacing d:
        ///
        /// Unlike fftfreq (but like scipy.fftpack.rfftfreq)
        /// the Nyquist frequency component is considered to be positive.
        /// </summary>
        /// <param name="n">
        /// Window length.
        /// </param>
        /// <param name="d">
        /// Sample spacing (inverse of the sampling rate). Defaults to 1.
        /// </param>
        /// <returns>
        /// Array of length n//2 + 1 containing the sample frequencies.
        /// </returns>
        public NDarray fft_rfftfreq(int n, float?d = 1.0f)
        {
            //auto-generated code, do not change
            var fft      = self.GetAttr("fft");
            var __self__ = fft;
            var pyargs   = ToTuple(new object[]
            {
                n,
            });
            var kwargs = new PyDict();

            if (d != 1.0f)
            {
                kwargs["d"] = ToPython(d);
            }
            dynamic py = __self__.InvokeMethod("rfftfreq", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
        /// <summary>
        /// Read back a list of all projects on the account for a user.
        /// </summary>
        /// <returns>pandas.DataFrame for list of projects</returns>
        public PyObject ListProjects()
        {
            var listProject = _api.ListProjects();

            if (listProject.Success)
            {
                using (Py.GIL())
                {
                    var pyDict = new PyDict();
                    var index  = listProject.Projects.Select(x => x.ProjectId);
                    pyDict.SetItem("Name", _pandas.Series(listProject.Projects.Select(x => x.Name).ToList(), index));
                    pyDict.SetItem("Created", _pandas.Series(listProject.Projects.Select(x => x.Created).ToList(), index));
                    pyDict.SetItem("Modified", _pandas.Series(listProject.Projects.Select(x => x.Modified).ToList(), index));
                    return(_pandas.DataFrame(pyDict, columns: new[] { "Name", "Created", "Modified" }.ToList()));
                }
            }

            return(null);
        }
示例#13
0
        /// <summary>
        /// Set TensorFlow Backend Session configuration parameters
        /// </summary>
        /// <param name="intra_op_parallelism_threads">The execution of an individual op (for some op types) can be parallelized on a pool of intra_op_parallelism_threads. 0 means the system picks an appropriate number.</param>
        /// <param name="inter_op_parallelism_threads">Nodes that perform blocking operations are enqueued on a pool of inter_op_parallelism_threads available in each process. 0 means the system picks an appropriate number.</param>
        /// <param name="allow_soft_placement">Whether soft placement is allowed. If allow_soft_placement is true, an op will be placed on CPU if 1. there's no GPU implementation for the OP or 2. no GPU devices are known or registered or 3. need to co-locate with reftype input(s) which are from CPU.</param>
        /// <param name="cpu_device_count">Maximum number of CPU devices of that type to use.</param>
        /// <param name="gpu_device_count">Maximum number of GPU devices of that type to use.</param>
        public static void ConfigTensorFlowBackend(int intra_op_parallelism_threads, int inter_op_parallelism_threads, bool allow_soft_placement, int cpu_device_count, int gpu_device_count)
        {
            dynamic tf = Py.Import("tensorflow");
            dynamic kb = Py.Import("keras.backend");

            PyDict deviceCount = new PyDict();

            deviceCount["CPU"] = new PyInt(cpu_device_count);
            deviceCount["GPU"] = new PyInt(gpu_device_count);
            dynamic config = tf.ConfigProto(
                intra_op_parallelism_threads: intra_op_parallelism_threads,
                inter_op_parallelism_threads: inter_op_parallelism_threads,
                allow_soft_placement: allow_soft_placement,
                device_count: deviceCount
                );
            dynamic session = tf.Session(config: config);

            kb.set_session(session);
        }
示例#14
0
        /// <summary>
        ///	Return a new array with sub-arrays along an axis deleted.<br></br>
        ///	 For a one
        ///	dimensional array, this returns those entries not returned by
        ///	arr[obj].<br></br>
        ///
        ///	Notes
        ///
        ///	Often it is preferable to use a boolean mask.<br></br>
        ///	 For example:
        ///
        ///	Is equivalent to np.delete(arr, [0,2,4], axis=0), but allows further
        ///	use of mask.
        /// </summary>
        /// <param name="arr">
        ///	Input array.
        /// </param>
        /// <param name="obj">
        ///	Indicate which sub-arrays to remove.
        /// </param>
        /// <param name="axis">
        ///	The axis along which to delete the subarray defined by obj.<br></br>
        ///
        ///	If axis is None, obj is applied to the flattened array.
        /// </param>
        /// <returns>
        ///	A copy of arr with the elements specified by obj removed.<br></br>
        ///	 Note
        ///	that delete does not occur in-place.<br></br>
        ///	 If axis is None, out is
        ///	a flattened array.
        /// </returns>
        public static NDarray delete(NDarray arr, int obj, int?axis = null)
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
                arr,
                obj,
            });
            var kwargs = new PyDict();

            if (axis != null)
            {
                kwargs["axis"] = ToPython(axis);
            }
            dynamic py = __self__.InvokeMethod("delete", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
        /// <summary>
        ///	Compute the eigenvalues of a complex Hermitian or real symmetric matrix.<br></br>
        ///
        ///	Main difference from eigh: the eigenvectors are not computed.<br></br>
        ///
        ///	Notes
        ///
        ///	Broadcasting rules apply, see the numpy.linalg documentation for
        ///	details.<br></br>
        ///
        ///	The eigenvalues are computed using LAPACK routines _syevd, _heevd
        /// </summary>
        /// <param name="a">
        ///	A complex- or real-valued matrix whose eigenvalues are to be
        ///	computed.
        /// </param>
        /// <param name="UPLO">
        ///	Specifies whether the calculation is done with the lower triangular
        ///	part of a (‘L’, default) or the upper triangular part (‘U’).<br></br>
        ///
        ///	Irrespective of this value only the real parts of the diagonal will
        ///	be considered in the computation to preserve the notion of a Hermitian
        ///	matrix.<br></br>
        ///	It therefore follows that the imaginary part of the diagonal
        ///	will always be treated as zero.
        /// </param>
        /// <returns>
        ///	The eigenvalues in ascending order, each repeated according to
        ///	its multiplicity.
        /// </returns>
        public NDarray linalg_eigvalsh(NDarray a, string UPLO = "L")
        {
            //auto-generated code, do not change
            var linalg   = self.GetAttr("linalg");
            var __self__ = linalg;
            var pyargs   = ToTuple(new object[]
            {
                a,
            });
            var kwargs = new PyDict();

            if (UPLO != "L")
            {
                kwargs["UPLO"] = ToPython(UPLO);
            }
            dynamic py = __self__.InvokeMethod("eigvalsh", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#16
0
        /// <summary>
        ///	Compute the ‘inverse’ of an N-dimensional array.<br></br>
        ///
        ///	The result is an inverse for a relative to the tensordot operation
        ///	tensordot(a, b, ind), i.<br></br>
        ///	 e., up to floating-point accuracy,
        ///	tensordot(tensorinv(a), a, ind) is the “identity” tensor for the
        ///	tensordot operation.
        /// </summary>
        /// <param name="a">
        ///	Tensor to ‘invert’. Its shape must be ‘square’, i.<br></br>
        ///	e.,
        ///	prod(a.shape[:ind]) == prod(a.shape[ind:]).
        /// </param>
        /// <param name="ind">
        ///	Number of first indices that are involved in the inverse sum.<br></br>
        ///
        ///	Must be a positive integer, default is 2.
        /// </param>
        /// <returns>
        ///	a’s tensordot inverse, shape a.shape[ind:] + a.shape[:ind].
        /// </returns>
        public NDarray linalg_tensorinv(NDarray a, int?ind = 2)
        {
            //auto-generated code, do not change
            var linalg   = self.GetAttr("linalg");
            var __self__ = linalg;
            var pyargs   = ToTuple(new object[]
            {
                a,
            });
            var kwargs = new PyDict();

            if (ind != 2)
            {
                kwargs["ind"] = ToPython(ind);
            }
            dynamic py = __self__.InvokeMethod("tensorinv", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#17
0
        /// <summary>
        /// Returns True if cast between data types can occur according to the
        /// casting rule.  If from is a scalar or array scalar, also returns
        /// True if the scalar value can be cast without overflow or truncation
        /// to an integer.
        ///
        /// Notes
        ///
        /// Starting in NumPy 1.9, can_cast function now returns False in ‘safe’
        /// casting mode for integer/float dtype and string dtype if the string dtype
        /// length is not long enough to store the max integer/float value converted
        /// to a string. Previously can_cast in ‘safe’ mode returned True for
        /// integer/float dtype and a string dtype of any length.
        /// </summary>
        /// <param name="from_">
        /// Data type, scalar, or array to cast from.
        /// </param>
        /// <param name="to">
        /// Data type to cast to.
        /// </param>
        /// <param name="casting">
        /// Controls what kind of data casting may occur.
        /// </param>
        /// <returns>
        /// True if cast can occur according to the casting rule.
        /// </returns>
        public bool can_cast(Dtype from_, Dtype to, string casting = "safe")
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
                from_,
                to,
            });
            var kwargs = new PyDict();

            if (casting != "safe")
            {
                kwargs["casting"] = ToPython(casting);
            }
            dynamic py = __self__.InvokeMethod("can_cast", pyargs, kwargs);

            return(ToCsharp <bool>(py));
        }
示例#18
0
                public Parameter(Tensor data, bool?requires_grad = null)
                {
                    //auto-generated code, do not change
                    var nn       = self.GetAttr("nn");
                    var __self__ = nn;
                    var pyargs   = ToTuple(new object[]
                    {
                        data,
                    });
                    var kwargs = new PyDict();

                    if (requires_grad != null)
                    {
                        kwargs["requires_grad"] = ToPython(requires_grad);
                    }
                    dynamic py = __self__.InvokeMethod("Parameter", pyargs, kwargs);

                    self = py as PyObject;
                }
示例#19
0
        public bool Decode(PyObject data)
        {
            if (data.Type != PyObjectType.ObjectData)
            {
                Log.Error("ClientSessionData", "Wrong container type");
                return(false);
            }

            PyObjectData container = data as PyObjectData;

            if (container.Name != "macho.sessionInitialState")
            {
                Log.Error("ClientSessionData", "Wrong container name/type");
                return(false);
            }

            PyTuple args = container.Arguments as PyTuple;

            if (args.Items.Count != 2)
            {
                Log.Error("ClientSessionData", "Wrong args count");
                return(false);
            }

            if (args.Items[0].Type != PyObjectType.Dict)
            {
                Log.Error("ClientSessionData", "Arguments first element is not PyDict");
                return(false);
            }

            session = args.Items[0] as PyDict;

            if ((args.Items[1] is PyInt) == false)
            {
                Log.Error("ClientSessionData", "Arguments second element is not PyInt");
                return(false);
            }

            clientID = (args.Items[1] as PyInt).Value;

            return(true);
        }
示例#20
0
        public CallMachoBindObject(PyTuple payload)
        {
            if (payload == null)
            {
                throw new InvalidDataException("CallMachoBindObject: null payload.");
            }
            if (payload.Items.Count != 2)
            {
                throw new InvalidDataException("CallMachoBindObject: Invalid tuple size expected 2 got" + payload.Items.Count);
            }
            bindArgs = payload.Items[0];
            PyTuple tupleArgs = bindArgs as PyTuple;

            if (tupleArgs != null && tupleArgs.Items.Count == 2 && tupleArgs.Items[0].isIntNumber && tupleArgs.Items[1].isIntNumber)
            {
                locationID      = tupleArgs.Items[0].IntValue;
                locationGroupID = tupleArgs.Items[1].IntValue;
                bindArgs        = null;
            }
            else if (bindArgs.isIntNumber)
            {
                characterID = bindArgs.IntValue;
                bindArgs    = null;
            }
            PyTuple tuple = payload.Items[1] as PyTuple;

            if (tuple != null)
            {
                if (tuple.Items.Count != 3)
                {
                    throw new InvalidDataException("CallMachoBindObject: Invalid tuple size expected 3 got" + tuple.Items.Count);
                }
                if (!(tuple.Items[0] is PyString) || !(tuple.Items[1] is PyTuple) || !(tuple.Items[2] is PyDict))
                {
                    throw new InvalidDataException("CallMachoBindObject: Invalid call structure, expected PyString, PyTuple, PyDict.  Got " +
                                                   tuple.Items[0].Type + ", " + tuple.Items[1].Type + "," + tuple.Items[2].Type);
                }
                callMethod = tuple.Items[0].StringValue;
                callTuple  = tuple.Items[1] as PyTuple;
                callDict   = tuple.Items[2] as PyDict;
            }
        }
示例#21
0
        /// <summary>
        /// Solve the tensor equation a x = b for x.
        ///
        /// It is assumed that all indices of x are summed over in the product,
        /// together with the rightmost indices of a, as is done in, for example,
        /// tensordot(a, x, axes=b.ndim).
        /// </summary>
        /// <param name="a">
        /// Coefficient tensor, of shape b.shape + Q. Q, a tuple, equals
        /// the shape of that sub-tensor of a consisting of the appropriate
        /// number of its rightmost indices, and must be such that
        /// prod(Q) == prod(b.shape) (in which sense a is said to be
        /// ‘square’).
        /// </param>
        /// <param name="b">
        /// Right-hand tensor, which can be of any shape.
        /// </param>
        /// <param name="axes">
        /// Axes in a to reorder to the right, before inversion.
        /// If None (default), no reordering is done.
        /// </param>
        public NDarray tensorsolve(NDarray a, NDarray b, int[] axes = null)
        {
            //auto-generated code, do not change
            var linalg   = self.GetAttr("linalg");
            var __self__ = linalg;
            var pyargs   = ToTuple(new object[]
            {
                a,
                b,
            });
            var kwargs = new PyDict();

            if (axes != null)
            {
                kwargs["axes"] = ToPython(axes);
            }
            dynamic py = __self__.InvokeMethod("tensorsolve", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#22
0
        /// <summary>
        /// Compute the qr factorization of a matrix.
        ///
        /// Factor the matrix a as qr, where q is orthonormal and r is
        /// upper-triangular.
        ///
        /// Notes
        ///
        /// This is an interface to the LAPACK routines dgeqrf, zgeqrf,
        /// dorgqr, and zungqr.
        ///
        /// For more information on the qr factorization, see for example:
        /// https://en.wikipedia.org/wiki/QR_factorization
        ///
        /// Subclasses of ndarray are preserved except for the ‘raw’ mode. So if
        /// a is of type matrix, all the return values will be matrices too.
        ///
        /// New ‘reduced’, ‘complete’, and ‘raw’ options for mode were added in
        /// NumPy 1.8.0 and the old option ‘full’ was made an alias of ‘reduced’.  In
        /// addition the options ‘full’ and ‘economic’ were deprecated.  Because
        /// ‘full’ was the previous default and ‘reduced’ is the new default,
        /// backward compatibility can be maintained by letting mode default.
        /// The ‘raw’ option was added so that LAPACK routines that can multiply
        /// arrays by q using the Householder reflectors can be used. Note that in
        /// this case the returned arrays are of type np.double or np.cdouble and
        /// the h array is transposed to be FORTRAN compatible.  No routines using
        /// the ‘raw’ return are currently exposed by numpy, but some are available
        /// in lapack_lite and just await the necessary work.
        /// </summary>
        /// <param name="a">
        /// Matrix to be factored.
        /// </param>
        /// <param name="mode">
        /// If K = min(M, N), then
        ///
        /// The options ‘reduced’, ‘complete, and ‘raw’ are new in numpy 1.8,
        /// see the notes for more information. The default is ‘reduced’, and to
        /// maintain backward compatibility with earlier versions of numpy both
        /// it and the old default ‘full’ can be omitted. Note that array h
        /// returned in ‘raw’ mode is transposed for calling Fortran. The
        /// ‘economic’ mode is deprecated.  The modes ‘full’ and ‘economic’ may
        /// be passed using only the first letter for backwards compatibility,
        /// but all others must be spelled out. See the Notes for more
        /// explanation.
        /// </param>
        /// <returns>
        /// A tuple of:
        /// q
        /// A matrix with orthonormal columns. When mode = ‘complete’ the
        /// result is an orthogonal/unitary matrix depending on whether or not
        /// a is real/complex. The determinant may be either +/- 1 in that
        /// case.
        /// r
        /// The upper-triangular matrix.
        /// (h, tau)
        /// The array h contains the Householder reflectors that generate q
        /// along with r. The tau array contains scaling factors for the
        /// reflectors. In the deprecated  ‘economic’ mode only h is returned.
        /// </returns>
        public (NDarray, NDarray, NDarray) qr(NDarray a, string mode = "reduced")
        {
            //auto-generated code, do not change
            var linalg   = self.GetAttr("linalg");
            var __self__ = linalg;
            var pyargs   = ToTuple(new object[]
            {
                a,
            });
            var kwargs = new PyDict();

            if (mode != "reduced")
            {
                kwargs["mode"] = ToPython(mode);
            }
            dynamic py = __self__.InvokeMethod("qr", pyargs, kwargs);
            var     t  = py as PyTuple;

            return(ToCsharp <NDarray>(t[0]), ToCsharp <NDarray>(t[1]), ToCsharp <NDarray>(t[2]));
        }
示例#23
0
                public GRUCell(int input_size, int hidden_size, bool bias = true)
                {
                    //auto-generated code, do not change
                    var nn       = self.GetAttr("nn");
                    var __self__ = nn;
                    var pyargs   = ToTuple(new object[]
                    {
                        input_size,
                        hidden_size,
                    });
                    var kwargs = new PyDict();

                    if (bias != true)
                    {
                        kwargs["bias"] = ToPython(bias);
                    }
                    dynamic py = __self__.InvokeMethod("GRUCell", pyargs, kwargs);

                    self = py as PyObject;
                }
示例#24
0
                public Threshold(double threshold, double @value, bool inplace = false)
                {
                    //auto-generated code, do not change
                    var nn       = self.GetAttr("nn");
                    var __self__ = nn;
                    var pyargs   = ToTuple(new object[]
                    {
                        threshold,
                        @value,
                    });
                    var kwargs = new PyDict();

                    if (inplace != false)
                    {
                        kwargs["inplace"] = ToPython(inplace);
                    }
                    dynamic py = __self__.InvokeMethod("Threshold", pyargs, kwargs);

                    self = py as PyObject;
                }
                public DataParallel(Module module, int[] device_ids, int?output_device = null)
                {
                    //auto-generated code, do not change
                    var nn       = self.GetAttr("nn");
                    var __self__ = nn;
                    var pyargs   = ToTuple(new object[]
                    {
                        module,
                        device_ids,
                    });
                    var kwargs = new PyDict();

                    if (output_device != null)
                    {
                        kwargs["output_device"] = ToPython(output_device);
                    }
                    dynamic py = __self__.InvokeMethod("DataParallel", pyargs, kwargs);

                    self = py as PyObject;
                }
示例#26
0
        /// <summary>
        /// Gets symbol information from a list of tickers
        /// </summary>
        /// <param name="pyObject">The tickers to retrieve information for</param>
        /// <returns>A pandas.DataFrame containing the symbol information</returns>
        public PyObject PrintSymbols(PyObject pyObject)
        {
            var symbols = GetSymbolsFromPyObject(pyObject);

            if (symbols == null)
            {
                return("Invalid ticker(s). Please use get_symbol to add symbols.".ToPython());
            }

            using (Py.GIL())
            {
                var data  = new PyDict();
                var index = symbols.Select(x => x.ID);
                data.SetItem("Value", _pandas.Series(symbols.Select(x => x.Value).ToList(), index));
                data.SetItem("Asset Type", _pandas.Series(symbols.Select(x => x.SecurityType.ToString()).ToList(), index));
                data.SetItem("Market", _pandas.Series(symbols.Select(x => x.ID.Market.ToString()).ToList(), index));
                data.SetItem("Start Date", _pandas.Series(symbols.Select(x => x.SecurityType == SecurityType.Equity ? x.ID.Date.ToShortDateString() : null).ToList(), index));
                return(_pandas.DataFrame(data, columns: "Value,Asset Type,Market,Start Date".Split(',').ToList()));
            }
        }
示例#27
0
 public bool TryDecode <T>(PyObject pyObj, out T value)
 {
     if (!PyDict.IsDictType(pyObj))
     {
         value = default;
         return(false);
     }
     using (var pyDict = new PyDict(pyObj))
     {
         if (typeof(T).IsGenericType)
         {
             value = pyDict.ToDictionary <T>();
         }
         else
         {
             value = (T)pyDict.ToDictionary();
         }
         return(true);
     }
 }
示例#28
0
        /// <summary>
        ///	Insert values along the given axis before the given indices.<br></br>
        ///
        ///	Notes
        ///
        ///	Note that for higher dimensional inserts obj=0 behaves very different
        ///	from obj=[0] just like arr[:,0,:] = values is different from
        ///	arr[:,[0],:] = values.
        /// </summary>
        /// <param name="arr">
        ///	Input array.
        /// </param>
        /// <param name="obj">
        ///	Object that defines the index or indices before which values is
        ///	inserted.<br></br>
        ///
        ///	Support for multiple insertions when obj is a single scalar or a
        ///	sequence with one element (similar to calling insert multiple
        ///	times).
        /// </param>
        /// <param name="values">
        ///	Values to insert into arr.<br></br>
        ///	If the type of values is different
        ///	from that of arr, values is converted to the type of arr.<br></br>
        ///
        ///	values should be shaped so that arr[...,obj,...] = values
        ///	is legal.
        /// </param>
        /// <param name="axis">
        ///	Axis along which to insert values.<br></br>
        ///	If axis is None then arr
        ///	is flattened first.
        /// </param>
        /// <returns>
        ///	A copy of arr with values inserted.<br></br>
        ///	  Note that insert
        ///	does not occur in-place: a new array is returned.<br></br>
        ///	 If
        ///	axis is None, out is a flattened array.
        /// </returns>
        public static NDarray insert <T>(NDarray arr, int obj, T values, int?axis = null) where T : struct
        {
            //auto-generated code, do not change
            var __self__ = self;
            var pyargs   = ToTuple(new object[]
            {
                arr,
                ToPython(obj),
            });
            var kwargs = new PyDict();

            kwargs["values"] = ToPython(values);
            if (axis != null)
            {
                kwargs["axis"] = ToPython(axis);
            }
            dynamic py = __self__.InvokeMethod("insert", pyargs, kwargs);

            return(ToCsharp <NDarray>(py));
        }
示例#29
0
        /// <summary>
        /// Return the eigenvalues and eigenvectors of a complex Hermitian
        /// (conjugate symmetric) or a real symmetric matrix.
        ///
        /// Returns two objects, a 1-D array containing the eigenvalues of a, and
        /// a 2-D square array or matrix (depending on the input type) of the
        /// corresponding eigenvectors (in columns).
        ///
        /// Notes
        ///
        /// Broadcasting rules apply, see the numpy.linalg documentation for
        /// details.
        ///
        /// The eigenvalues/eigenvectors are computed using LAPACK routines _syevd,
        /// _heevd
        ///
        /// The eigenvalues of real symmetric or complex Hermitian matrices are
        /// always real. [1] The array v of (column) eigenvectors is unitary
        /// and a, w, and v satisfy the equations
        /// dot(a, v[:, i]) = w[i] * v[:, i].
        ///
        /// References
        /// </summary>
        /// <param name="a">
        /// Hermitian or real symmetric matrices whose eigenvalues and
        /// eigenvectors are to be computed.
        /// </param>
        /// <param name="UPLO">
        /// Specifies whether the calculation is done with the lower triangular
        /// part of a (‘L’, default) or the upper triangular part (‘U’).
        /// Irrespective of this value only the real parts of the diagonal will
        /// be considered in the computation to preserve the notion of a Hermitian
        /// matrix. It therefore follows that the imaginary part of the diagonal
        /// will always be treated as zero.
        /// </param>
        /// <returns>
        /// A tuple of:
        /// w
        /// The eigenvalues in ascending order, each repeated according to
        /// its multiplicity.
        /// v
        /// The column v[:, i] is the normalized eigenvector corresponding
        /// to the eigenvalue w[i].  Will return a matrix object if a is
        /// a matrix object.
        /// </returns>
        public (NDarray, NDarray) eigh(NDarray a, string UPLO = null)
        {
            //auto-generated code, do not change
            var linalg   = self.GetAttr("linalg");
            var __self__ = linalg;
            var pyargs   = ToTuple(new object[]
            {
                a,
            });
            var kwargs = new PyDict();

            if (UPLO != null)
            {
                kwargs["UPLO"] = ToPython(UPLO);
            }
            dynamic py = __self__.InvokeMethod("eigh", pyargs, kwargs);
            var     t  = py as PyTuple;

            return(ToCsharp <NDarray>(t[0]), ToCsharp <NDarray>(t[1]));
        }
示例#30
0
                public LPPool2d(int[] kernel_size, int[] stride, bool ceil_mode = false)
                {
                    //auto-generated code, do not change
                    var nn       = self.GetAttr("nn");
                    var __self__ = nn;
                    var pyargs   = ToTuple(new object[]
                    {
                        kernel_size,
                        stride,
                    });
                    var kwargs = new PyDict();

                    if (ceil_mode != false)
                    {
                        kwargs["ceil_mode"] = ToPython(ceil_mode);
                    }
                    dynamic py = __self__.InvokeMethod("LPPool2d", pyargs, kwargs);

                    self = py as PyObject;
                }