public void AddIndex(ndarray arr, string s, int index) { index -= num_newindexes; if (arr != null) { Slice Slice = ParseIndexString(arr, index, s, false); if (Slice != null) { AddIndex(Slice); return; } CSharpTuple CSharpTuple = ParseCSharpTupleString(arr, index, s, false); if (CSharpTuple != null) { AddCSharpTuple(CSharpTuple); return; } } // Write the type indexes[num_indexes].type = NpyIndexType.NPY_INDEX_STRING; // Write the data indexes[num_indexes]._string = s; // Save the string if (strings == null) { strings = new List <string>(); } strings.Add(s); ++num_indexes; }
private static void AssignFromSeq(IEnumerable <Object> seq, ndarray result, int dim, long offset) { if (dim >= result.ndim) { throw new RuntimeException(String.Format("Source dimensions ({0}) exceeded target array dimensions ({1}).", dim, result.ndim)); } if (seq is ndarray && seq.GetType() != typeof(ndarray)) { // Convert to an array to ensure the dimensionality reduction // assumption works. ndarray array = NpyCoreApi.FromArray((ndarray)seq, null, NPYARRAYFLAGS.NPY_ENSUREARRAY); seq = (IEnumerable <object>)array; } if (seq.Count() != result.Dim(dim)) { throw new RuntimeException("AssignFromSeq: sequence/array shape mismatch."); } long stride = result.Stride(dim); if (dim < result.ndim - 1) { // Sequence elements should be additional sequences seq.Iteri((o, i) => AssignFromSeq((IEnumerable <Object>)o, result, dim + 1, offset + stride * i)); } else { seq.Iteri((o, i) => result.Dtype.f.setitem(offset + i * stride, o, result.Array)); } }
/// <summary> /// Copies the source object into the destination array. src can be /// any type so long as the number of elements matches dest. In the /// case of strings, they will be padded with spaces if needed but /// can not be longer than the number of elements in dest. /// </summary> /// <param name="dest">Destination array</param> /// <param name="src">Source object</param> public static void CopyObject(ndarray dest, Object src) { // For char arrays pad the input string. if (dest.Dtype.Type == NPY_TYPECHAR.NPY_CHARLTR && dest.ndim > 0 && src is String) { int ndimNew = (int)dest.Dim(dest.ndim - 1); int ndimOld = ((String)src).Length; if (ndimNew > ndimOld) { src = ((String)src).PadRight(ndimNew, ' '); } } ndarray srcArray; if (src is ndarray) { srcArray = (ndarray)src; } else if (false) { // TODO: Not handling scalars. See arrayobject.c:111 } else { srcArray = np.FromAny(src, dest.Dtype, 0, dest.ndim, 0, null); } NpyCoreApi.MoveInto(dest, srcArray); }
private static ndarray _broadcast_to(object oarray, object oshape, bool subok, bool _readonly) { shape newshape = NumpyExtensions.ConvertTupleToShape(oshape); if (newshape == null) { throw new Exception("Unable to convert shape object"); } if (newshape.iDims == null || newshape.iDims.Length == 0) { newshape = new shape(asanyarray(oarray).shape); } ndarray array = np.array(asanyarray(oarray), copy: false, subok: subok); if (array.dims == null) { throw new ValueError("cannot broadcast a non-scalar to a scalar array"); } if (np.anyb(np.array(newshape.iDims) < 0)) { throw new ValueError("all elements of broadcast shape must be non-negative"); } var toshape = NpyCoreApi.BroadcastToShape(array, newshape.iDims, newshape.iDims.Length); var newStrides = new npy_intp[toshape.nd_m1 + 1]; Array.Copy(toshape.strides, 0, newStrides, 0, newStrides.Length); var result = np.as_strided(array, shape: newshape.iDims, strides: newStrides); return(result); }
public static IEnumerable <ndarray> broadcast_arrays(bool subok, params object[] args) { ndarray[] arrays = new ndarray[args.Length]; for (int i = 0; i < args.Length; i++) { arrays[i] = np.array(args[i], copy: false, subok: subok); } var shape = _broadcast_shape(arrays); bool allsame = true; for (int i = 0; i < arrays.Length; i++) { if (shape != arrays[i].shape) { allsame = false; break; } } if (allsame) { return(arrays); } ndarray[] broadcastedto = new ndarray[args.Length]; for (int i = 0; i < args.Length; i++) { broadcastedto[i] = _broadcast_to(args[i], shape, subok: subok, _readonly: false); } return(broadcastedto); }
internal static ndarray FromPythonScalar(object src, dtype descr) { int itemsize = descr.ElementSize; NPY_TYPES type = descr.TypeNum; if (itemsize == 0 && NpyDefs.IsExtended(type)) { int n = PythonOps.Length(src); if (type == NPY_TYPES.NPY_UNICODE) { n *= 4; } descr = new dtype(descr); descr.ElementSize = n; } ndarray result = NpyCoreApi.AllocArray(descr, 0, null, false); if (result.ndim > 0) { throw new ArgumentException("shape-mismatch on array construction"); } result.Dtype.f.setitem(0, src, result.Array); return(result); }
public static ndarray CheckFromAny(Object src, dtype descr, int minDepth, int maxDepth, NPYARRAYFLAGS requires, Object context) { if ((requires & NPYARRAYFLAGS.NPY_NOTSWAPPED) != 0) { if (descr == null && src is ndarray && !((ndarray)src).Dtype.IsNativeByteOrder) { descr = new dtype(((ndarray)src).Dtype); } else if (descr != null && !descr.IsNativeByteOrder) { // Descr replace } if (descr != null) { descr.ByteOrder = '='; } } ndarray arr = np.FromAny(src, descr, minDepth, maxDepth, requires, context); if (arr != null && (requires & NPYARRAYFLAGS.NPY_ELEMENTSTRIDES) != 0 && arr.ElementStrides == 0) { arr = arr.NewCopy(NPY_ORDER.NPY_ANYORDER); } return(arr); }
public static ndarray as_strided(ndarray x, object oshape = null, object ostrides = null, bool subok = false, bool writeable = false) { npy_intp[] shape = null; npy_intp[] strides = null; if (oshape != null) { shape newshape = NumpyExtensions.ConvertTupleToShape(oshape); if (newshape == null) { throw new Exception("Unable to convert shape object"); } shape = newshape.iDims; } if (ostrides != null) { shape newstrides = NumpyExtensions.ConvertTupleToShape(ostrides); if (newstrides == null) { throw new Exception("Unable to convert strides object"); } strides = newstrides.iDims; } return(as_strided(x, shape, strides, subok, writeable)); }
//Replace NaN with zero and infinity with large finite numbers. //If `x` is inexact, NaN is replaced by zero, and infinity and -infinity //replaced by the respectively largest and most negative finite floating //point values representable by ``x.dtype``. //For complex dtypes, the above is applied to each of the real and //imaginary components of `x` separately. //If `x` is not inexact, then no replacements are made. //Parameters //---------- //x : scalar or array_like // Input data. //copy : bool, optional // Whether to create a copy of `x` (True) or to replace values // in-place (False). The in-place operation only occurs if // casting to an array does not require a copy. // Default is True. // ..versionadded:: 1.13 //Returns //------- //out : ndarray // `x`, with the non-finite values replaced.If `copy` is False, this may // be `x` itself. //See Also //-------- //isinf : Shows which elements are positive or negative infinity. //isneginf : Shows which elements are negative infinity. //isposinf : Shows which elements are positive infinity. //isnan : Shows which elements are Not a Number (NaN). //isfinite : Shows which elements are finite (not NaN, not infinity) //Notes //----- //NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic //(IEEE 754). This means that Not a Number is not equivalent to infinity. //Examples //-------- //>>> np.nan_to_num(np.inf) //1.7976931348623157e+308 //>>> np.nan_to_num(-np.inf) //-1.7976931348623157e+308 //>>> np.nan_to_num(np.nan) //0.0 //>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128]) //>>> np.nan_to_num(x) //array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, // -1.28000000e+002, 1.28000000e+002]) //>>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)]) //>>> np.nan_to_num(y) //array([ 1.79769313e+308 +0.00000000e+000j, // 0.00000000e+000 +0.00000000e+000j, // 0.00000000e+000 +1.79769313e+308j]) /// <summary> /// Replace NaN with zero and infinity with large finite numbers /// </summary> /// <param name="x">Input data.</param> /// <param name="copy">Whether to create a copy of x (True) or to replace values in-place (False).</param> /// <returns></returns> public static object nan_to_num(object x, bool copy = true) { ndarray xa = asanyarray(x); ndarray xn = nan_to_num(xa, copy); return(xn.GetItem(0)); }
/// <summary> /// Performs a generic reduce or accumulate operation on an input array. /// A reduce operation reduces the number of dimensions of the input array /// by one where accumulate does not. Accumulate stores in incremental /// accumulated values in the extra dimension. /// </summary> /// <param name="arr">Input array</param> /// <param name="indices">Used only for reduceat</param> /// <param name="axis">Axis to reduce</param> /// <param name="otype">Output type of the array</param> /// <param name="outArr">Optional output array</param> /// <param name="operation">Reduce/accumulate operation to perform</param> /// <returns>Resulting array, either outArr or a new array</returns> private Object GenericReduce(ndarray arr, ndarray indices, int axis, dtype otype, ndarray outArr, GenericReductionOp operation) { if (signature() != null) { throw new RuntimeException("Reduction is not defined on ufunc's with signatures"); } if (nin != 2) { throw new ArgumentException("Reduce/accumulate only supported for binary functions"); } if (nout != 1) { throw new ArgumentException("Reduce/accumulate only supported for functions returning a single value"); } if (arr.ndim == 0) { throw new ArgumentTypeException("Cannot reduce/accumulate a scalar"); } if (arr.IsFlexible || (otype != null && NpyDefs.IsFlexible(otype.TypeNum))) { throw new ArgumentTypeException("Cannot perform reduce/accumulate with flexible type"); } return(NpyCoreApi.GenericReduction(this, arr, indices, outArr, axis, otype, operation)); }
internal static void SetField(ndarray dest, NpyArray_Descr descr, int offset, object src) { // For char arrays pad the input string. if (dest.Dtype.Type == NPY_TYPECHAR.NPY_CHARLTR && dest.ndim > 0 && src is String) { int ndimNew = (int)dest.Dim(dest.ndim - 1); int ndimOld = ((String)src).Length; if (ndimNew > ndimOld) { src = ((String)src).PadRight(ndimNew, ' '); } } ndarray srcArray; if (src is ndarray) { srcArray = (ndarray)src; } else if (false) { // TODO: Not handling scalars. See arrayobject.c:111 } else { dtype src_dtype = new dtype(descr); srcArray = np.FromAny(src, src_dtype, 0, dest.ndim, NPYARRAYFLAGS.NPY_CARRAY, null); } NpyCoreApi.Incref(descr); if (numpyAPI.NpyArray_SetField(dest.core, descr, offset, srcArray.core) < 0) { NpyCoreApi.CheckError(); } }
/// <summary> /// Return the indices for the lower-triangle of arr. /// </summary> /// <param name="arr">input array. The indices will be valid for square arrays whose dimensions are the same as arr.</param> /// <param name="k">Diagonal offset (see 'tril' for details).</param> /// <returns></returns> public static ndarray[] tril_indices_from(ndarray arr, int k = 0) { /* * Return the indices for the lower-triangle of arr. * * See `tril_indices` for full details. * * Parameters * ---------- * arr : array_like * The indices will be valid for square arrays whose dimensions are * the same as arr. * k : int, optional * Diagonal offset (see `tril` for details). * * See Also * -------- * tril_indices, tril */ if (arr.ndim != 2) { throw new ValueError("input array must be 2-d"); } ndarray m1 = array(arr.dims).A("-2"); ndarray m2 = array(arr.dims).A("-1"); return(tril_indices(n: Convert.ToInt32(m1[0]), k: k, m: Convert.ToInt32(m2[0]))); }
/// <summary> /// Upper triangle of an array. /// </summary> /// <param name="m">input array.</param> /// <param name="k">Diagonal below which to zero elements.</param> /// <returns></returns> public static ndarray triu(ndarray m, int k = 0) { /* * Upper triangle of an array. * * Return a copy of a matrix with the elements below the `k`-th diagonal * zeroed. * * Please refer to the documentation for `tril` for further details. * * See Also * -------- * tril : lower triangle of an array * * Examples * -------- * >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) * array([[ 1, 2, 3], * [ 4, 5, 6], * [ 0, 8, 9], * [ 0, 0, 12]]) */ m = asanyarray(m); ndarray m1 = array(m.dims).A("-2:"); ndarray mask = tri(N: Convert.ToInt32(m1[0]), M: Convert.ToInt32(m1[1]), k: k - 1, dtype: np.Bool); return(where (mask, zeros(new shape(1), dtype: m.Dtype), m) as ndarray); }
public static ndarray outer(UFuncOperation ops, dtype dtype, object a, object b, ndarray @out = null, int?axis = null) { var a1 = np.asanyarray(a); var b1 = np.asanyarray(b); List <npy_intp> destdims = new List <npy_intp>(); foreach (var dim in a1.shape.iDims) { destdims.Add(dim); } foreach (var dim in b1.shape.iDims) { destdims.Add(dim); } ndarray dest = @out; if (dest == null) { dest = np.empty(new shape(destdims), dtype: dtype != null ? dtype : a1.Dtype); } return(NpyCoreApi.PerformOuterOp(a1, b1, dest, ops)); }
private CSharpTuple ParseCSharpTupleString(ndarray arr, int index, string s, bool UseLiteralRanges) { try { if (s.StartsWith("[") && s.EndsWith("]")) { string indexstring = s.Trim('[').Trim(']'); string[] indexParts = indexstring.Split(','); if (indexParts.Length == 1) { return(new CSharpTuple(int.Parse(indexParts[0]))); } if (indexParts.Length == 2) { return(new CSharpTuple(int.Parse(indexParts[0]), int.Parse(indexParts[1]))); } if (indexParts.Length == 3) { return(new CSharpTuple(int.Parse(indexParts[0]), int.Parse(indexParts[1]), int.Parse(indexParts[2]))); } } } catch { } return(null); }
/// <summary> /// Return the indices for the upper-triangle of arr. /// </summary> /// <param name="arr"> ndarray, shape(N, N) The indices will be valid for square arrays.</param> /// <param name="k">Diagonal offset (see 'triu' for details).</param> /// <returns></returns> public static ndarray[] triu_indices_from(ndarray arr, int k = 0) { /* * Return the indices for the upper-triangle of arr. * * See `triu_indices` for full details. * * Parameters * ---------- * arr : ndarray, shape(N, N) * The indices will be valid for square arrays. * k : int, optional * Diagonal offset (see `triu` for details). * * Returns * ------- * triu_indices_from : tuple, shape(2) of ndarray, shape(N) * Indices for the upper-triangle of `arr`. * * See Also * -------- * triu_indices, triu */ if (arr.ndim != 2) { throw new ValueError("input array must be 2-d"); } ndarray m1 = array(arr.dims).A("-2"); ndarray m2 = array(arr.dims).A("-1"); return(triu_indices(Convert.ToInt32(m1[0]), k: k, m: Convert.ToInt32(m2[0]))); }
/// <summary> /// An array with ones at and below the given diagonal and zeros elsewhere. /// </summary> /// <param name="N">Number of rows in the array.</param> /// <param name="M">Number of columns in the array.</param> /// <param name="k">The sub-diagonal at and below which the array is filled.'k' = 0 is the main diagonal, while 'k' LT 0 is below it, and 'k' GT 0 is above.The default is 0.</param> /// <param name="dtype">Data type of the returned array. The default is float.</param> /// <returns></returns> public static ndarray tri(int N, int?M = null, int k = 0, dtype dtype = null) { /* * An array with ones at and below the given diagonal and zeros elsewhere. * * Parameters * ---------- * N : int * Number of rows in the array. * M : int, optional * Number of columns in the array. * By default, `M` is taken equal to `N`. * k : int, optional * The sub-diagonal at and below which the array is filled. * `k` = 0 is the main diagonal, while `k` < 0 is below it, * and `k` > 0 is above. The default is 0. * dtype : dtype, optional * Data type of the returned array. The default is float. * * Returns * ------- * tri : ndarray of shape (N, M) * Array with its lower triangle filled with ones and zero elsewhere; * in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise. * * Examples * -------- * >>> np.tri(3, 5, 2, dtype=int) * array([[1, 1, 1, 0, 0], * [1, 1, 1, 1, 0], * [1, 1, 1, 1, 1]]) * * >>> np.tri(3, 5, -1) * array([[ 0., 0., 0., 0., 0.], * [ 1., 0., 0., 0., 0.], * [ 1., 1., 0., 0., 0.]]) */ if (dtype == null) { dtype = np.Float32; } if (M == null) { M = N; } ndarray m = ufunc.outer(UFuncOperation.greater_equal, np.Bool, arange(N, dtype: _min_int(0, N)), arange(-k, M - k, dtype: _min_int(-k, (int)M - k))); // Avoid making a copy if the requested type is already bool m = m.astype(dtype, copy: false); return(m); }
/// <summary> /// Converts args to arrays and return an array nargs long containing the arrays and /// nulls. /// </summary> /// <param name="args"></param> /// <returns></returns> private ndarray[] ConvertArgs(object[] args) { if (args.Length < nin || args.Length > nargs) { throw new ArgumentException("invalid number of arguments"); } ndarray[] result = new ndarray[nargs]; for (int i = 0; i < nin; i++) { // TODO: Add check for scalars object arg = args[i]; object context = null; if (!(arg is ndarray) && !(arg is ScalarGeneric)) { object[] contextArray = null; contextArray = new object[] { this, new PythonTuple(args), i }; context = new PythonTuple(contextArray); } result[i] = np.FromAny(arg, context: context); } for (int i = nin; i < nargs; i++) { if (i >= args.Length || args[i] == null) { result[i] = null; } else if (args[i] is ndarray) { result[i] = (ndarray)args[i]; } else if (args[i] is flatiter) { // TODO What this code needs to do... Is flatiter the right equiv to PyArrayIter? //PyObject *new = PyObject_CallMethod(obj, "__array__", NULL); //if (new == NULL) { // result = -1; // goto fail; //} else if (!PyArray_Check(new)) { // PyErr_SetString(PyExc_TypeError, // "__array__ must return an array."); // Py_DECREF(new); // result = -1; // goto fail; //} else { // mps[i] = (PyArrayObject *)new; //} throw new NotImplementedException("Calling __array__ method on flatiter (PyArrayIter) is not yet implemented."); } else { throw new ArgumentTypeException("return arrays must be of array type"); } } return(result); }
public static ndarray reshape(this ndarray a, params long[] newshape) { npy_intp[] newdims = new npy_intp[newshape.Length]; for (int i = 0; i < newshape.Length; i++) { newdims[i] = newshape[i]; } return(a.reshape(newdims, NPY_ORDER.NPY_ANYORDER)); }
/// <summary> /// Fill the main diagonal of the given array of any dimensionality. /// </summary> /// <param name="a">array, at least 2-D, whose diagonal is to be filled, it gets modified in-place.</param> /// <param name="val">Value(s) to write on the diagonal. </param> /// <param name="wrap">the diagonal “wrapped” after N columns.</param> public static void fill_diagonal(ndarray a, object val, bool wrap = false) { /* * Fill the main diagonal of the given array of any dimensionality. * * For an array `a` with ``a.ndim >= 2``, the diagonal is the list of * locations with indices ``a[i, ..., i]`` all identical. This function * modifies the input array in-place, it does not return a value. * * Parameters * ---------- * a : array, at least 2-D. * Array whose diagonal is to be filled, it gets modified in-place. * * val : scalar * Value to be written on the diagonal, its type must be compatible with * that of the array a. * * wrap : bool * For tall matrices in NumPy version up to 1.6.2, the * diagonal "wrapped" after N columns. You can have this behavior * with this option. This affects only tall matrices. */ if (a.ndim < 2) { throw new ValueError("array must be at least 2-d"); } npy_intp?end = null; npy_intp?step = null; if (a.ndim == 2) { // Explicit, fast formula for the common case. For 2-d arrays, we // accept rectangular ones. step = a.shape.iDims[1] + 1; // This is needed to don't have tall matrix have the diagonal wrap. if (!wrap) { end = a.shape.iDims[1] * a.shape.iDims[1]; } } else { // For more than d=2, the strided formula is only valid for arrays with // all dimensions equal, so we check first. if (!allb(diff(a.shape.iDims) == 0)) { throw new ValueError("All dimensions of input must be of equal length"); } step = 1 + (npy_intp)(cumprod(a.shape.iDims).A(":-1")).Sum().GetItem(0); } // Write the value out into the diagonal. a.Flat[":" + end.ToString() + ":" + step.ToString()] = val; }
/// <summary> /// Flip array in the up/down direction. /// </summary> /// <param name="m">Input array.</param> /// <returns></returns> public static ndarray flipud(ndarray m) { /* * Flip array in the up/down direction. * * Flip the entries in each column in the up/down direction. * Rows are preserved, but appear in a different order than before. * * Parameters * ---------- * m : array_like * Input array. * * Returns * ------- * out : array_like * A view of `m` with the rows reversed. Since a view is * returned, this operation is :math:`\\mathcal O(1)`. * * See Also * -------- * fliplr : Flip array in the left/right direction. * rot90 : Rotate array counterclockwise. * * Notes * ----- * Equivalent to ``m[::-1,...]``. * Does not require the array to be two-dimensional. * * Examples * -------- * >>> A = np.diag([1.0, 2, 3]) * >>> A * array([[ 1., 0., 0.], * [ 0., 2., 0.], * [ 0., 0., 3.]]) * >>> np.flipud(A) * array([[ 0., 0., 3.], * [ 0., 2., 0.], * [ 1., 0., 0.]]) * * >>> A = np.random.randn(2,3,5) * >>> np.all(np.flipud(A) == A[::-1,...]) * True * * >>> np.flipud([1,2]) * array([2, 1]) */ m = asanyarray(m); if (m.ndim < 1) { throw new ValueError("Input must be >= 1-d."); } return(m.A("::-1", "...")); }
internal static ndarray FromScalar(ScalarGeneric scalar, dtype descr = null) { ndarray arr = scalar.ToArray(); if (descr != null && !NpyCoreApi.EquivTypes((dtype)scalar.dtype, descr)) { arr = NpyCoreApi.CastToType(arr, descr, arr.IsFortran); } return(arr); }
private static int DiscoverItemsize(object s, int nd, int min) { if (s is ndarray) { ndarray a1 = (ndarray)s; return(Math.Max(min, a1.Dtype.ElementSize)); } throw new Exception("not an ndarray"); }
public static ndarray setxor1d(ndarray ar1, ndarray ar2, bool assume_unique = false) { /* * Find the set exclusive-or of two arrays. * * Return the sorted, unique values that are in only one (not both) of the * input arrays. * * Parameters * ---------- * ar1, ar2 : array_like * Input arrays. * assume_unique : bool * If True, the input arrays are both assumed to be unique, which * can speed up the calculation. Default is False. * * Returns * ------- * setxor1d : ndarray * Sorted 1D array of unique values that are in only one of the input * arrays. * * Examples * -------- * >>> a = np.array([1, 2, 3, 2, 4]) * >>> b = np.array([2, 3, 5, 7, 5]) * >>> np.setxor1d(a,b) * array([1, 4, 5, 7]) */ if (!assume_unique) { ar1 = unique(ar1).data; ar2 = unique(ar2).data; } ndarray aux = np.concatenate(new ndarray[] { ar1, ar2 }); if (aux.size == 0) { return(aux); } aux = aux.Sort(); ndarray True1 = np.array(new bool[] { true }); ndarray True2 = np.array(new bool[] { true }); ndarray flag = np.concatenate(new ndarray[] { True1, (aux.A("1:")).NotEquals(aux.A(":-1")), True2 }); ndarray mask = flag.A("1:") & flag.A(":-1"); return(aux.A(mask)); }
/// <summary> /// Dot product of two arrays. /// </summary> /// <param name="a">input array</param> /// <param name="b">input array</param> /// <returns></returns> public static ndarray dot(object a, object b) { dtype d = FindArrayType(asanyarray(a), null); d = FindArrayType(asanyarray(b), d); ndarray arr1 = np.FromAny(a, d, flags: NPYARRAYFLAGS.NPY_ALIGNED); ndarray arr2 = np.FromAny(b, d, flags: NPYARRAYFLAGS.NPY_ALIGNED); return(NpyCoreApi.MatrixProduct(arr1, arr2, d.TypeNum)); }
public static ndarray reshape(this ndarray a, object oshape, NPY_ORDER order = NPY_ORDER.NPY_CORDER) { shape newshape = ConvertTupleToShape(oshape); if (newshape == null) { throw new Exception("Unable to convert shape object"); } return(np.reshape(a, newshape, order)); }
public static ndarray dot(object o1, object o2) { dtype d = FindArrayType(asanyarray(o1), null); d = FindArrayType(asanyarray(o2), d); ndarray a1 = np.FromAny(o1, d, flags: NPYARRAYFLAGS.NPY_ALIGNED); ndarray a2 = np.FromAny(o2, d, flags: NPYARRAYFLAGS.NPY_ALIGNED); return(NpyCoreApi.MatrixProduct(a1, a2, d.TypeNum)); }
private static ndarray reshape_uniq(ndarray uniq, int axis, dtype orig_dtype, npy_intp[] orig_shape) { uniq = uniq.view(orig_dtype); npy_intp[] orig_shape_adjusted = new npy_intp[orig_shape.Length]; Array.Copy(orig_shape, 0, orig_shape_adjusted, 0, orig_shape.Length); orig_shape_adjusted[0] = -1; uniq = uniq.reshape(new shape(orig_shape_adjusted)); uniq = np.swapaxes(uniq, 0, axis); return(uniq); }
/// <summary> /// Finds the offset for a single item assignment to the array. /// </summary> /// <param name="arr">The array we are assigning to.</param> /// <returns>The offset or -1 if this is not a single assignment.</returns> internal npy_intp SingleAssignOffset(ndarray arr) { // Check to see that there are just newaxis, ellipsis, intp or bool indexes for (int i = 0; i < num_indexes; i++) { switch (IndexType(i)) { case NpyIndexType.NPY_INDEX_NEWAXIS: case NpyIndexType.NPY_INDEX_ELLIPSIS: case NpyIndexType.NPY_INDEX_INTP: case NpyIndexType.NPY_INDEX_BOOL: break; default: return(-1); } } // Bind to the array and calculate the offset. NpyIndexes bound = Bind(arr); { npy_intp offset = 0; int nd = 0; for (int i = 0; i < bound.num_indexes; i++) { switch (bound.IndexType(i)) { case NpyIndexType.NPY_INDEX_NEWAXIS: break; case NpyIndexType.NPY_INDEX_INTP: offset += arr.Stride(nd++) * bound.GetIntP(i); break; case NpyIndexType.NPY_INDEX_SLICE: // An ellipsis became a slice on binding. // This is not a single item assignment. return(-1); default: // This should never happen return(-1); } } if (nd != arr.ndim) { // Not enough indexes. This is not a single item. return(-1); } return(offset); } }
internal flagsobj(ndarray arr) { if (arr == null) { flags = NPYARRAYFLAGS.NPY_CONTIGUOUS | NPYARRAYFLAGS.NPY_OWNDATA | NPYARRAYFLAGS.NPY_FORTRAN | NPYARRAYFLAGS.NPY_ALIGNED; } else { flags = arr.Array.flags; } array = arr; }