Namespace NumSharp
Primary NumSharp namespace containing the NDArray type, NumPy-style API facade, dtype metadata, slicing and shape helpers, random state, and NumPy-compatible exception types.
Use this namespace when writing NumSharp code:
- np is the NumPy-style static API, equivalent to Python's
import numpy as np. - NDArray is the main n-dimensional array container.
- Shape, Slice, and NPTypeCode define shape, view, indexing, and dtype behavior.
- NumPyRandom exposes NumPy-compatible MT19937 random generation.
NumSharp targets NumPy 2.x API and behavioral compatibility. Arrays use unmanaged storage,
slicing returns views that share storage, broadcasting follows NumPy shape rules, and the public
NDArray dtype set covers Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Char,
Half, Single, Double, Decimal, Complex, and the text families S, U and StringDType (T).
Text uses NPTypeCode.String with a full DType
descriptor for the width, encoding and missing-value policy. Preserve array.dtype, not just its type code.
NPTypeCode.Empty is a sentinel; NPTypeCode.Float is an alias of Single.
np.strings.add and np.strings.multiply concatenate and repeat text. np.@char is NumPy's
numpy.char module (C# escapes the keyword); NDCharArray
supplies chararray behavior and NDListArray
holds split results. None of these is the numeric UTF-16 Char dtype.
using NumSharp;
var a = np.arange(6).reshape(2, 3);
var b = np.array([10, 20, 30]);
NDArray c = a + b; // NumPy-style broadcasting
NDArray col = c[":, 1"]; // Slicing returns a view
Classes
- AnyToVStringCastingImpl
NumPy's casts INTO
StringDTypefrom another class (any_to_string_resolve_descriptors<safety>): the destination is the given descriptor or a freshStringDType(), and the safety is fixed per source class —safefrom numbers, bool and the datetime pair,same_kindfromUandS.
- ArithmeticError
Python's
ArithmeticError: the base of the numeric failures OverflowError, ZeroDivisionError and FloatingPointError. Catch it to handle all three at once, asexcept ArithmeticErrordoes.
- ArrayMemoryError
NumPy's
_ArrayMemoryError: an array of a given shape and dtype could not be allocated. Its text is NumPy'sUnable to allocate 7.45 GiB for an array with shape (1000000000,) and data type float64, the size in binary units from the shape and the dtype's item size.
- ArrayMethod
NEP 43's
ArrayMethod— ONE object per (input DTypes → output DTypes) implementation of an operation: it resolves the loop descriptors for the given operand descriptors (resolve_descriptors(DType[], DType[], out long)) and hands out the strided inner loop that runs them (get_strided_loop(ArrayMethodContext, bool, long[], out NDArrayMethodFlags)). Casts are the first family (CastingImpl); ufunc loops for a new dtype register the same way (Stage C) instead of adding acase NPTypeCode.X:to the IL generators.
- ArrayMethodContext
NEP 43's
PyArrayMethod_Context: the method being run plus the resolved descriptors — what a strided loop receives so it can read parameters (a datetime unit) without re-resolving.
- AssertionError
Exception that corresponds to Python's
AssertionError, raised where NumPy's own code ends in anassertor intyping.assert_neverfor an argument it does not handle.
- AttributeError
Exception that corresponds to Python/NumPy's AttributeError. Raised when an attribute reference or assignment fails.
- AxisError
NumPy-compatible AxisError exception. Raised when an axis argument is out of bounds for the array's dimensions.
- BaseExceptionGroup
Python's
BaseExceptionGroup: several unrelated exceptions raised together (Python 3.11+, PEP 654), with the operations Python'sexcept*is built on — subgroup(params Type[]), split(params Type[]) and the derive(IEnumerable<Exception>) hook. Its Message is Python'sstr():message (2 sub-exceptions).
- BitGenerator
Base class for the pseudo-random bit generators that drive Generator and the legacy NumPyRandom (
RandomState).
- BitGeneratorState
A snapshot of a bit generator's state — the typed stand-in for NumPy's
bit_generator.statedict.
- BlockingIOError
Python's
BlockingIOError(errnoEAGAIN,EALREADY,EWOULDBLOCK,EINPROGRESS): an operation on a non-blocking object that would have blocked. A buffered write reports how much it wrote first in characters_written.
- BrokenPipeError
Python's
BrokenPipeError(errnoEPIPE,ESHUTDOWN): a write to a pipe whose reader is gone, or to a socket shut down for writing.
- BufferError
Python's
BufferError: a buffer could not be exported in the form a caller asked for. NumPy'sndarray(shape, buffer=memoryview(a[::2]))raises it, because the buffer protocol request asks for a contiguous buffer and a stridedmemoryviewrefuses (memoryview: underlying buffer is not contiguous).
- BuiltinCastingImpl
The cast between two storage-backed builtin classes (NumPy's
add_numeric_cast,convert_datatype.c). Its casting is computed the way NumPy computesspec.casting: the same class, or two NumPy classes of one kind and one size (intc↔int32on Windows,longdouble↔float64) →equiv(NumPy'snumeric_copy_or_byteswap, resolved to no cast at all when both byte orders are native);safewhen the frozen promotion table sayspromote(from, to) == to(NumPy's_npy_can_cast_safely_table); otherwisesame_kindwhen the source kind orders at or below the destination kind (b < u < i < f < c), elseunsafe. These are exactly the rulesnp.can_cast(NPTypeCode, NPTypeCode)always applied, so the builtin answers are unchanged; the class pair now owns them.
- CastingImpl
An ArrayMethod with one input and one output: the cast from From to To (NumPy's
castingimpl). Looked up per class pair by GetCastingImpl(DTypeMeta) and consulted by DTypeCasting (can_cast, cast-safety, descriptor adaptation) and by CastDescrToDType(DType, DTypeMeta) (which is how a parametric class learns the instance an operand of another class should become).
- CharModule
The
numpy.charmodule surface, reachable as char: NumPy's legacy vectorized string operations. Its own functions are the comparisons that strip trailing whitespace (equal(object, object), not_equal(object, object), less(object, object), less_equal(object, object), greater(object, object), greater_equal(object, object), compare_chararrays(object, object, object, bool)), multiply(object, object) (its ValueError rule), partition(object, object) / rpartition(object, object) (the three parts stacked on a new last axis), the object path (split(object, object, object), rsplit(object, object, object), splitlines(object, object), join(object, object)) and thechararrayconstructors (chararray(Shape, long, bool, object, long, long[], char), array(object, long?, bool, bool?, char?), asarray(object, long?, bool?, char?)); the others ARE np.strings' functions (NumPy re-exports the same function objects), so they answer exactly as np.strings does, overS,UandStringDTypetext.
- ChebyshevModule
numpy.polynomial.chebyshev— Chebyshev series of the first kindp(x) = c[0]*T_0(x) + c[1]*T_1(x) + …, reachable asnp.polynomial.chebyshev. Coefficients are LOW degree first.
- ChildProcessError
Python's
ChildProcessError(errnoECHILD, 10): an operation on a child process that does not exist (os.waitpidwith no children).
- ConnectionAbortedError
Python's
ConnectionAbortedError(errnoECONNABORTED): a connection the peer (or the local stack) aborted.
- ConnectionError
Python's
ConnectionError: the base of the connection failures, BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError. No errno names it directly.
- ConnectionRefusedError
Python's
ConnectionRefusedError(errnoECONNREFUSED): a connection the peer refused.
- ConnectionResetError
Python's
ConnectionResetError(errnoECONNRESET): a connection the peer reset.
- ConverterError
NumPy's
numpy.lib._iotools.ConverterError(alsonumpy.lib.npyio.ConverterError): a string value thatnp.genfromtxt's column converter cannot convert (Converter #2 is locked and cannot be upgraded: (occurred line #4 for value 'abc')).
- ConverterLockError
NumPy's
numpy.lib._iotools.ConverterLockError: an attempt to upgrade a locked column converter ofnp.genfromtxt(one whose dtype the caller fixed) to a wider type.
- DType
NumSharp's data-type descriptor — the INSTANCE of a DTypeMeta class, standing in for NumPy's
numpy.dtypeobject (np.dtype('f8'),np.dtype('M8[ns]')), and the single dtype spelling every dtype-taking API in NumSharp accepts.
- DTypeCasting
The NEP 43 casting engine over descriptors — the ports of NumPy's
convert_datatype.centry points: GetCastingImpl(DTypeMeta, DTypeMeta) (PyArray_GetCastingImpl), GetCastInfo(DType, DType, DTypeMeta, out long) (PyArray_GetCastInfo), CheckCastSafety(NPY_CASTING, DType, DType, DTypeMeta) (PyArray_CheckCastSafety), CanCastTypeTo(DType, DType, NPY_CASTING) (PyArray_CanCastTypeTo— the engine behindnp.can_cast), EquivTypes(DType, DType) (PyArray_EquivTypes), MinCastSafety(NPY_CASTING, NPY_CASTING) and the casting-string parser. Every question is answered by the CastingImpl registered for the CLASS pair, so a new dtype joinsnp.can_castby registering its casts — no table edit.
- DTypeMeta
The DType CLASS — NumPy's
PyArray_DTypeMeta(type(np.dtype('f8')), i.e.np.dtypes.Float64DType). One live object per dtype class; a DType is an INSTANCE of it (the descriptor). This is NEP 41/42's two-level model: behaviour lives on the class as virtual "slots" (common_dtype(DTypeMeta), common_instance(DType, DType), default_descr(), ensure_canonical(DType), discover_descr_from_pyobject(object), is_known_scalar_type(Type), the casting implementations), parameters live on the instance (a datetime unit, a byte order).
- DTypePromotion
The NEP 42 / NEP 50 promotion engine over DType classes and descriptors — the ports of NumPy's
common_dtype.candconvert_datatype.c: CommonDType(DTypeMeta, DTypeMeta) (PyArray_CommonDType), PromoteDTypeSequence(IReadOnlyList<DTypeMeta>) (PyArray_PromoteDTypeSequencewith itsreduce_dtypes_to_most_knowledgeablepass), PromoteTypes(DType, DType) (PyArray_PromoteTypes), CastDescrToDType(DType, DTypeMeta) (PyArray_CastDescrToDType), CastToDTypeAndPromoteDescriptors(IReadOnlyList<DType>, DTypeMeta) and ResultType(params object[]) (PyArray_ResultType, the NEP 50 entry point where C# literals are weak and arrays — 0-d included — are strong).
- DTypePromotionError
numpy.exceptions.DTypePromotionError— raised when two (or more) DTypes have no common DType, i.e.np.promote_types/np.result_typecannot find a dtype that can hold every input (NEP 42'scommon_dtypeprotocol returnedNotImplementedin both directions).
- DTypeRegistry
The table of live DTypeMeta classes and their casting implementations — NumPy's
_builtin_descrs/typenum_to_dtypemeta/_PyArray_MapPyTypeToDTyperolled into one static registry. Lookups by NPTypeCode, C# scalar Type, NumPy type number and class name (aliases included); Register(DTypeMeta) admits a new class (a Stage C/D dtype, a user dtype) without touching the kernel switches — the class registers its code and its casts, and the promotion/casting engines pick it up.
- DatetimeDTypeMeta
The DType classes of
datetime64(np.dtypes.DateTime64DType, type number 21, kind/char'M') andtimedelta64(np.dtypes.TimeDelta64DType, 22,'m') — NumSharp's first PARAMETRIC classes: the unit metadata (DatetimeMetaData) lives on the descriptor INSTANCE, soM8[ns]andM8[s]are two descriptors of one class, and promotion runs common_instance(DType, DType) (the unit GCD) instead of returning a class default.
- DatetimeTimedeltaCastingImpl
The cast between
datetime64andtimedelta64(either direction) — NumPy'sdatetime_to_timedelta_resolve_descriptors: the destination inherits the SOURCE's unit when none is given (which is howpromote_typesturnsm8[Y]intoM8[Y]before taking the GCD), and the cast is alwaysunsafe.
- EOFError
Python's
EOFError: a read that hit the end of its input with nothing to read. NumSharp raises it where NumPy does:np.loadon an empty file, or past the last array of a file that holds several (No data left in file).
- EmathModule
The
numpy.emath(numpy.lib.scimath) module surface, reachable as emath. Holds the nine automatic-domain functions (sqrt(NDArray), log(NDArray), log2(NDArray), log10(NDArray), logn(NDArray, NDArray), power(NDArray, NDArray), arccos(NDArray), arcsin(NDArray), arctanh(NDArray)).Each function's body is its engine member (EmathSqrt(NDArray) and its siblings in
TensorEngine.Scimath.cs), whichDefaultEngineimplements as a PURE COMPOSITION over the existingnp.*ufuncs — a domain scan (np.anyof a comparison), an optional cast to complex128, then the standard real/complex ufunc — a line-for-line port of NumPy 2.4.2numpy/lib/_scimath_impl.py. The methods here keep the signatures, the class-boundary statements and one call. Because the numerics ARE the already-validatednp.sqrt/np.log/np.arccos/… kernels, emath introduces no divergence of its own — every difference from NumPy traces to a documented property of the underlying ufunc (validated by an 897-case layout-aware differential, 775 bit-exact + 122 accounted). Results are bit-identical to NumPy on every REAL path and on the bit-exact COMPLEX paths (complexsqrt/log/log10/log2); the remaining complex paths inherit the underlying complex ufunc's precision: arccos(NDArray)/arcsin(NDArray)/arctanh(NDArray) ride the complex-unary ≤~1-ULP envelope (a property ofnp.arccosetc. itself — e.g. plainnp.arccos(-0.5+0j)is already 1 ULP from NumPy — not something emath adds), and power(NDArray, NDArray) with a non-integer exponent isallclose(the F5 complex-powerdivergence, see that method).ONE dtype-only divergence (F1): NumSharp has a single complex type (complex128) and no complex64, so a triggering
float32/float16/small-int input returns complex128 where NumPy returns complex64. The VALUES are bit-identical; only the dtype width differs (the library-wide "no complex64" divergence, issue #569).
- EnvVars
Central, typed accessor for every environment variable NumSharp reads. Each property RETURNS THE VALUE (not the name), read through the shared Get(string) / GetBool(string, bool) helpers, so null/blank handling, trimming and boolean parsing live in ONE place. Read-sites use e.g.
if (EnvVars.DebugGuardPages)orvar lib = EnvVars.OpenBlasLibrary;instead of repeatingEnvironment.GetEnvironmentVariable(...)and its parsing.
- ExceptionGroup
Python's
ExceptionGroup: a BaseExceptionGroup whose members are all PythonExceptions, the group ordinary code raises and catches (except*).
- FftEngine
The contract of
numpy.fft: one member per function that computes (16 of NumPy's 18;fftshiftandifftshiftare rolls of the array object). An engine reaches it through Fft, and every publicnp.fftfunction makes C#'s conversions and calls one member (woven: a subclass operand arrives as its plain view, and the declared mechanism answers for the class).
- FileExistsError
Python's
FileExistsError(errnoEEXIST, 17): creating a file or directory that already exists (open(path, 'x'),os.mkdir).
- FileNotFoundError
Python's
FileNotFoundError(errnoENOENT, 2): a file or directory that does not exist. NumSharp's file functions raise it as CPython'sopen()does:np.load/np.fromfile/np.saveinto a missing directory read[Errno 2] No such file or directory: 'x.npy', andnp.loadtxt'sDataSourceraisesx.txt not found.(its own text, without an errno).
- FloatingPointError
Python's
FloatingPointError: the error NumPy raises for a floating-point exception whennp.seterr(all='raise')(ornp.errstate) turns warnings into errors, with NumPy's text (divide by zero encountered in divide,overflow encountered in exp).
- FourierModule
The
numpy.fftmodule surface, reachable as fft. Holds the 18 public transforms/helpers (standardfft/ifft/fft2/ifft2/fftn/ifftn, realrfft/irfft/rfft2/irfft2/rfftn/irfftn, hermitianhfft/ihfft, and helpersfftfreq/rfftfreq/fftshift/ifftshift).The transforms and
fftfreq/rfftfreqare members of the Fft sub-engine (FftEngine): each method here keeps its signature and its documentation and makes one call into the sub-engine of its operand's engine (hfft on the plain view itsnp.conjugateneeds), so an engine assigned to Fft computes every function of this module. The default, DefaultFftEngine, validates and resolves everything NumPy's Python layer does — n/axis/norm/shape/dtype and the N-D→1-D decomposition — then computes throughPocketFFTDriver.Execute, the managed port of pocketfft's 1-D engine (bit-identical to NumPy 2.4.2 on the double/complex128 path).fftshift/ifftshiftroll the array object and stay compositions overnp.rollhere.
- Generator
The modern NumPy random number container returned by
np.random.default_rng.
- GeneratorExit
Python's
GeneratorExit: raised inside a generator when it is closed (generator.close()), so itsfinallyblocks run.
- HermiteEModule
numpy.polynomial.hermite_e— probabilists' Hermite seriesp(x) = c[0]*He_0(x) + c[1]*He_1(x) + …, reachable asnp.polynomial.hermite_e. Coefficients are LOW degree first.
- HermiteModule
numpy.polynomial.hermite— physicists' Hermite seriesp(x) = c[0]*H_0(x) + c[1]*H_1(x) + …, reachable asnp.polynomial.hermite. Coefficients are LOW degree first.
- ImportError
Python's
ImportError: a module or a name in it could not be imported. NumSharp itself raises none (.NET binds its assemblies at build time); the class exists so code ported from Python keeps Python'sraise ImportError(...)andexcept ImportError- a plugin or registry that loads by name, a missing optional dependency - with Python's attributes.
- IncorrectSizeException
Raised when an array that is not of size 1 is read as one scalar:
item()with NumPy's text (can only convert an array of size 1 to a Python scalar), andnp.asscalarand the scalar conversions inConvertswith NumSharp's own (Unable to convert NDArray to scalar because size is not 1.).
- IncorrectTypeException
Raised when a dtype cannot satisfy an operation — the ufunc "no loop matching the specified signature and casting was found", a dtype= request with no matching loop, or a dtype that a function forbids ("i0 not supported for complex values", "x may not be complex"). Every one of these is a NumPy
TypeError, which is why this derives from TypeError: a caller writingcatch (TypeError)(the way NumPy code writesexcept TypeError) now catches it, whilecatch (NumSharpException)still works because TypeError is itself a NumSharpException. Do NOT re-parent this to NumSharpException directly — that silently drops it out of theTypeErrorhierarchy and reopens the parity gap (a ufunc type error that acatch (TypeError)misses).
- IndentationError
Python's
IndentationError: source whose indentation is wrong (unexpected indent,expected an indented block).
- IndexError
Exception that corresponds to Python/NumPy's IndexError. Raised when a sequence subscript is out of range, or when an index type is invalid (e.g. float/complex index on an ndarray).
- InterruptedError
Python's
InterruptedError(errnoEINTR, 4): a system call a signal interrupted (CPython retries most of them itself since PEP 475).
- IsADirectoryError
Python's
IsADirectoryError(errnoEISDIR, 21): a file operation on a directory. NumSharp's file functions raise it as CPython'sopen()does on Linux and macOS ([Errno 21] Is a directory: 'data'); on Windows the same open is a PermissionError, as in CPython.
- KeyError
Exception that corresponds to Python/NumPy's KeyError. Raised when a mapping (dict) key is not found.
- KeyboardInterrupt
Python's
KeyboardInterrupt: the user pressed the interrupt key (Ctrl+C), which CPython turns into this error in the running code.
- LaguerreModule
numpy.polynomial.laguerre— Laguerre seriesp(x) = c[0]*L_0(x) + c[1]*L_1(x) + …, reachable asnp.polynomial.laguerre. Coefficients are LOW degree first.
- LapackError
NumPy's
numpy.linalg.lapack_lite.LapackError: the error NumPy's bundledlapack_litemodule raises when a LAPACK call gets an argument it cannot pass (Parameter a is not contiguous in lapack_lite.dgelsd,Parameter a is not of type float64 in lapack_lite.dgelsd).
- LegacyBuiltinDTypeMeta
The DType class of a storage-backed NumSharp dtype — the 15 element types (plus the vestigial String), wrapped the way NumPy's
dtypemeta_wrap_legacy_descriptorwraps its builtin descriptors intonumpy.dtypes.*DTypeclasses. Data-driven: the registry constructs one per NPTypeCode with its NumPy type number, kind, char, size, alignment and aliases; the behaviour slots are the builtin ones — the singleton is the default descriptor, and common_dtype(DTypeMeta) is NumPy'sdefault_builtin_common_dtypeover NumSharp's frozen promotion table (NumSharp.np._nptypemap_arr_arr), so every existingpromote_typesanswer is reproduced bit-for-bit.
- LegacyWrappingCastingImpl
A cast whose safety is fixed per class pair with the plain descriptor resolution — NumPy's
PyArray_AddLegacyWrapping_CastingImpl, used for the numeric ↔ datetime/timedelta casts (every cast to or fromdatetime64isunsafe; an integer or bool castssafely totimedelta64, a 64-bit unsigned one onlysame_kind, a float or complex onlyunsafely) and for the casts OUT of a string class into a numeric class ortimedelta64(alwaysunsafe: text parses into a number).
- LegendreModule
numpy.polynomial.legendre— Legendre seriesp(x) = c[0]*P_0(x) + c[1]*P_1(x) + …, reachable asnp.polynomial.legendre. Coefficients are LOW degree first.
- LinAlgError
NumPy-compatible
numpy.linalg.LinAlgError. Raised by np.linalg when a matrix is unsuitable for the requested factorisation — the wrong rank, not square, singular, or not positive definite.
- LinalgEngine
The contract of
numpy.linalg: one member per function that computes (29 of NumPy's 31; the viewsdiagonalandmatrix_transposeare the array object's), plus a second C# form where NumPy's argument is an int or a tuple (Tensordot(NDArray, NDArray, int[], int[]), VectorNorm(NDArray, int, bool, object)). An engine reaches it through Linalg, and every publicnp.linalgfunction calls one member (woven: anumpy.matrixornumpy.char.chararrayoperand arrives as its plain view, and the declared mechanism answers for the class).
- LookupError
NumPy-compatible
LookupError: a name that a registry does not know. NumSharp raises it where Python's codec registry does — an encoding namenp.savetxt/np.loadtxtcannot resolve (unknown encoding: bytes:np.savetxthas no special'bytes'encoding, unlikenp.loadtxt).
- MAError
NumPy's
numpy.ma.MAError: the base exception for masked-array errors. Distinct from the ordinary NumSharp/NumPy exceptions so a caller can catch masked-array-specific failures without also catching unrelated Exceptions. NumSharp'snp.masurface does not yet RAISE this itself (the current failures leak the underlyingnp.*exception), so it exists for API/type parity and for callers that want to throw it from their own masked-array code.
- MT19937
The Mersenne Twister MT19937 bit generator (NumPy's
numpy.random.MT19937) — the engine behind the legacy NumPyRandom (RandomState) and usable with Generator.
- MT19937.State
The MT19937 state — NumPy's
{'bit_generator': 'MT19937', 'state': {'key': uint32[624], 'pos': int}}with the nested'state'dict flattened.
- MaskError
NumPy's
numpy.ma.MaskError: a mask-specific MAError (raised by NumPy when an operation cannot honor the mask). Extends MAError exactly as NumPy'sMaskErrorextendsMAError, socatch (MAError)also catches it.
- MaskedArrayModule
The
numpy.mamodule surface, reachable as ma. Holds the masked-array substrate (getdata(object)/getmask(object)/getmaskarray(object)/filled(object, object)/ NDMasked/nomask) and the masked ufunc family — every unary/binary arithmetic, comparison, logical and bitwise op NumPy exposes onnumpy.mavia its_MaskedUnaryOperation/_MaskedBinaryOperation/_DomainedBinaryOperationwrappers.Each ufunc is a thin wrapper that (1) pulls the raw data out of its operand(s), (2) calls the already-optimized
np.*kernel on that data, and (3) propagates the mask — pass-through for a domain-free unary, logical-OR of the input masks for a binary, and OR'd with the domain's invalid-input predicate for a domained op (sqrt/log/divide/…). No new compute loop is emitted; the work is mask bookkeeping over existing IL/NDIter-backed ops.Reductions (
sum/mean/…), creation (zeros/arange/…) and theextrasfunctions are separate mechanisms and are NOT part of this ufunc-family module yet.
- MaskedPrintOption
NumPy's
numpy.ma.masked_print_option: the mutable, process-global object controlling how masked elements are DISPLAYED and whether that display happens at all. Reach for it to change the two-character--placeholder (set_display(string)) or to turn the placeholder off entirely (enable(bool)) so masked slots print their FILL value instead — the two ways NumPy lets you tune a masked repr globally.It is a single shared instance behind masked_print_option — mutating it (like NumPy's module global) changes every subsequent ToString(), so it is a global side effect: set it back if you only meant a local change.
- MemoryError
Python's
MemoryError: an allocation that cannot be satisfied. NumSharp raises it where NumPy does, with NumPy's text: aStringDTypecell that cannot be allocated, loaded or packed (Failed to allocate string in add,Failed to load string in string comparison), an iterator whose buffers cannot be allocated (Could not allocate the iterator's buffers), CPython's barePyErr_NoMemory(an empty text), and an array allocation, as the subclass ArrayMemoryError.
- MethodImplOptionsConstants
Method implementation option constants for use with MethodImplAttribute.
- MissingBackendException
Raised when an operation needs a pluggable compute backend — an IBlasBackend assigned to Blas — and none is installed, or the installed one declined these operands.
- ModuleNameAttribute
Marks a public type as the C# host of a NumPy module surface — the type whose public members ARE that module's functions.
npitself carries"np", NDArray carries"ndarray", and each function-namespace facade carries its dotted Python path ("np.random"on NumPyRandom,"np.fft"on FourierModule,"np.linalg"on the nestednp.linalgclass).
- ModuleNotFoundError
Python's
ModuleNotFoundError, the ImportError raised when a module cannot be located (No module named 'x'). NumSharp itself raises none; a port raises it where its Python source does - a registry that resolves"module:Name"entry points, for example.
- MrClass
The masked counterpart of r_ — NumPy's
numpy.ma.mr_(anMAxisConcatenator): concatenates masked arrays / slices / scalars along the first axis, propagating the mask, with the SAME slice-expression grammar as r_ (a colon-string is a slice, a leading directive string sets axis/ndmin/matrix — the library-wide convention). Reach for it to stitch masked pieces together the waynp.r_stitches plain arrays.
- NDAnchoredAttribute
Marks a method that opens NO NDScope as an operand anchor: at build time the NumSharp IL weaver roots each of its parameters that can reach an NDArray (and
this, for an instance method of a class) from the method's entry to every return, so an operand the caller passed as a temporary cannot be collected while a kernel inside the call still reads its memory. Use it on an unscoped entry point that hands an operand's raw address to a kernel; a NDScopedAttribute method already gets the same rooting and must not carry this attribute too.
- NDArray
Container protocol implementation for NDArray. Provides Python-compatible container protocol methods: contains, hash, len, iter, getitem, setitem
- NDArrayFlags
The memory-layout flags of an NDArray — a byte-for-byte port of NumPy 2.4.2's
arrayflagsobject (numpy/_core/src/multiarray/flagsobject.c): the lowercase dotted attributes (c_contiguous,f_contiguous,owndata,writeable,aligned,writebackifcopy, and the derivedfnc/forc/behaved/carray/farray/num), the bracket-key accessor (flags["C"],flags["F_CONTIGUOUS"], …), the six-line ToString() repr, and equality by the integer num. Values are read live from the array's Shape and storage, verified equal to NumPy across every layout (C/F/strided/transposed/broadcast/0-d/empty).ALIGNED is true for every array over NumSharp's own memory (its allocations are always aligned). It is false for an array over a caller's buffer at a byte offset that splits the dtype's alignment (
np.ndarray(shape, buffer=b, offset=3),np.frombuffer(b, offset=3)) and for every view of one, as NumPy computes it from the data pointer. setflags(bool?, bool?, bool?) /flags["A"] = falseclears it on one array object — NumPy parity, the flag then reads back False andnum/behaved/carray/farrayfollow. WRITEBACKIFCOPY is always false (NumSharp has no copy-on-write handoff), matching what a NumSharp array can be.
- NDArrayNetInterop
Fluent bridges from NumSharp iteration to built-in .NET types — the "other types (foreach or non-foreach)" companions to the by-
ref T/Span<T>walks and to NDArray._Unsafe.These are the SAFE side of the integration: AsEnumerable<T>(NDArray) gives LINQ/collection interop with UNBOXED elements (only the enumerator is heap-allocated, once, not each element), and the iterator
ToArray/CopyToextensions MATERIALIZE or COPY into caller-owned .NET storage — so, unlike the aliasingnd.Unsafe.*views, the result does not depend on the NDArray staying alive. For a zero-copy aliasingSpan<T>/Memory<T>over the buffer, usend.Unsafe(see Unsafe).
- NDBorrowedAttribute
Marks a field, property, class or struct as borrowing the NDArray(s) it references — they are owned and disposed by someone else — so the compile-time ownership analyzer (
NumSharp.Build.Analyzer) must not demand that the containing type dispose them.
- NDCharArray
NumPy's
numpy.char.chararray: a string array (SorU) whose single elements come back with their trailing whitespace stripped (c[0]of['ab ']is'ab') and whose views and copies stay chararrays. Create one with chararray(Shape, long, bool, object, long, long[], char), array(object, long?, bool, bool?, char?) or asarray(object, long?, bool?, char?), or view an existing string array with view(DType, Type). NumPy keeps the class for backward compatibility with Numarray and recommends plainS/Uarrays and thenp.char/np.stringsfunctions for new code.
- NDChebyshev
NumPy's
numpy.polynomial.chebyshev.Chebyshev: a Chebyshev series of the first kind:c[0]·T₀(x) + c[1]·T₁(x) + …, with a domain (default[-1, 1]) mapped onto a window (default[-1, 1]). Arithmetic (+ - * / %, __floordiv__(object), __divmod__(object), __pow__(object)), evaluation (__call__(object)), calculus (integ(int, object, object), deriv(int)), roots, fitting (fit(object, object, object, object, object, bool, object, object, string)), conversion between bases (convert(object, Type, object), cast(NDPolyBase, object, object)) and printing, all as NumPy 2.4.2 has them.
- NDHermite
NumPy's
numpy.polynomial.hermite.Hermite: a (physicists') Hermite series:c[0]·H₀(x) + c[1]·H₁(x) + …, with a domain (default[-1, 1]) mapped onto a window (default[-1, 1]). Arithmetic (+ - * / %, __floordiv__(object), __divmod__(object), __pow__(object)), evaluation (__call__(object)), calculus (integ(int, object, object), deriv(int)), roots, fitting (fit(object, object, object, object, object, bool, object, object, string)), conversion between bases (convert(object, Type, object), cast(NDPolyBase, object, object)) and printing, all as NumPy 2.4.2 has them.
- NDHermiteE
NumPy's
numpy.polynomial.hermite_e.HermiteE: a (probabilists') HermiteE series:c[0]·He₀(x) + c[1]·He₁(x) + …, with a domain (default[-1, 1]) mapped onto a window (default[-1, 1]). Arithmetic (+ - * / %, __floordiv__(object), __divmod__(object), __pow__(object)), evaluation (__call__(object)), calculus (integ(int, object, object), deriv(int)), roots, fitting (fit(object, object, object, object, object, bool, object, object, string)), conversion between bases (convert(object, Type, object), cast(NDPolyBase, object, object)) and printing, all as NumPy 2.4.2 has them.
- NDLaguerre
NumPy's
numpy.polynomial.laguerre.Laguerre: a Laguerre series:c[0]·L₀(x) + c[1]·L₁(x) + …, with a domain (default[0, 1]) mapped onto a window (default[0, 1]). Arithmetic (+ - * / %, __floordiv__(object), __divmod__(object), __pow__(object)), evaluation (__call__(object)), calculus (integ(int, object, object), deriv(int)), roots, fitting (fit(object, object, object, object, object, bool, object, object, string)), conversion between bases (convert(object, Type, object), cast(NDPolyBase, object, object)) and printing, all as NumPy 2.4.2 has them.
- NDLegendre
NumPy's
numpy.polynomial.legendre.Legendre: a Legendre series:c[0]·P₀(x) + c[1]·P₁(x) + …, with a domain (default[-1, 1]) mapped onto a window (default[-1, 1]). Arithmetic (+ - * / %, __floordiv__(object), __divmod__(object), __pow__(object)), evaluation (__call__(object)), calculus (integ(int, object, object), deriv(int)), roots, fitting (fit(object, object, object, object, object, bool, object, object, string)), conversion between bases (convert(object, Type, object), cast(NDPolyBase, object, object)) and printing, all as NumPy 2.4.2 has them.
- NDListArray
NumPy's object array of Python lists — what
np.char.split,rsplitandsplitlinesreturn (array([list(['a', 'b']), list([])], dtype=object)). NumSharp has no object dtype, so this type holds the array's elements as list ids (NumPy's object pointers) into a shared store of the lists: the text of the pieces once, each piece with its exact length.
- NDMaskedArray
A NumPy
numpy.ma.MaskedArray: an NDArray of data paired with a boolean mask marking elements to ignore. Distinct from a plain NDArray precisely because operations SKIP the masked elements' influence and preserve their mask into the result — reach for it only when some entries are invalid/missing and must not participate in arithmetic while keeping the array's shape.The mask is stored as
nullwhen there is no mask (NumPy'snomaskfast path), which is what keeps an all-valid masked array as cheap as the underlying NDArray. The data is never null. This type deliberately does NOT own/dispose its arrays — it holds references the way NumPy's MaskedArray holds views over its base — so the caller keeps the source arrays alive.
- NDMaskedConstant
NumPy's
numpy.ma.maskedsingleton: the scalar constant that represents "a single masked value". A masked ufunc that reduces to one fully-masked 0-D element returns this instance, matching NumPy wherenp.ma.add(masked, x)and a masked 0-D result aremasked.
- NDMatrix
NumPy's
numpy.matrix: a two-dimensional array whose*is the matrix product, whose rows and columns stay two-dimensional when indexed, and which adds T, H, I, A and A1. Create one with matrix(NDArray, DType, bool), asmatrix(NDArray, DType) or bmat(NDArray[][]). Use it to port NumPy code written againstnp.matrix; for new code NumPy recommends plain arrays andnp.matmul.
- NDPolyBase
NumPy's
numpy.polynomial._polybase.ABCPolyBase: a polynomial series in one of the six bases — power, Chebyshev, Legendre, Laguerre, Hermite (physicists') and HermiteE (probabilists') — with a domain mapped onto a window, and the arithmetic, calculus, evaluation, conversion and printing NumPy's series classes have. The concrete classes are NDPolynomial, NDChebyshev, NDLegendre, NDLaguerre, NDHermite and NDHermiteE.
- NDPolyClass
NumPy's class object of one numpy.polynomial series class (
Chebyshev,Polynomial, ...): the class attributes domain, window, maxpower and basis_name under NumPy's names, and the class's __name__ / __module__. Reached asNDChebyshev.Class(NumPy'sChebyshev) and as __class__ of a series (Python'sp.class): NumPy'sChebyshev.domainisNDChebyshev.Class.domain.
- NDPolyFitResult
The result of a
numpy.polynomialleast-squares fit (polyfit,chebfit,legfit,lagfit,hermfit,hermefit): the fitted coefficient array ITSELF — an NDArray, so it indexes, computes and passes to every function (chebval(x, chebfit(x, y, 3))) exactly like NumPy's ndarray — that also carries NumPy'sfull=Truestatistics.
- NDPolynomial
NumPy's
numpy.polynomial.polynomial.Polynomial: a power series:c[0] + c[1]·x + c[2]·x² + …, with a domain (default[-1, 1]) mapped onto a window (default[-1, 1]). Arithmetic (+ - * / %, __floordiv__(object), __divmod__(object), __pow__(object)), evaluation (__call__(object)), calculus (integ(int, object, object), deriv(int)), roots, fitting (fit(object, object, object, object, object, bool, object, object, string)), conversion between bases (convert(object, Type, object), cast(NDPolyBase, object, object)) and printing, all as NumPy 2.4.2 has them.
- NDScalarClassCalls
NumPy's class calls (
np.float32(1.5f),np.int8(),np.complex128(1, 2),np.str_(5)) as C# 14 static extension members of np, so each concrete scalar-class name is both a VALUE - the DType fieldnp.float32, unchanged - and a CALL that constructs NumPy's scalar. Reach them throughnp..
- NDScalarType
A NumPy scalar TYPE: one class of NumPy's
numpy.generichierarchy, or one of the Python built-in classes that hierarchy derives from, as a C# object. The ten abstract classes arenp.generic,np.number,np.integer,np.signedinteger,np.unsignedinteger,np.inexact,np.floating,np.complexfloating,np.flexibleandnp.character; every registered dtype class has one concrete class under them (numpy.float64,numpy.int8,numpy.datetime64, ...), and so do the NumPy classes NumSharp has no dtype for (numpy.complex64,numpy.object_,numpy.void). They are whatnp.issubdtype(a.dtype, np.integer),isinstance(x, np.floating)andissubclass(t, np.number)test against.
- NDScope
Ambient reclamation scope for transient NDArray intermediates — the library's standard way to make a composition method eagerly return its temporaries' pooled buffers instead of waiting on the finalizer (see
DISPOSAL-GUIDELINES.md). Every NDArray constructed on the current thread while a scope is open is tracked by it; disposing the scope disposes every tracked array that was not yielded via Returns<T>(T). Tracked disposal is ordinary ARC release (the buffer frees only at refcount 0), so releasing a base whose view was yielded never corrupts — the same safety as a hand-writtenDispose, with the bookkeeping automated.
- NDScopedAsyncAttribute
The ASYNC counterpart of NDScopedAttribute: marks an async method, an async iterator, or a non-async method returning
Task/ValueTask[<T>] as an NDScope boundary. At build time the NumSharp IL weaver (tools/NumSharp.Build, shipped to consumer projects as theNumSharp.BuildNuGet package) weaves the method's compiler STATE MACHINE — or, for a non-async Task-returning body, its DEFERRAL egress — so the NDArray temporaries it drops are reclaimed at the invocation's completion instead of waiting on the finalizer, with the source keeping its 100% original body exactly as NDScopedAttribute does for synchronous ones.
- NDScopedAttribute
Marks a method (or a property accessor) as an NDScope boundary: at build time the NumSharp IL weaver (
tools/NumSharp.Build, shipped to consumer projects as theNumSharp.BuildNuGet package) injects the exact code the hand-written pattern spells —using var scope = NDScope.Open(); ...original body, byte-for-byte... return scope.Returns(result); // NDArray-like returns— so the source keeps its 100% original body and the reclamation is invisible.
- NDScopedCoveredAttribute
Marks a method (or property accessor) as covered by an ambient NDScope opened by its caller — a
[NDScoped]OR[NDScopedAsync]boundary (or a hand-written scope) — so its NDArray temporaries are reclaimed by that caller's scope, and theNDW012leak analyzer must treat the method as covered instead of flagging its transients.
- NDScopedExitAttribute
Marks a by-value parameter as one the callee RETAINS — a reference it keeps past the call (stores in a field/property, adds to a long-lived collection, captures in a closure/task that outlives the call). At build time the NumSharp IL weaver detaches the argument from whatever NDScope tracks it, so the CALLER's scope will NOT reclaim an NDArray the callee is still holding.
- NameError
Exception that corresponds to Python/NumPy's
NameError. Raised when a name referenced by value is not defined.
- NotADirectoryError
Python's
NotADirectoryError(errnoENOTDIR, 20): a directory operation on something that is not a directory (a path that runs through a file:data.npy/x).
- NotImplementedError
Python's
NotImplementedError: an operation declared for an input it is not implemented for, or an abstract method a subclass did not override. NumSharp raises it where NumPy does, with NumPy's text: a masked array'stofile, the numpy.ma functions limited to two dimensions (compress_rows,compress_cols,compress_rowcols,mask_rowcols,notmasked_contiguous) and a seedlessSeedSequence'sgenerate_state; a port throws it where its Python source raises it (a base class'sraise NotImplementedError).
- NumPyRandom
A class that serves as numpy.random.RandomState in python. Uses MT19937 (Mersenne Twister) for NumPy-compatible random number generation by default, and any BitGenerator when constructed from one (NumPy's
RandomState(bit_generator)).
- NumPyRandom.State
NumPy's
RandomState.get_state(legacy=False)dict: the bit generator's state plus RandomState's cached Gaussian — the one state form every bit generator supports.
- OSError
NumPy-compatible
OSError: an operating-system level failure — a file that is missing or cannot be opened (raised as one of its subclasses, FileNotFoundError, PermissionError, …), and the file operations NumPy refuses itself (ndarray.tofile'scannot write object arrays to a file in binary modefor aStringDTypearray,problem writing element 3 to file). NumSharp raises it in the same places with NumPy's (and CPython's) text.
- OpenBlasMissingBackendException
A MissingBackendException whose message says how to make the operation work: reference the
NumSharp.Interop.OpenBLASNuGet package.
- OverflowError
Python's
OverflowError: a number too large for the type it must become. NumSharp raises it where NumPy and CPython do, with their text: a Python int that does not fit the target (Python integer 300 out of bounds for uint8,Python int too large to convert to C long), a float infinity converted to an integer (cannot convert float infinity to integer), an int too large for a float (int too large to convert to float), a string repeat or pad whose result cannot be sized (Overflow encountered in string multiply), and the random generators' range checks (Range exceeds valid bounds).
- PCG64
PCG64 (XSL-RR 128/64) bit generator — the default BitGenerator behind
np.random.default_rng.
- PCG64.State
The PCG64 state — NumPy's
{'bit_generator': 'PCG64', 'state': {'state': int, 'inc': int}, 'has_uint32': int, 'uinteger': int}with the nested'state'dict flattened.
- PCG64DXSM
PCG64DXSM — the 128-bit PCG with the cheap 64-bit multiplier and the stronger "double xorshift multiply" output (NumPy's
numpy.random.PCG64DXSM), recommended by NumPy for massively parallel use.
- PCG64DXSM.State
The PCG64DXSM state — NumPy's
{'bit_generator': 'PCG64DXSM', 'state': {'state': int, 'inc': int}, 'has_uint32': int, 'uinteger': int}with the nested'state'dict flattened.
- PermissionError
Python's
PermissionError(errnoEACCES13,EPERM1): an operation the operating system denies. NumSharp's file functions raise it as CPython'sopen()does: a read-only or locked file opened for writing, a file another process holds without sharing, and on Windows a directory opened as a file ([Errno 13] Permission denied: 'data').
- Philox
The Philox 4x64-10 counter-based bit generator (NumPy's
numpy.random.Philox): a 256-bit counter encrypted under a 128-bit key by ten Feistel-like rounds, so any stream position — and any of 2**128 keyed streams — is directly addressable.
- Philox.State
The Philox state — NumPy's
{'bit_generator': 'Philox', 'state': {'counter': uint64[4], 'key': uint64[2]}, 'buffer': uint64[4], 'buffer_pos': int, 'has_uint32': int, 'uinteger': int}with the nested'state'dict flattened.
- PolyUtilsModule
numpy.polynomial.polyutils— the helpers the six basis modules are built on, reachable asnp.polynomial.polyutils: series normalization (as_series(object, bool), trimseq(NDArray), trimcoef(object, double)), the linear domain maps (getdomain(object), mapparms(object, object), mapdomain(NDArray, object, object)) and the coefficient formatter of the series classes (format_float(object, bool)).
- PolynomialModule
The
numpy.polynomialpackage facade, reachable as polynomial. Its members are the six basis submodules; each is a first-class object, so Python'simport … as Pbecomesvar P = np.polynomial.polynomial;. (A nested static class cannot model this: C# forbids a member namedpolynomialinside a type of that name.)
- PowerSeriesModule
numpy.polynomial.polynomial— power seriesp(x) = c[0] + c[1]*x + … + c[n]*x**n, reachable asnp.polynomial.polynomial. Coefficients are LOW degree first.
- ProcessLookupError
Python's
ProcessLookupError(errnoESRCH, 3): a process that does not exist (os.killof a finished process).
- PyScalarDTypeMeta
NumPy's abstract DType classes for Python scalars —
numpy.dtypes._PyLongDType,_PyFloatDType,_PyComplexDType(abstractdtypes.c). They are how NEP 50 "weak" promotion works: a literal contributes only its abstract CLASS toresult_type(no descriptor, so no value or width), and the class's common_dtype(DTypeMeta) lets the other operand's dtype win within its kind (int8 + 300 → int8,float32 + 1e300 → float32) while still lifting across kinds (int8 + 1.5 → float64). A literal that survives alone falls back to the class default (int64/float64/complex128).
- RecursionError
Python's
RecursionError: the interpreter's recursion limit was exceeded (maximum recursion depth exceeded).
- ReferenceError
Python's
ReferenceError: a weak-reference proxy was used after its referent was collected (weakly-referenced object no longer exists).
- RuntimeError
Exception that corresponds to Python/NumPy's RuntimeError. Raised when an error is detected that does not fall into any of the other categories.
- SFC64
Chris Doty-Humphrey's Small Fast Chaotic PRNG (NumPy's
numpy.random.SFC64): four 64-bit words of state, one of them a counter that guarantees a minimum period of 2**64 per seed.
- SFC64.State
The SFC64 state — NumPy's
{'bit_generator': 'SFC64', 'state': {'state': uint64[4]}, 'has_uint32': int, 'uinteger': int}with the nested'state'dict flattened.
- SeedSequence
Mixes sources of entropy into a high-quality initial state for a bit generator, and spawns independent children for parallel streams (NumPy's
numpy.random.SeedSequence).
- SeedlessSeedSequence
A seed sequence for bit generators that need no seed state (NumPy's
numpy.random.bit_generator.SeedlessSeedSequence).
- Slice
NDArray can be indexed using slicing
A slice is constructed by start:stop:step notation
Examples:
a[start:stop] # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-1
The key point to remember is that the :stop value represents the first value that is not
in the selected slice. So, the difference between stop and start is the number of elements
selected (if step is 1, the default).
There is also the step value, which can be used with any of the above:
a[:] # a copy of the whole array
a[start:stop:step] # start through not past stop, by step
The other feature is that start or stop may be a negative number, which means it counts
from the end of the array instead of the beginning. So:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
Similarly, step may be a negative number:
a[::- 1] # all items in the array, reversed
a[1::- 1] # the first two items, reversed
a[:-3:-1] # the last two items, reversed
a[-3::- 1] # everything except the last two items, reversed
NumSharp is kind to the programmer if there are fewer items than
you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an
empty list instead of an error.Sometimes you would prefer the error, so you have to be aware
that this may happen.
Adapted from Greg Hewgill's answer on Stackoverflow: https://stackoverflow.com/questions/509211/understanding-slice-notation
Note: special IsIndex == true
It will pick only a single value at Start in this dimension effectively reducing the Shape of the sliced matrix by 1 dimension.
It can be used to reduce an N-dimensional array/matrix to a (N-1)-dimensional array/matrix
Example:
a=[[1, 2], [3, 4]]
a[:, 1] returns the second column of that 2x2 matrix as a 1-D vector
- StopAsyncIteration
Python's
StopAsyncIteration: an asynchronous iterator (anext) has no more items.
- StopIteration
Python's
StopIteration: an iterator has no more items. A generator'sreturn valuetravels in it as value, which is how Python'syield fromreceives a sub-generator's result.
- StringComputationNotSupportedException
A computation on text that
np.evaluatedoes not run: anNDExprnode that takes anS,UorStringDTypeoperand where NumPy's answer is not a number or a bool (a text result such as a concatenation or aWherewith text branches, a reduction of text other than the truth tests, an arithmetic or math node), or a text argument to anNDExpr.Calldelegate.np.evaluateis a NumSharp extension without a NumPy function to follow; it computes text in the comparisons, the truth readers (the logical nodes,Where's condition,Any/All/CountNonzero),IsNaN,Castto a number and the numpy.strings factories (StrLen, the predicates, the searches), whose numeric results feed the rest of the tree, and the message names the refused node and how to compute it (the string functions first, their result passed into the expression).
- StringDTypeMeta
NumPy's two fixed-width string DType classes —
numpy.dtypes.BytesDType(kind'S', type number 18, one byte per character, NumPy'snp.bytes_) andnumpy.dtypes.StrDType(kind'U', type number 19, one UCS-4 code point = 4 bytes per character, NumPy'snp.str_). Both are PARAMETRIC: the length lives on the descriptor (S5→itemsize5,U5→ 20), so promotion runs common_instance(DType, DType) (the longer string wins) and every cast resolves the destination length (ToStringCastingImpl, StringToStringCastingImpl).
- StringToDatetimeCastingImpl
The cast from a string class into
datetime64— NumPy'sstring_to_datetime_cast_resolve_descriptors: alwaysunsafe; a missing destination is the generic unit (which NumPy notes "doesn't actually work, and will error during the cast"). Descriptor level only until Stage C.
- StringToStringCastingImpl
The cast between two descriptors of ONE string class (
S → SorU → U) — NumPy'sstring_to_string_cast(convert_datatype.c,string_to_string_resolve_descriptors): a longer destination issafe(zero padding, never a view), a shorter onesame_kind(truncation; a view at offset 0 when the byte order matches), an equal one a no-op view (no) or aUbyte swap (equiv).
- SyntaxError
Exception that corresponds to Python's
SyntaxError: text that is not valid Python source. Catch it where a string argument is parsed as Python literals and the caller wants to tell malformed text from a well-formed value that is merely not allowed (that one is a ValueError).
- SystemError
NumPy-compatible
SystemError— Python's "the interpreter found an internal inconsistency" error. NumPy raises it when an operation meets data that no Python object can represent, and NumSharp raises it in the same places with CPython's verbatim text.
- SystemExit
Python's
SystemExit:sys.exit(code), a request to end the program with an exit status (code).
- TabError
Python's
TabError: indentation that mixes tabs and spaces inconsistently (inconsistent use of tabs and spaces in indentation).
- TensorEngine
The matrix products beyond
dot/matmul-inner,vdot,vecdot,matvec,vecmat- NumPy's C core: each asks Blas first and falls back to NumSharp's managed kernels, so a backend changes which implementation runs and never whether an answer exists.
- TensorEngine.Threading
Process-wide threading configuration — one named, environment-variable-backed knob per threading domain (NumSharp's own kernels, and the native BLAS / OpenMP runtimes NumPy and the rest of the ecosystem thread through: OpenBLAS, MKL, BLIS, NumExpr, vecLib). It is the single surface for reading and setting them, and it is extensible per module: a module registers (or upgrades) its own knob via Register(string, string, Func<int?>, Action<int?>) — that is how
NumSharp.Interop.OpenBLASattaches a native applier to the OpenBlas knob so a change reaches the loaded library, and how any future backend adds its own.
- TensorEngine.Threading.Variable
One threading knob: a logical name, an optional backing environment variable, and the module hooks that read and apply its value. Read-only from outside; mutated only through TensorEngine.Threading.
- TimeToStringCastingImpl
The cast from
datetime64/timedelta64into a string class — NumPy'stime_to_string_resolve_descriptors(datetime.c): alwaysunsafe; a missing destination is the ISO 8601 width of the unit fordatetime64(NpyDatetime_GetDatetimeISO8601StrLen) and 21 characters fortimedelta64.
- TimeToTimeCastingImpl
The within-class cast of
datetime64/timedelta64— a unit conversion. Port of NumPy'stime_to_time_resolve_descriptors(datetime.c): identical metadata (or an exact 10³ᵏ metric-prefix fold such as[1000ms] → [s]) is a no-op view /equivbyte swap; a generic source issafe; a generic destination or, for timedelta, a jump across the years-months barrier isunsafe; towards a finer unit that divides exactly issafe, anything elsesame_kind.
- TimeoutError
Python's
TimeoutError(errnoETIMEDOUT): a system-level timeout (a socket operation, a lock).
- ToStringCastingImpl
A cast INTO a string class from any other non-datetime class — a numeric class, or the other string class — NumPy's
legacy_cast_to_string(add_other_to_and_from_string_cast+cast_to_string_resolve_descriptors). Its class-level safety issame_kind("safe when the destination is long enough") for every source butU, andunsafeforU → S(a code point above 127 cannot be stored in a byte string).
- TooHardError
Exception that corresponds to NumPy's
numpy.exceptions.TooHardError— raised by shares_memory(NDArray, NDArray, long) when the bounded memory-overlap search exhausts itsmax_workcandidate budget before it can decide the question exactly.
- TypeError
Exception that corresponds to Python/NumPy's TypeError. Raised when an operation or function receives an argument of inappropriate type.
- UFuncBinaryResolutionError
NumPy's
_UFuncBinaryResolutionError: a binary ufunc whose two operand dtypes cannot be combined (ufunc 'add' cannot use operands with types dtype('S1') and dtype('<U1')).
- UFuncCastingError
NumPy's
_UFuncCastingError: the base of the casting refusals, a cast between an operand and the loop's dtype that thecasting=rule forbids. NumPy raises only its two subclasses, UFuncInputCastingError and UFuncOutputCastingError.
- UFuncInputCastingError
NumPy's
_UFuncInputCastingError: an input cannot be cast to the loop's dtype under thecasting=rule (Cannot cast ufunc 'add' input 0 from dtype('float64') to dtype('int64') with casting rule 'safe').
- UFuncNoLoopError
NumPy's
_UFuncNoLoopError: a ufunc has no loop for its operands' dtypes. Its text is NumPy'sufunc 'add' did not contain a loop with signature matching types (dtype('<U1'), dtype('int64')) -> None: the input dtypes, then the output ones, each a lone value or a tuple.
- UFuncOutputCastingError
NumPy's
_UFuncOutputCastingError: the loop's result cannot be cast to an output (out=) under thecasting=rule (Cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind').
- UFuncTypeError
NumPy's
numpy._core._exceptions.UFuncTypeError: the base of the errors a ufunc raises when it cannot run for its operands' dtypes — no loop for them (UFuncNoLoopError), two operands it cannot combine (UFuncBinaryResolutionError), or a cast itscasting=rule forbids (UFuncInputCastingError, UFuncOutputCastingError).
- UnboundLocalError
Python's
UnboundLocalError: a local variable read before any value was bound to it (cannot access local variable 'x' where it is not associated with a value).
- UnicodeDecodeError
NumPy-compatible
UnicodeDecodeError: bytes that the source encoding cannot read. NumSharp raises it where NumPy's codecs do — anS(byte-string) value holding a byte at or above0x80stored into aUarray, cast toU, or given tonp.array(…, dtype='U'), every codec ofnp.strings.decode, and text that is not UTF-8 where NumPy reads UTF-8.
- UnicodeEncodeError
NumPy-compatible
UnicodeEncodeError: a Unicode string held a character the target encoding cannot represent. NumSharp raises it where NumPy's codecs do — aUorStringDTypevalue with a code point at or above 128 stored into anS(byte-string) array, cast toS, or given tonp.array(…, dtype='S'), and every codec ofnp.strings.encode.
- UnicodeError
NumPy-compatible
UnicodeError— Python's base class for text encoding and decoding failures, a subclass of ValueError. NumSharp raises its two concrete subclasses, UnicodeEncodeError and UnicodeDecodeError, when a value crosses between a fixed-width Unicode (U) and a byte-string (S) dtype the way NumPy's ASCII codec refuses it.
- UnicodeTranslateError
Python's
UnicodeTranslateError: a characterstr.translate-style mapping could not translate (can't translate character '\xe9' in position 1: reason).
- VStringDTypeMeta
NumPy's NEP 55 variable-width string DType class,
numpy.dtypes.StringDType(kind and char'T', type number 2056): every element is a 16-byte cell that holds a short UTF-8 string inline or points into an arena / heap the array owns, so one array can hold strings of any length without padding them all to the longest.
- VStringToFixedWidthCastingImpl
NumPy's casts from
StringDTypeto the fixed-width string classes (string_to_fixed_width_resolve_descriptors):same_kind, and only to a SIZED destination — there is no way to know the width the strings need.
- VStringToNumberCastingImpl
NumPy's casts from
StringDTypeto numbers, bool and the datetime pair (string_to_int / _float / _bool / _datetime_timedelta_resolve_descriptors): the destination is the given descriptor or the class default, and the resolved safety is alwaysunsafe(parsing can fail or lose a missing value).
- VStringToVStringCastingImpl
NumPy's
StringDType → StringDTypecast (string_to_string_resolve_descriptorsinstringdtype/casts.cpp): no casting at all between descriptors, except from a descriptor WITH a missing-data object to one WITHOUT, which is UNSAFE (the missing values have nowhere to go).
- ValueError
NumPy-compatible ValueError exception. Raised when an operation receives an argument with the right type but inappropriate value.
- Vectorized
A reusable vectorized wrapper around a C# delegate — the object vectorize(Delegate, DType[]) and frompyfunc(Delegate, int, int) return, mirroring NumPy's
vectorizeclass. Build it once and call it many times: an element-wise instance re-uses one compiled fused kernel across calls (the delegate identity is stable, so evaluate(NDExpr, NDArray[], NDArray, NDArray, DType, string, char)'s structural cache reuses it), so repeated invocation is cheap.
- ZeroDivisionError
Python's
ZeroDivisionError: a division or modulo whose divisor is zero, raised where Python's scalar arithmetic raises it. NumSharp raises it where NumPy does:np.averageover weights that sum to zero (Weights sum to zero, can't be normalized),np.fft.fftfreqwithd=0(float division by zero), the object-dtype and polynomial paths that compute with Python scalars (division by zero,integer division or modulo by zero,complex division by zero).
- finfo
Machine limits for floating point types.
- iinfo
Machine limits for integer types.
- np
API bridge between NumSharp and Python NumPy
- np.AxisConcatenator
Translates slice expressions to concatenation along an axis — the machinery shared by r_ and c_.
- np.Broadcast
NumPy's
numpy.broadcast— the broadcast result of N operands, usable as an iterator. Like NumPy, the object is its OWN iterator (iter(b) is b): it keeps a single live cursor exposed as index, iterating it yields one tuple of per-operand values per step (advancing the cursor), and reset() rewinds it.
- np.CClass
Translates slice expressions to concatenation along the SECOND axis.
- np.FlatIterator
A flat, C-order iterator over an NDArray — the NumSharp analog of NumPy's
flatiter(the type ofndarray.flat), obtained from flatiter or flat(NDArray).Unlike NumSharp's flat (a raveled NDArray that materializes a COPY for a non-contiguous array, so writes through it are lost), this iterator always reads AND writes THROUGH to the base array in logical C-order, whatever the memory layout — matching NumPy's
a.flat[i] = vsemantics for transposed, sliced, strided, negative-stride and broadcast layouts alike. Every element access maps a flat C-order index to the base's coordinate and goes through the base's stride-aware element accessors, so no per-dtype branching and no buffer materialization occur.Surface (probed against NumPy 2.4.2): this[long] single-element get (a 0-d write-through view, NumSharp's scalar analog) / set; fancy (
int[]/long[]/ NDArray) and slice-string ("1:4","::2") get/set; the index / coords cursor, Base, size, copy() (a fresh 1-D C-order array), and C-order iteration that shares the cursor (so a second pass RESUMES, as NumPy'siter(f) is f).Scalar assignment matches NumPy's weak-scalar bounds check: an OUT-OF-RANGE C# primitive (NumSharp's NEP50 analog of a Python int/float) written to an integer element RAISES (
OverflowException, "Python integer 300 out of bounds for int8") rather than wrapping, the truncate-then-check rule for floats included (127.9stores 127,128.0raises, NaN/inf raise). A STRONG scalar — an NDArray, reached through the fancy/slice setters ora.astype— still wraps, exactly as in NumPy (which range-checks a Python int but wraps annp.int64scalar).One documented divergence remains (
[Misaligned]): coords read at the EXHAUSTED position (index == size, after a full pass) on a truly non-contiguous array is implementation-defined — NumSharp returns the arithmetic continuation, NumPy an internal odometer artifact; every IN-RANGE coord (the values read during iteration) is bit-exact.
- np.IndexExpression
A nicer way to build up index tuples for arrays — the type behind s_ and index_exp. Use those two instances rather than constructing this directly.
- np.MGridClass
An instance which returns a dense ("fleshed out") multi-dimensional "meshgrid" when indexed, so that every returned axis-grid has the SAME shape. The number of stacked grids and their dimensionality equal the number of indexing slices. If the step length is not a complex number, the stop is NOT inclusive; a complex step (e.g.
"…:5j") instead specifies the number of points, with the stop INCLUSIVE: pointiisi * step + startwithstep = (stop - start) / (N - 1), as NumPy computes it (so the last point can miss the stop by a rounding:np.mgrid["0.3:0.9:7j"]ends at 0.9000000000000001, wherelinspaceputs it on 0.9).
- np.MemoryView
The NumSharp analog of Python's
memoryview— the buffer object returned by data. It is a lightweight, zero-copy HANDLE onto an array's raw memory plus the layout metadata needed to interpret it (NumPy'sndarray.datais literallymemoryview(self)).It owns no memory of its own: every member reads LIVE through the source array's Storage and Shape, so it stays valid while the source array (held as obj, keeping it alive exactly as NumPy's
memoryview.objdoes) is alive and not structurally mutated. The Pointer addresses the LOGICAL first element (base + offset·itemsize), matching NumPy'sa.data/PyArray_DATA/a.ctypes.data/a.__array_interface__['data'][0]— for a sliced or reversed view this is the offset element, not the buffer base.Surface (probed against NumPy 2.4.2's
memoryview): obj, nbytes, itemsize, ndim, readonly (true for broadcast / non-writeable views), shape, strides (in BYTES like NumPy's — NumSharp's own strides are in elements), format (the struct-module type code), c_contiguous / f_contiguous / contiguous, Length (NumPy'slen(mv)), tobytes(string) / hex(), the raw Pointer / Address, and write-through scalar element access via this[long[]].Deliberately NOT modelled (documented boundaries, not gaps to close): partial-index sub-views (
mv[1]on an N-D memoryview yields a sub-memoryviewin Python — use the NDArray indexer for sub-arrays),cast,tolist,release/ the context-manager protocol, and element iteration. NumSharp has no Python buffer protocol, so these Python-object conveniences have no counterpart; the buffer ESSENCE (pointer + metadata + write-through +tobytes) is whatndarray.datais for.
- np.NDEnumerate
NumPy's
numpy.ndenumerate— walks an array in C-order, yielding(index, value)for every element.// numpy: list(np.ndenumerate(np.array([[1, 2], [3, 4]]))) // -> [((0,0), 1), ((0,1), 2), ((1,0), 3), ((1,1), 4)] foreach (var (index, value) in np.ndenumerate(a)) { … }Like NumPy the object is its OWN iterator (
iter(e) is e): it keeps a single live cursor, so a second enumeration resumes where the first stopped.
- np.NDEnumerate<T>
Typed np.NDEnumerate — identical traversal, but reads elements as
Twithout boxing. See ndenumerate<T>(NDArray).
- np.NDIndex
NumPy's
numpy.ndindex— a C-order odometer over the index space of a shape, yielding one index array per step with the LAST dimension varying fastest.// numpy: list(np.ndindex(3, 2)) -> [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)] foreach (var idx in np.ndindex(3, 2)) { /* idx = {0,0}, {0,1}, {1,0}, ... */ }Like NumPy the object is its OWN iterator (
iter(i) is i): it keeps a single live cursor, so a second enumeration resumes where the first stopped rather than restarting — the same contract np.Broadcast follows.
- np.NDIterator
NumPy's
numpy.nditer— the public, managed face of NumSharp's NDIterRef.// numpy: for x in np.nditer(a): total += x foreach (var vals in np.nditer(a)) total += (int)vals[0]; // numpy: it = np.nditer(a, flags=['multi_index']) // while not it.finished: print(it.multi_index, it[0]); it.iternext() var it = np.nditer(a, flags: new[] {"multi_index"}); while (!it.finished) { Use(it.multi_index, it[0]); it.iternext(); }
- np.OGridClass
An instance which returns an open multi-dimensional "meshgrid" when indexed, so that only one dimension of each returned array is greater than 1. The number and dimensionality of the outputs equal the number of indexing slices. If the step length is not a complex number, the stop is NOT inclusive; a complex step (e.g.
"…:5j") instead specifies the number of points, with the stop INCLUSIVE: pointiisi * step + startwithstep = (stop - start) / (N - 1), as NumPy computes it (notlinspace, which forces the last point onto the stop).
- np.RClass
Translates slice expressions to concatenation along the FIRST axis. Two use cases: comma-separated arrays are stacked along axis 0, and slice notation or scalars build a 1-D array.
- np.dtypes
numpy.dtypes(NEP 56 / NumPy 1.25+): the DType CLASSES —np.dtypes.Float64DTypeistype(np.dtype('f8')). Each member is the live DTypeMeta singleton; its Instantiate() is NumPy's class call (Int8DType()→dtype('int8');DateTime64DType()raises the "Preliminary-API … can only be instantiated usingnp.dtype(...)" TypeError), and Meta istype(dtype).
- np.lib
NumPy's
numpy.libpackage: a namespace for its public submodules (np.lib.stride_tricks). It holds no functions of its own here.
- np.lib.array_utils
NumPy's
numpy.lib.array_utils(NumPy 2.0's public home of three helpers that lived innumpy.lib.utils/numpy.core.multiarray): byte_bounds(NDArray), normalize_axis_index(int, int, string) and normalize_axis_tuple(NDAxis, int, string, bool), over the same statements every NumSharp axis-taking function runs (Shape's axis checks), so their texts are NumPy's.
- np.lib.format
NumPy's
numpy.lib.format: the public face of the.npyformat - the magic string, the header dictionary, the header readers and writers, and whole-array reads and writes - with NumPy's names over NumSharp's NpyFormat, which np.save / np.load already run (so the bytes are the ones those write and read).
- np.lib.stride_tricks
NumPy's
numpy.lib.stride_tricks: views that re-read an array's memory with other strides. sliding_window_view(NDArray, Shape, NDAxis?, bool) is the safe one (every window lies inside the array); as_strided(NDArray, Shape?, long[], bool, bool) takes any shape and byte strides, and where NumPy reads whatever memory they reach, NumSharp refuses a view that leaves the array's buffer (the bounds-checked form the owner approved in API-parity batch 12).
- np.linalg
NumPy's
numpy.linalgmodule.
- np.strings
NumPy's
numpy.stringsmodule: elementwise comparisons, concatenation, repetition, search, stripping, padding, replacement, slicing, Unicode properties, case conversion, formatting and codecs over fixed-widthS/Uand variable-widthStringDTypetext. Arguments broadcast; each operation determines its result width and handling of missing values.
- np.typing
numpy.typing— NumPy's static-typing aliases (NDArray,ArrayLike,DTypeLike,NBitBase), each as the C# type that plays its role in NumSharp's own signatures.
- np.typing.NBitBase
numpy.typing.NBitBase: the base of the precision markers NumPy's stubs parametrize its scalar classes with (np.floating[npt.NBitBase]), used only by static type checkers. Deprecated in NumPy 2.3 (accessing it warns, as using this class does) and without a use in C#, which has no precision-generic scalar classes; it exists so a ported reference compiles and says why it should go.
- poly1d
A one-dimensional polynomial class — the NumSharp port of
numpy.poly1d. Encapsulates a coefficient vector (highest power first) and the natural polynomial operations.C# has no call syntax, so NumPy's
p(x)evaluation is spellednp.polyval(p, x); the indexerp[k]retrieves the coefficient ofx**kexactly like NumPy. NumPy'sp ** n(polynomial power) has no**operator in C# — spell it with repeated multiplication (p * p * p), which NumPy defines it to equal. ToString() renders NumPy'sreprform (poly1d([...])); NumPy's separate prettystr()form is not reproduced (C# has a singleToString).
Structs
- Char8
Represents a single byte as a character. Equivalent to NumPy's
dtype('S1')/numpy.bytes_of length 1, and to a Pythonbytesobject of length 1. Interoperable with byte, char (via Latin-1), and string (via ASCII/Latin-1 encoding).
- DateTime64
A 64-bit signed tick count representing a date/time value with full
longrange and a NaT sentinel, matching NumPy'snp.datetime64semantics. Used as a conversion-helper type in Converts.
- DatetimeMetaData
The per-INSTANCE parameter of a
datetime64/timedelta64descriptor — NumPy'sPyArray_DatetimeMetaData({ NPY_DATETIMEUNIT base; int num; }): the unit and an integer multiplier, sodatetime64[5m]counts five-minute ticks. This is what makes the datetime pair PARAMETRIC:M8[ns]andM8[s]share one DTypeMeta and one 8-byte storage but are different dtypes, and promotion / casting between units is arithmetic on these two fields.
- EinsumPath
The contraction path returned by einsum_path(string, NDArray[]) — NumPy's
['einsum_path', (1, 2), (0, 1)]list expressed as a value.
- MaskedArrayModule.AverageResult
The result of average(object, int?, object, bool, bool) - NumPy's bare-masked-average-OR-tuple return as one type: the masked average (values, typed NDMaskedArray), plus sum_of_weights when
returnedwas set (null otherwise). It converts implicitly to NDMaskedArray and deconstructs:var (avg, sum_of_weights) = np.ma.average(a, returned: true);.
- MaskedArrayModule.UniqueResult
The result of unique(object, bool, bool): NumPy's bare masked array (no flag) or its
(MaskedArray, ndarray[, ndarray])tuple (a flag), as one type. It converts implicitly to NDMaskedArray (the values), deconstructs into the present outputs, indexes them in NumPy's order, and forwards the masked array's members (data, mask, fill_value, hardmask, shape, dtype, size) to its values, so a flag-less result reads like the masked array it stands for.
- NDAxis
NumPy's
axisargument as one C# type: a single axis (axis=1) or a tuple of axes (axis=(0, 2),axis=(1,),axis=()). A function whose NumPy default isaxis=NonetakesNDAxis? axis = null, sonullis NumPy'sNone, and the four spellings below convert implicitly:np.all(a, 1); // axis=1 np.all(a, (0, 2)); // axis=(0, 2) - a C# tuple of two or three ints np.all(a, new[] { 0, 2 }); // axis=(0, 2) - an int[]: NumPy's tuple of any length, () included np.all(a, null); // axis=None - the default np.all(a, new NDAxis(0, 2)); // axis=(0, 2) - the constructors build the same values explicitlyThe value only HOLDS the axes, exactly as given: negative axes stay negative and nothing is range-checked until the function that receives it normalizes them against its operand (Normalize(int, string, bool)), so the error texts are the ones NumPy's function raises.
- NativeRandomState
Represents the stored state of MT19937 random number generator. This format is compatible with NumPy's random state.
- PolyfitResult
The polymorphic return of polyfit(NDArray, NDArray, int, double?, bool, NDArray, object). Converts implicitly to the coefficient array (the bare-return case); deconstructs to NumPy's
fullfive-tuple(coeffs, residuals, rank, singular_values, rcond)or thecovtwo-tuple(coeffs, covariance).
- Shape
Broadcasting operations for Shape.
- Shape.Enumerator
The dimension enumerator GetEnumerator() returns: a cursor over the shape's own dimension array.
- np.AverageResult
The result of <xref href="NumSharp.np.average(NumSharp.NDArray%2cSystem.Nullable%7bNumSharp.NDAxis%7d%2cNumSharp.NDArray%2cSystem.Boolean%2cSystem.Boolean)" data-throw-if-not-resolved="false"></xref> — NumPy's bare-average-OR-tuple return expressed as one type (np.unique's <xref href="NumSharp.np.UniqueResult" data-throw-if-not-resolved="false"></xref> pattern): the average (<xref href="NumSharp.np.AverageResult.values" data-throw-if-not-resolved="false"></xref>), plus <xref href="NumSharp.np.AverageResult.sum_of_weights" data-throw-if-not-resolved="false"></xref> when <code>returned</code> was set (null otherwise).It stands in for both NumPy return shapes: it converts implicitly to NDArray (the bare form:
NDArray avg = np.average(a);) and to NDArray[](the present outputs), and deconstructs:var (avg, sum_of_weights) = np.average(a, returned: true);.
- np.FlatRefIter<T>
The
foreach-able returned by flat<T>(NDArray, bool) and AsTyped<T>(bool) — the typed, unboxed, by-reference flat iterator. Yieldsref Tin logical C-order (matching flatiter), write-through for every memory layout.It is exactly a C-order np.NDRefIter<T>. This type reuses np.NDRefIter<T>.Enumerator verbatim — the same NDIterRef cursor that
np.nditer<T>drives — pinned toNPY_CORDER. It exists as its own type only so the flat contract (always C-order, never memory order) is stated in the type rather than left to a parameter default; there is no separate iteration logic. Everything documented on np.NDRefIter<T> — why the enumerator is aref struct, that this value holds no unmanaged state while the enumerator does, thatforeachdisposes it and re-enumeration restarts — applies identically.
- np.GradientResult
The result of gradient(NDArray, object, NDAxis?, int): NumPy returns a single ndarray when the gradient is taken along ONE axis and a tuple of ndarrays (one per axis) otherwise. C# cannot pick a return type from a runtime count, so this value stands in for both — it converts implicitly to NDArray (valid only for the single-axis result), to NDArray
[](always),Deconstructs (var (gy, gx) = np.gradient(a);) and indexes ([k]).
- np.Histogram2dResult
The bi-dimensional histogram plus its two edge arrays — the three values NumPy's
histogram2dreturns. Converts implicitly to NDArray (the histogramH) and deconstructs asvar (H, xedges, yedges) = np.histogram2d(x, y);.
- np.HistogramResult
The two arrays NumPy's
histogramreturns: the per-bin values and the bin edges. Converts implicitly to NDArray (the histogram values — the primary result) and to NDArray[]([hist, bin_edges]), and deconstructs asvar (hist, edges) = np.histogram(a);so ported NumPy call shapes read verbatim.
- np.HistogramddResult
The multidimensional histogram plus its per-dimension bin edges — the two values NumPy's
histogramddreturns. Converts implicitly to NDArray (the histogramH, always float64) and deconstructs asvar (H, edges) = np.histogramdd(sample);.
- np.IndicesResult
The result of <xref href="NumSharp.np.indices(NumSharp.Shape%2cNumSharp.DType%2cSystem.Boolean)" data-throw-if-not-resolved="false"></xref> — NumPy's dense grid OR sparse tuple as one type (np.unique's <xref href="NumSharp.np.UniqueResult" data-throw-if-not-resolved="false"></xref> pattern). Dense: <xref href="NumSharp.np.IndicesResult.values" data-throw-if-not-resolved="false"></xref> is the grid of shape <code>(len(dimensions), *dimensions)</code>; sparse: <xref href="NumSharp.np.IndicesResult.values" data-throw-if-not-resolved="false"></xref> is null and the result holds one broadcast-shaped array per axis.Both read like NumPy's: it indexes and deconstructs per axis (
var (i, j) = np.indices((2, 3));works for either form, as Python's tuple unpacking iterates a dense grid's first axis), converts implicitly to NDArray[](the per-axis arrays), and a dense result converts implicitly to the grid's NDArray.
- np.Intersect1dResult
The result of <xref href="NumSharp.np.intersect1d(NumSharp.NDArray%2cNumSharp.NDArray%2cSystem.Boolean%2cSystem.Boolean)" data-throw-if-not-resolved="false"></xref> — NumPy's bare-array-OR-tuple return expressed as one type (np.unique's <xref href="NumSharp.np.UniqueResult" data-throw-if-not-resolved="false"></xref> pattern): the sorted common <xref href="NumSharp.np.Intersect1dResult.values" data-throw-if-not-resolved="false"></xref>, plus <xref href="NumSharp.np.Intersect1dResult.comm1" data-throw-if-not-resolved="false"></xref> / <xref href="NumSharp.np.Intersect1dResult.comm2" data-throw-if-not-resolved="false"></xref> when <code>return_indices</code> was set (null otherwise).It stands in for both NumPy return shapes: it converts implicitly to NDArray (the bare form, the values:
NDArray v = np.intersect1d(a, b);) and implicitly to NDArray[](the tuple form, the present outputs in NumPy's order), indexes the outputs ([1]is comm1), and deconstructs:var (values, comm1, comm2) = np.intersect1d(a, b, return_indices: true);.
- np.LinspaceResult
The result of linspace(object, object, long, bool, bool, DType, int, string): NumPy's
samples-or-(samples, step)return as one type. It converts implicitly to NDArray (the samples:NDArray y = np.linspace(a, b, 5, retstep: false);) and deconstructs into both (var (y, step) = np.linspace(0, 1, 5, retstep: true);).
- np.MGridResult
The result of an mgrid index expression: a dense mesh — one array. NumPy's
mgridis a singlendarray(a 1-D array for one slice; a stacked(N, *sizes)array for several), and the idiomX, Y = np.mgrid[…]works by iterating that array's first axis. This value carries the array and reproduces both spellings: it converts implicitly to the bare NDArray, and itDeconstructs (var (x, y) = np.mgrid["0:5", "0:3"];) or indexes ([k]) into the per-axis grids along that first axis.
- np.MeshgridResult
The result of meshgrid(NDArray[], string, bool, bool): a tuple of N coordinate grids (NumPy returns a Python tuple). C# cannot return a variadic tuple, so this value stands in for it — it converts implicitly to NDArray
[],Deconstructs (var (xx, yy) = np.meshgrid(x, y);) and indexes ([k]).
- np.NDChunkIter<T>
The
foreach-able returned by nditer_chunks<T>(NDArray, bool, char). See np.NDRefIter<T> for theref struct, disposal, re-enumeration and iteration-order rationale, which apply identically.The yielded Span<T> points straight at the operand, so writes go through and the span is invalidated by the next step.
- np.NDChunkIter<T>.Enumerator
The cursor — one Span<T> per inner loop.
- np.NDEnumerateRef<T>
The
foreach-able returned by AsRef(bool) — the typed, allocation-free, by-ref Tndenumerate. Yields, per element, a np.NDEnumerateRef<T>.Entry carrying the coordinate (a ReadOnlySpan<T> over a reused buffer) and the value BY REFERENCE, in logical C-order (matching ndenumerate(NDArray)), write-through for every memory layout.It composes two things that are already correct: the value
refcomes from np.NDRefIter<T>.Enumerator pinned to C-order (the same engine flat<T>(NDArray, bool) drives), and the coordinate comes from a C-order odometer advanced in lockstep — since a C-order walk visits logical positions0, 1, …, size-1, the k-th value and the k-th unravelled coordinate always line up. Everything documented on np.NDRefIter<T> about theref structenumerator, disposal underforeach, and restart-on-re-enumeration applies.
- np.NDEnumerateRef<T>.Entry
One enumerated element: its coordinate and its value by reference.
- np.NDEnumerateRef<T>.Enumerator
The cursor — pairs the C-order value
refwith a lockstep coordinate odometer.
- np.NDIndexSpans
The
foreach-able returned by AsSpans() — the allocation-free odometer. Yields the current multi-index as a ReadOnlySpan<T> over a buffer REUSED each step (C-order, last axis fastest — identical order to np.NDIndex), so an entire index-space walk allocates nothing per step.Re-enumeration RESTARTS (each
foreachbuilds a fresh enumerator with its own buffer) — deliberately unlike np.NDIndex, which is its own iterator (NumPy'siter(i) is i) and resumes. Copy the span (.ToArray()) to keep an index past the current iteration; storing the span itself, or the whole enumeration, is a use-after-overwrite.
- np.NDIndexSpans.Enumerator
The cursor — one ReadOnlySpan<T> (over a reused buffer) per step.
- np.NDRefIter<T>
The
foreach-able returned by nditer<T>(NDArray, bool, char).Why a
ref structenumerator. C#'sforeachis pattern-based — it needs onlyGetEnumerator/MoveNext/Current, no interface — so an enumerator exposingref T Currentgivesforeach (ref T x in …)with no allocation, no boxing and no interface dispatch. Being aref structalso makes the compiler enforce what this API needs anyway: neither the enumerator nor therefit hands out can escape to a field, a lambda or anasyncframe.This type holds no unmanaged state; the ENUMERATOR does. Each GetEnumerator() builds a fresh NDIterRef, which
foreachthen disposes through the same pattern (noIDisposablerequired). That is why this value is safe to keep and re-enumerate, and why every pass starts from the beginning — deliberately UNLIKE the class-based np.NDIterator, which is its own iterator (NumPy'siter(x) is x) and therefore resumes. ReturningthisfromGetEnumerator— the np.Broadcast pattern — would be a use-after-free here: the firstforeachfrees the state that the second would then walk.Order is
'K', i.e. MEMORY order — not logical C-order. This matchesnp.nditerexactly (probed against NumPy 2.4.2: a reversed viewa[:, ::-1]ofarange(6).reshape(2,3)yields0 1 2 3 4 5under the default order in BOTH libraries, and2 1 0 5 4 3underorder='C'). It is also what lets reversed / F-contiguous / transposed views coalesce to a single chunk. For logical order — the order ndenumerate(NDArray) uses — passorder: 'C'.
- np.NDRefIter<T>.Enumerator
The cursor. Walks the inner loop with plain pointer arithmetic and only touches the iterator at a chunk boundary, so a contiguous array costs one iterator call for the whole walk.
- np.OGridResult
The result of an ogrid index expression: an open mesh — a set of N arrays, each 1 in every axis but its own. NumPy's
ogridis polymorphic (a single slice yields a barendarray, several slices yield atuple), which C# cannot express from one indexer, so this value stands in for both:
- np.UniqueAllResult
The result of unique_all(NDArray): NumPy's
UniqueAllResultnamedtuple (values,indices,inverse_indices,counts). Converts implicitly to NDArray[],Deconstructs (var (values, indices, inv, counts) = np.unique_all(x);) and indexes ([k]).
- np.UniqueCountsResult
The result of unique_counts(NDArray): NumPy's
UniqueCountsResultnamedtuple (values,counts). Converts implicitly to NDArray[],Deconstructs (var (values, counts) = np.unique_counts(x);) and indexes.
- np.UniqueInverseResult
The result of unique_inverse(NDArray): NumPy's
UniqueInverseResultnamedtuple (values,inverse_indices). Converts implicitly to NDArray[],Deconstructs (var (values, inv) = np.unique_inverse(x);) and indexes.
- np.UniqueResult
The result of <xref href="NumSharp.np.unique(NumSharp.NDArray%2cSystem.Boolean%2cSystem.Boolean%2cSystem.Boolean%2cSystem.Nullable%7bSystem.Int32%7d%2cSystem.Boolean%2cSystem.Boolean)" data-throw-if-not-resolved="false"></xref> — NumPy's bare-array-OR-tuple return expressed as one type. It carries the sorted unique <xref href="NumSharp.np.UniqueResult.values" data-throw-if-not-resolved="false"></xref> plus whichever of <xref href="NumSharp.np.UniqueResult.indices" data-throw-if-not-resolved="false"></xref>/<xref href="NumSharp.np.UniqueResult.inverse_indices" data-throw-if-not-resolved="false"></xref>/ <xref href="NumSharp.np.UniqueResult.counts" data-throw-if-not-resolved="false"></xref> were requested (the others are <code>null</code>), so <code>np.unique(ar, return_counts=True)</code> ports from Python verbatim.It stands in for both NumPy return shapes: it converts implicitly to NDArray (the bare form — yields values, so
NDArray u = np.unique(ar);works) and implicitly to NDArray[](the tuple form — the present outputs in NumPy field order). It also indexes ([k]= the k-th present output, matching the oldNDArray[]return) andDeconstructs (var (values, counts) = np.unique(ar, return_counts: true);).
Interfaces
- IIndex
Represents a class that can be served as an index, e.g. ndarray[new Slice(...)]
- INDArrayCarrier
Opt-in seam a tuple-standin result struct (np.UniqueResult, np.MeshgridResult, PolyfitResult, …) implements so the NDScopedAttribute weaver can weave a boundary method that RETURNS it: YieldTo(NDScope) hands every NDArray the struct carries back to the ambient scope (via Returns<T>(T)), so the method's temporaries are reclaimed while its results survive.
- ISeedSequence
The seed-sequence protocol a BitGenerator seeds itself from (NumPy's
numpy.random.bit_generator.ISeedSequence).
- ISpawnableSeedSequence
A seed sequence that can derive independent children (NumPy's
numpy.random.bit_generator.ISpawnableSeedSequence) — what spawn(int) and spawn(int) require.
Enums
- ArrayFlags
NumPy-aligned array flags. Cached at shape creation for O(1) access. Matches numpy/core/include/numpy/ndarraytypes.h flag definitions.
- DTypeFlags
Flags describing a DTypeMeta — the DType CLASS — under NumPy's own names, the
NPY_DT_*bits ofdtypemeta.h/dtype_api.hwith NumPy's values (NPY_DT_LEGACY = 1,NPY_DT_ABSTRACT = 2,NPY_DT_PARAMETRIC = 4,NPY_DT_NUMERIC = 8), so a flags word compares bit for bit with NumPy'sPyArray_DTypeMeta.flags.
- NPTypeCode
Represents all available types in numpy.
- NPTypeKind
Abstract type categories in NumPy's type hierarchy. These mirror NumPy's abstract scalar types (np.generic, np.number, etc.)
- NPY_DATETIMEUNIT
NumPy's
NPY_DATETIMEUNIT(ndarraytypes.h): the time unit adatetime64/timedelta64value counts in. The enum values are NumPy's — including the gap at 3 where the 1.6 business-day unit sat — because unit ORDER is semantic (a larger value is a finer unit) and NumPy's casting rules compare them.
- NPY_SCALARKIND
NumPy's
NPY_SCALARKINDenum (numpy/_core/include/numpy/ndarraytypes.h, NumPy 2.4.2): the kind of a scalar for the LEGACY value-based casting of NumPy 1.x, the answer ofPyArray_ScalarKindthatPyArray_CanCoerceScalarreads. The same members, order and values as the header.
- NPY_TYPECHAR
NumPy's
NPY_TYPECHARenum (numpy/_core/include/numpy/ndarraytypes.h, NumPy 2.4.2): the one-character type codes of the builtin dtypes (char, the stringsnp.dtype('d')parses) followed by the dtype KIND letters (kind). Byte-identical to the header: the same members, in the same order, with the same values, so(char)NPY_TYPECHAR.NPY_CDOUBLELTRis'D'exactly as in C.
- NPY_TYPES
NumPy's
NPY_TYPEStype-number enum (numpy/_core/include/numpy/ndarraytypes.h) — the C-API identity behind every descriptor's num / type_num. Byte-identical to NumPy's header: the members and their integer values are exactly NumPy's, so(int)NPY_TYPES.NPY_CDOUBLEis 15 on every platform, anda.dtype.type_numequalsnp.dtype(...).numon the host it runs on.
- NewSubtypeZeroDim
How an ndarray method's 0-d result reaches the caller (NumSharp.NewSubtypeAttribute.ZeroDim): the third argument of __array_finalize__(NDArray, bool, NewSubtypeZeroDim), which a subclass reads to decide whether a 0-d result stays an array of its class or becomes the element it stands for.
- PyScalarKind
The three NEP 50 "weak" literal categories: a Python
int,float,complex.