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)); } }
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); }
/// <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)); }
public static dtype result_type(NPY_TYPES type_num) { var return_type = DefaultArrayHandlers.GetArrayHandler(type_num).MathOpFloatingType(UFuncOperation.divide); dtype result_dtype = NpyCoreApi.DescrFromType(return_type); return(result_dtype); }
public static ndarray outer(NpyArray_Ops 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)); }
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(); } }
private static bool can_cast(object from_, dtype to, string casting = "safe") { dtype from = null; if (from_ is dtype) { from = from_ as dtype; } else { try { var arr = asanyarray(from_); if (arr != null) { from = arr.Dtype; } } catch (Exception ex) { return(false); } } return(NpyCoreApi.CanCastTo(from, to)); }
/// <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); }
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 bool Equals(dtype other) { if (other == null) { return(false); } return(this.core == other.core || NpyCoreApi.EquivTypes(this, other)); }
internal byte[] ToString(NPY_ORDER order = NPY_ORDER.NPY_ANYORDER) { long nbytes = Size * Dtype.ElementSize; byte[] data = new byte[nbytes]; NpyCoreApi.GetBytes(this, data, order); return(data); }
internal object Get(npy_intp index) { VoidPtr pos = NpyCoreApi.IterGoto1D(this, index); if (pos == null) { NpyCoreApi.CheckError(); } return(arr.GetItem(index)); }
internal void SingleAssign(npy_intp index, object value) { VoidPtr pos = NpyCoreApi.IterGoto1D(this, index); if (pos == null) { NpyCoreApi.CheckError(); } arr.SetItem(value, index); }
/// <summary> /// Returns the descriptor for a given native type or null if src is /// not a scalar type /// </summary> /// <param name="src">Object to type</param> /// <returns>Descriptor for type of 'src' or null if not scalar</returns> internal static dtype FindScalarType(Object src) { NPY_TYPES type = DefaultArrayHandlers.GetArrayType(src); if (type != NPY_TYPES.NPY_NOTSET) { return(NpyCoreApi.DescrFromType(type)); } return(null); }
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 dtype FindArrayReturn(dtype chktype, dtype minitype) { dtype result = NpyCoreApi.SmallType(chktype, minitype); if (result.TypeNum == NPY_TYPES.NPY_VOID && minitype.TypeNum != NPY_TYPES.NPY_VOID) { result = NpyCoreApi.DescrFromType(NPY_TYPES.NPY_OBJECT); } return(result); }
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)); }
/// <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 bool MoveNext() { if (current == null) { current = core.dataptr; } else { current = NpyCoreApi.IterNext(core); } return(current != null); }
public bool MoveNext() { if (current == null) { current = core; } else { NpyCoreApi.MultiIterNext(core); } return(NpyCoreApi.MultiIterDone(core)); }
public Object this[params object[] args] { get { ndarray result; NpyIndexes indexes = new NpyIndexes(); { NpyUtil_IndexProcessing.IndexConverter(this.arr.ravel(), args, indexes); result = NpyCoreApi.IterSubscript(this, indexes); } if (result.ndim == 0) { return(result.GetItem(0)); } else { return(result); } } set { NpyIndexes indexes = new NpyIndexes(); { NpyUtil_IndexProcessing.IndexConverter(this.arr.ravel(), args, indexes); if (indexes.NumIndexes == 1) { // Special cases for single assigment. switch (indexes.IndexType(0)) { case NpyIndexType.NPY_INDEX_INTP: SingleAssign(indexes.GetIntP(0), value); return; case NpyIndexType.NPY_INDEX_BOOL: if (indexes.GetBool(0)) { SingleAssign(0, value); } return; default: break; } } ndarray array_val = np.FromAny(value, arr.Dtype, 0, 0, 0, null); NpyCoreApi.IterSubscriptAssign(this, indexes, array_val); } } }
private static ndarray ndArrayFromMD(Array ssrc, NPY_TYPES type_num, int ndim) { npy_intp [] newshape = new npy_intp[ndim]; for (int i = 0; i < ndim; i++) { newshape[i] = ssrc.GetLength(i); } dtype WantedDType = NpyCoreApi.DescrFromType(type_num); return(np.array(new VoidPtr(ArrayFromMD(ssrc, type_num), type_num), dtype: WantedDType).reshape(newshape)); }
internal void FillWithScalar(object scalar) { if (Dtype.IsObject) { NpyCoreApi.FillWithObject(this, scalar); } else { ndarray zero_d_array = np.FromAny(scalar, Dtype, flags: NPYARRAYFLAGS.NPY_ALIGNED); NpyCoreApi.FillWithScalar(this, zero_d_array); } }
internal static ndarray reduce(NpyArray_Ops ops, object a, int axis = 0, dtype dtype = null, ndarray @out = null, bool keepdims = false) { ndarray arr = asanyarray(a); if (arr == null) { throw new ValueError("unable to convert a to ndarray"); } NPY_TYPES rtype = dtype != null ? dtype.TypeNum : arr.Dtype.TypeNum; return(NpyCoreApi.PerformReduceOp(arr, axis, ops, rtype, @out, keepdims)); }
internal void AddIntpArray(Object arg) { // Convert to an intp array ndarray arr = np.FromAny(arg, NpyCoreApi.DescrFromType(NPY_TYPES.NPY_INTP), 0, 0, NPYARRAYFLAGS.NPY_FORCECAST, null); // Write the type indexes[num_indexes].type = NpyIndexType.NPY_INDEX_INTP_ARRAY; // Write the array indexes[num_indexes].intp_array = arr.Array; ++num_indexes; }
internal void AddBoolArray(Object arg) { // Convert to an intp array ndarray arr = np.FromAny(arg, NpyCoreApi.DescrFromType(NPY_TYPES.NPY_BOOL), 0, 0, 0, null); // Write the type indexes[num_indexes].type = NpyIndexType.NPY_INDEX_BOOL_ARRAY; // Write the array indexes[num_indexes].bool_array = arr.Array; ++num_indexes; }
internal static ndarray accumulate(UFuncOperation ops, object a, int axis = 0, dtype dtype = null, ndarray @out = null) { ndarray arr = asanyarray(a); if (arr == null) { throw new ValueError("unable to convert a to ndarray"); } NPY_TYPES rtype = dtype != null ? dtype.TypeNum : arr.TypeNum; return(NpyCoreApi.PerformAccumulateOp(arr, axis, ops, rtype, @out)); }
internal NpyIndexes Bind(ndarray arr) { NpyIndexes result = new NpyIndexes(); int n = NpyCoreApi.BindIndex(arr, this, result); if (n < 0) { NpyCoreApi.CheckError(); } else { result.num_indexes = n; } return(result); }
private static ndarray FromScalar(object src, dtype descr, object context) { npy_intp[] dims = new npy_intp[1] { 1 }; ndarray result = NpyCoreApi.AllocArray(descr, 1, dims, false); if (result.ndim != 1) { throw new ArgumentException("shape-mismatch on array construction"); } result.Dtype.f.setitem(0, src, result.Array); return(result); }
internal static ndarray FromNestedList(object src, dtype descr, bool fortran) { npy_intp[] dims = new npy_intp[NpyDefs.NPY_MAXDIMS]; int nd = ObjectDepthAndDimension(src, dims, 0, NpyDefs.NPY_MAXDIMS); if (nd == 0) { return(FromPythonScalar(src, descr)); } ndarray result = NpyCoreApi.AllocArray(descr, nd, dims, fortran); AssignToArray(src, result); return(result); }