BigParrot Numerics Library for Unity is a tool that can increase productivity in numerical computing tasks in Unity and C#.
It provides more than 100 methods, including easily and flexible array manipulation routines, useful mathematical functions, linear algebra and polynomial routines, Fast Fourier transforms, and signal processing.
It can be used directly in Unity without requiring additional installation or environment setup, and it is compatible with mobile platforms as well.
E-mail: bigparrotstudio@gmail.com (Feature requests, bug reports or contact)
Install package to your project by using the Package Manager window.
Importing an Asset Store packageIt targets .NET Standard 2.1 or higher and Unity 2021 LTS or higher.
https://docs.unity3d.com/Manual/dotnetProfileSupport.htmlIn the .NET Standard 2.0 environment, change the API compatibility to .NET 4.x.
https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/unity-scripting-upgradeThe NumericsArray serves as the primary storage space, providing arrays of various types that inherit from NumericsArray<T>.
| Array | Data Type |
|---|---|
| DoubleArray | double |
| FloatArray | float |
| IntArray | int |
| BoolArray | bool |
| ComplexArray | BigParrot.Numerics.Complex |
Each array class will have an array based on its data type. Therefore, the supported features or behaviors may vary for each type.
To declare an NumericsArray, you can create a class of the desired type.
Here is an example that creates an array of type double with length 5 and an array of type boolean with length 3:
To declare an 2-dimensional array, you would input the row and column sizes.
The following creates an array of type int with 2 rows and 5 columns:
You can use the Empty method to create an empty array. The following creates an empty array of type float:
You can also create an array by providing an existing C# array as an argument:
The properties that contain information about the shape and size of an array are as follows:
| Properties | Description |
|---|---|
| NDim | Returns the number of dimensions of the array. |
| Length | Returns the total number of elements in the array. |
| RowCount | Returns the number of rows in the array. |
| ColumnCount | Returns the number of columns in the array. |
| Shape | Returns an ArrayShape structure containing the above elements. |
In a one-dimensional array, RowCount is 0, and Length and ColumnCount are equal.
In a two-dimensional array, Length is equal to the product of RowCount and ColumnCount.
Currently, arrays with a maximum of 2 dimensions are supported. We plan to support higher-dimensional arrays in the future.
Like C# arrays, NumericsArray's indexing is zero-based, but it also supports negative indexing. For instance, -1 accesses the last element of the array.
For 2-dimensional array, both 2-dimensional indexing and 1-dimensional indexing are possible. In this case, the index order follows row-major order.
In addition to accessing it through the array indexer, you can also slice a specific range of array elements using the Get or Slice functions.
The following is an example of using the Get function to slice elements from rows 0 to 2 and columns 1 to 2 in an array.
You can also index an array using conditions. Here's an example that indexes elements greater than 3:
You can easily perform operations between arrays and scalars or between arrays. Arithmetic operators provided include +, -, *, /, and %.
In C#, the % operator behaves as the remainder operator, which is different from Python's % operator. To achieve the same result as Python's % operator in C#, you should use the Modulo method.
Comparison operators provided include ==, !=, >, >=, <, <=, &, |, ^.
When you compare elements of two arrays using these operators, the result is returned as a BoolArray.
If you want to determine whether two arrays have exactly the same shape and elements, you can use the ArrayEquiv. Equals compares whether two arrays are the same object.
To perform operations between two arrays, their shapes and sizes must match, or one of the arrays' axis sizes must be 1.
For example, if you want to perform addition operation between two 1-dimensional arrays. Assuming that the length of array b is 1, you can perform the operation by assuming that it matches the size of array a. Therefore, each element of a performs addition with the first index of b.
However, if the length of b is 2, an error will occur.
The same applies to 2-dimensional arrays. In the case of the following two arrays, there is no problem performing operations because the row size of array b is 1. If the row size is 1 or the column size is 1, it can extend it to perform calculations.
To convert the type of an array, type conversion functions such as ToIntArray and ToDoubleArray are provided.
Here's an example of converting a DoubleArray to an IntArray using the provided type conversion functions:
When performing type conversion, it use the Convert class in C#. For detailed information, please refer to the documentation of that class.
When creating arrays, various methods are provided to generate arrays with a specified interval or shapes.
Arange function generates an array with evenly spaced values within a given interval.
Linspace function generates an array with evenly spaced numbers over a specified interval.
The following example creates an array with a length of 5, evenly spaced between 2 and 10:
Logspace function generates an array with logarithmically spaced numbers over a specified interval.
Eye function creates a identity matrix. Here's an example to create a 3-by-3 identity matrix:
Diagonal function creates a diagonal array or extract a diagonal.
Triu function returns the upper triangular portion of array.
Vander function creates a Vandermonde matrix.
Random function creates an array filled with random values within the given range. Here's an example of creating a 2-dimensional array of size 3-by-3 using the ArrayShape class and filling it with random values between 0 and 10:
RandomChoice function generates a random samples from a given 1-dimensional array. Here's an example of creating a 1-dimensional array of size 5 and filling it with randomly chosen elements from array r:
RandomNormal function generates a random samples from a normal distribution.
When manipulating arrays, you can determine which axis to access elements along.
In a one-dimensional array, the axis is always Axis.None, and changing it to another axis has no effect. When Axis.None is used in a two-dimensional array, it accesses it as if it were a one-dimensional array.
Set function sets the value of the elements at the specified position. Here is an example of changing a element at row index 1 and column index 1:
Using functions like SetRow or SetColumn, you can replace specific columns or rows with different elements.
Fill function fills the array with a given values. If an array is provided as an argument, its contents will be used to fill all elements.
Swap function swaps elements at specified positions in an array. In the following example, the first and last rows (-1) are swapped.
Roll function shifts the elements of the array. If the shift argument is positive, the elements are shifted in the positive direction; if negative, the elements are shifted in the negative direction.
Place function changes elements that meet the condition with the given array elements. The following is an example of changing an element with value 1 to a given array.
Shuffle function shuffles all elements of an array randomly.
Clip function limits the elements of an array so that they do not fall below minValue or exceed maxValue.
Repeat function returns an array with each element of the original array repeated. If a 2-dimensional array is repeated, it will be repeated along the specified axis.
Append function adds new elements to the end of the array.
You can add a new row or a new column based on the specified axis. Here's an example of adding a new row to a 2-dimensional array:
Insert function inserts new elements into the array at the specified index.
Concatenate function concatenates two or three arrays. Here's an example of concatenating three 1-dimensional arrays:
Remove function removes a specific region of the array. Below is an example of removing elements from the last row (-1) of a 2-dimensional array:
The Trim function trims the leading and trailing zeros from an array.
Resize function changes the size of the array. If the new size is smaller, existing elements will be removed. It is also allowed to change the dimensions of the array. Here's how you can use it:
Reshape function changes the shape of a 2-dimensional array without altering its total size. When providing newRowCount and newColumnCount, the total size must be preserved. If one of the arguments is set to -1, it will be automatically determined to maintain the total size.
Here's an example of reshaping a 2-by-3 array into a 3-by-2 array:
Transpose function transposes the array.
Ravel function flattens a 2-dimensional array into a 1-dimensional array. If isRowMajor is set to false, it flattens the array in column-major order. Here's how you can use it:
Reverse function reverses the order of elements. Here's an example of reversing the array along the row axis in a 2-dimensional array:
Sort function sorts the array. Arrays are sorted in ascending order.
For a 1-dimensional array, all elements are sorted. For a 2-dimensional array, elements are sorted along each axis. If the axis is None, the entire array is sorted in row-major order.
Here's an example of sorting each row along the column axis in a 2-dimensional array:
ArgSort function returns the indices of the sorted array as an IntArray. Here's how you can use it:
Unique function returns the unique elements of an array as a 1-dimensional array.
Extract function returns elements that satisfy the specified condition as a 1-dimensional array. Here's an example of extracting elements from array a that are greater than 2 and less than or equal to 4:
Take function returns elements corresponding to the specified indices as a new array. Here's how you can use it:
NonZero function return the indices of the elements that are non-zero.
Sum function returns the sum of elements in the array.
You can calculate the sum along each axis. Here's an example of calculating the sum of each row along the column axis:
CumulativeSum function returns the cumulative sum of elements in the array. In a 2-dimensional array, you can calculate the cumulative sum along each axis.
Product function returns the product of elements in the array.
CumulativeProduct function returns the cumulative product of elements in the array.
Difference function calculates the discrete difference of elements in the array. The first difference is given by as a[1] - a[0]. Here's an example of computing differences in a one-dimensional array:
Exp function calculates the exponential of each element in the array.
Sqrt function calculates the square root of each element in the array.
Log function calculates the natural logarithm of each element in the array.
Log10 function calculates the base 10 logarithm of each element in the array.
Sin, Cos, Tan, etc. compute trigonometric functions element-wise.
Hypotenuse function returns the hypotenuse of a right-angled triangle.
Rad2Deg and Deg2Rad functions convert elements of an array from radians to degrees or from degrees to radians, respectively.
You can create a ComplexArray composed of the BigParrot.Numerics.Complex struct to perform complex number calculations.
The Real function returns only the real part of the complex array, while the Imag function returns only the imaginary part of the complex array.
Conjugate function returns the complex conjugate of the complex array.
Angle function returns the angle of the complex number elements. The returned angle is in radians, but if the isDegrees parameter is set to true, it returns the angle in degrees.
Abs function returns the absolute values of the elements.
Power function returns the elements raised to the power.
Round function rounds the elements to the given number of decimal.
Floor function returns the floor of the elements.
Ceiling function returns the ceiling of the elements.
Reciprocal function returns the reciprocal of the elements in the array.
Unwrap function unwraps a given array by transforming deltas to complement values.
Trunc function return the truncated value of the input.
Sinc function returns the normalized sinc function.
Interpolate function performs linear interpolation over monotonically increasing points.
The Min and Max function returns the minimum and maximum values among the elements of the array. Here's an example of finding the minimum and maximum values in a one-dimensional array:
In the following example, it returns the minimum and maximum values for each column along the row axis in a two-dimensional array:
ArgMin and AgrMax methods return the indices of the minimum or maximum values of the array as IntArray.
Additionally, you can use more statistical functions by creating a Stats class.
Below is example that creates a stats class and uses the Mean and Median functions to calculate the mean and median values of an array.
GeometricMean function returns the geometric mean, and HarmonicMean function returns the harmonic mean.
Variance function returns the sample variance of the elements, and the PVariance function returns the population variance.
Stdev function returns the sample standard deviation of the elements, and the PStdev function returns the population standard deviation.
Percentile function calculates the percentile of the elements. By providing a value percent between 0 and 100, it returns the percentile of the array elements.
Here's an example of finding the 30th percentile in a one-dimensional array:
Convolve function returns the linear convolution between two one-dimensional arrays. The default mode is Full, it returns the convolution at each overlapping point. If the mode is Valid, it returns only for points where the signals fully overlap.
Correlate function computes the correlation between two one-dimensional arrays. The dafault mode is Valid.
The BigParrot Numerics Library provides Linear Algebra functions based on OpenBLAS and LAPACK. The LAPACK library is based on the commercial license of DotNumerics.
Inner function computes the inner product of two one-dimensional arrays. It calls the _DOT function from OpenBLAS.
Matmul function computes the matrix product of two arrays. For the multiplication between a 2D array and a 1D array, it calls _GEMV from OpenBLAS, and for the multiplication between two 2D arrays, it calls _GEMM.
Dot function computes the dot product of two arrays. When the arrays are 1-dimensional, it calculates the inner product; when they are 2-dimensional, it performs matrix multiplication.
Outer function computes the outer product of two vectors.
Norm function to compute matrix or vector norms. By changing the ord argument you can determine the order of the norm.
QRDecomp function computes the QR decomposition of a matrix. It calls the _GEQRF function from LAPACK.
Solve function solves a linear matrix equation or linear scalar equation systems.
Solve the system of equations 1x + 2y = 8 and 3x + 4y = 18:
Lstsq function returns the least-squares solution to a linear matrix equation. It calls the _GELSD function from LAPACK.
Eigvals function computes the eigenvalues of a general matrix and returns them as a ComplexArray.
Inv function computes the inverse of a matrix.
Poly function computes the coefficients of a polynomial with the given specified roots.
Roots function returns the roots of a polynomial using the given coefficients.
PolyInt function returns the integral of the polynomial.
PolyDer function returns the derivative of the polynomial.
PolyFit function finds the least squares polynomial fit.
PolyVal function evaluates the polynomial at a specific value.
PolyAdd function find the sum of two polynomials.
PolySub function returns subtraction of two polynomials.
PolyMul function find the product of two polynomials.
PolyDiv function returns the quotient and remainder of polynomial division as a tuple.
The BigParrot Numerics Library provides various signal processing functions for 1-D signals.
The FFT functions of this library is developed based on SharpFFTPack.
https://github.com/dcprojects/SharpFFTPACKFFT function compute the 1-D discrete Fourier Transform.
IFFT function compute the 1-D inverse discrete Fourier Transform.
RFFT function compute the 1-D discrete Fourier Transform for real input.
IRFFT function compute the 1-D inverse discrete Fourier Transform for real input.
FFTFreq and RFFTFreq functions return the discrete fourier transform sample frequencies.
Butterworth function designs a digital Butterworth filter and returns the filter coefficients as a tuple of the numerator (b) and denominator (a) of the IIR filter. The filter types provided are BandpassFilter, BandstopFilter, LowpassFilter, and HighpassFilter.
The following example designs a Butterworth bandpass filter with a lower cutoff frequency of 0.5 Hz and a higher cutoff frequency of 4.0 Hz. Specify a sample rate of 50 Hz:
Chebyshev function and the Chebyshev2 function design digital Chebyshev filters and return the filter coefficients as a tuple of the numerator (b) and denominator (a) of the IIR filter.
FirWin function designs an FIR filter using window methods.
You can specify the window type in the window parameter. The provided types include the following:
- Hann, Hamming, Cosine, Boxcar, Bohman, Blackman, Blackmanharris, Nuttall, Flattop, Bartlett, Barthann, Kaiser, Gaussian, Tukey
FirWin2 function designs an FIR filter using window methods with the given frequency and gain.
LinearFilter function filters IIR or FIR filters along the elements of a 1-dimensional array.
LinearFilterZi function computes the initial conditions zi of the filter delay, which can be added as an argument to the LinearFilter method.
Filtfilt function applies a digital filter to the front and back of a signal.
Detrend function removes linear trend from data. You can select detrend type. The Linear type subtracts the result of a linear least squares fit to data. The Constant type only subtracts the mean of the data.
Welch function estimates the power spectral density using the Welch's method.
The Periodogram function estimates the power spectral density using a periodogram.
To find peaks within a 1-dimensional array signal, you can create a PeakFinding class and set attributes such as prominence, height, threshold, etc. Then, you can use the Find method to search for peaks. The indices corresponding to the peaks will be stored in the peaks attribute.