Skip to content

Latest commit

 

History

History
506 lines (342 loc) · 9.81 KB

File metadata and controls

506 lines (342 loc) · 9.81 KB

NDArray Class

The main N-dimensional array class.

Overview

NDArray is the core class of this library. It represents an N-dimensional array backed by Rust via FFI. Each NDArray instance holds:

  • A pointer to the underlying Rust array handle
  • Metadata about the array (shape, dtype, strides)
  • Reference counting information for memory management

An NDArray can represent either:

  • An owned array - The array owns its data and memory
  • A view of an array - A slice or view that shares memory with another array
use PhpMlKit\NDArray\NDArray;

// Create an owned array
$arr = NDArray::array([1, 2, 3, 4, 5]);

// Create a view (shares memory)
$view = $arr[0:3];
echo $view->isView();  // true

Properties

Methods to inspect array metadata.

shape()

Returns the dimensions of the array, or the length of a single axis when you pass an index.

public function shape(?int $axis = null): array|int

With no argument (or null), you get the full shape as a list of positive integers. With an integer $axis, you get only that axis length. Negative indices count from the last dimension (-1 is the last axis), matching how axis arguments work on reductions and similar methods. Requesting an axis index on a zero-dimensional array throws IndexException.

Parameters:

Parameter Type Description
$axis int|null Optional. If omitted or null, return the full shape. If set, return the size of that axis only.

Returns: list<int> for the full shape, or int for one axis length.

Examples:

$arr = NDArray::zeros([3, 4, 5]);
$arr->shape();    // [3, 4, 5]
$arr->shape(0);   // 3
$arr->shape(-1);  // 5 (last dimension)

$vector = NDArray::array([1, 2, 3]);
$vector->shape();   // [3]
$vector->shape(-1); // 3

ndim()

Returns the number of dimensions.

public function ndim(): int

Returns: Integer count of dimensions

Examples:

$scalar = NDArray::array([1]);
echo $scalar->ndim();  // 1

$matrix = NDArray::zeros([3, 4]);
echo $matrix->ndim();  // 2

$tensor = NDArray::zeros([2, 3, 4, 5]);
echo $tensor->ndim();  // 4

size()

Returns the total number of elements.

public function size(): int

Returns: Total element count

Examples:

$arr = NDArray::zeros([3, 4, 5]);
echo $arr->size();  // 60 (3 * 4 * 5)

$vector = NDArray::array([1, 2, 3, 4, 5]);
echo $vector->size();  // 5

dtype()

Returns the data type of the array.

public function dtype(): DType

Returns: DType enum value

Examples:

$arr = NDArray::array([1, 2, 3]);
echo $arr->dtype();  // DType::Int64

$int_arr = NDArray::array([1, 2, 3], DType::Int32);
echo $int_arr->dtype();  // DType::Int32

See Also:


itemsize()

Returns the size of each element in bytes.

public function itemsize(): int

Returns: Bytes per element

Examples:

$f64 = NDArray::array([1.0], DType::Float64);
echo $f64->itemsize();  // 8

$f32 = NDArray::array([1.0], DType::Float32);
echo $f32->itemsize();  // 4

$i32 = NDArray::array([1], DType::Int32);
echo $i32->itemsize();  // 4

nbytes()

Returns the total bytes consumed by the array.

public function nbytes(): int

Returns: Total bytes (size * itemsize)

Examples:

$arr = NDArray::zeros([1000, 1000], DType::Float64);
echo $arr->nbytes();  // 8000000 (8 MB)

// Memory-efficient alternative
$small = NDArray::zeros([1000, 1000], DType::Float32);
echo $small->nbytes();  // 4000000 (4 MB)

strides()

Returns the byte steps in each dimension.

public function strides(): array

Returns: Array of strides

Examples:

$arr = NDArray::array([[1, 2, 3], [4, 5, 6]], DType::Float64);
echo $arr->strides();  // [24, 8]
// 24 bytes to next row, 8 bytes to next column
// (Float64 = 8 bytes per element)

::: tip Strides are used internally for views and non-contiguous arrays. :::


isView()

Returns whether the array is a view of another array.

public function isView(): bool

Returns: True if array shares memory with parent

Examples:

$arr = NDArray::array([1, 2, 3, 4, 5]);
echo $arr->isView();  // false

$view = $arr[0:3];
echo $view->isView();  // true

See Also:


isContiguous()

Returns whether the array is C-contiguous (row-major).

public function isContiguous(): bool

Returns: True if elements stored sequentially in memory

Examples:

$arr = NDArray::array([[1, 2], [3, 4]]);
echo $arr->isContiguous();  // true

// Transpose changes strides
$transposed = $arr->transpose();
echo $transposed->isContiguous();  // false

// Copy restores contiguity
$copy = $transposed->copy();
echo $copy->isContiguous();  // true

String Representation

NDArray implements PHP's Stringable interface, allowing arrays to be used in any string context.

__toString()

Returns a string representation of the array.

public function __toString(): string

Uses global print options configured via setPrintOptions(). The output includes a header showing the array shape.

Returns: String representation of the array

Examples:

$arr = NDArray::array([1, 2, 3]);
echo $arr;
// array(3)
// [1 2 3]

$matrix = NDArray::array([[1, 2], [3, 4]]);
echo $matrix;
// array(2, 2)
// [
//  [1 2]
//  [3 4]
// ]

See Also:


NDArray::setPrintOptions()

Configure global print options for all array displays.

public static function setPrintOptions(
    int $threshold = 1000,
    int $edgeitems = 3,
    int $precision = 8
): void

Parameters:

Name Type Default Description
threshold int 1000 Maximum elements before truncation
edgeitems int 3 Items to show at each edge when truncating
precision int 8 Decimal places for floating-point numbers

Examples:

// Configure for high precision
NDArray::setPrintOptions(precision: 16);

$values = NDArray::array([1.123456789012345]);
echo $values;
// array(1)
// [1.123456789012345]

// Compact display for large arrays
NDArray::setPrintOptions(threshold: 10, edgeitems: 2);

$arr = NDArray::arange(20);
echo $arr;
// array(20)
// [0 1 ... 18 19]

NDArray::getPrintOptions()

Retrieve current print settings.

public static function getPrintOptions(): array

Returns: Array with keys threshold, edgeitems, and precision

Examples:

$options = NDArray::getPrintOptions();
// ['threshold' => 1000, 'edgeitems' => 3, 'precision' => 8]

NDArray::resetPrintOptions()

Restore print options to default values.

public static function resetPrintOptions(): void

Examples:

NDArray::setPrintOptions(precision: 16);
// ... use high precision ...

NDArray::resetPrintOptions();
// Now uses: threshold=1000, edgeitems=3, precision=8

Complex Value Object

The Complex class represents a complex number with real and imaginary parts. It is used to create complex arrays and to receive complex scalar results from operations.

Constructor

public function __construct(
    public readonly float $real,
    public readonly float $imag = 0.0
)

Create a complex number from real and imaginary parts.

Parameters:

Parameter Type Description
$real float The real part.
$imag float The imaginary part. Optional. Default: 0.0.

Examples:

use PhpMlKit\NDArray\Complex;

// Create complex numbers
$z1 = new Complex(3, 4);     // 3 + 4i
$z2 = new Complex(1.5);      // 1.5 + 0i (pure real)
$z3 = new Complex(0, 2);     // 0 + 2i (pure imaginary)

// Use in arrays
$arr = NDArray::array([
    new Complex(1, 2),
    new Complex(3, 4),
], DType::Complex128);

Properties

  • $real — The real part (read-only)
  • $imag — The imaginary part (read-only)

Methods

magnitude()

public function magnitude(): float

Returns the magnitude (absolute value): √(real² + imag²).

$z = new Complex(3, 4);
echo $z->magnitude();  // 5.0

angle()

public function angle(): float

Returns the phase angle in radians: atan2(imag, real).

$z = new Complex(1, 1);
echo $z->angle();  // 0.785... (π/4)

equals()

public function equals(Complex $other, float $tol = 1e-10): bool

Check if this complex number equals another within a tolerance.

$a = new Complex(1.0, 2.0);
$b = new Complex(1.0000001, 2.0000001);

$a->equals($b);        // true (within default tolerance)
$a->equals($b, 1e-12); // false (stricter tolerance)

toArray()

public function toArray(): array

Returns [real, imag] as a flat array for FFI transmission.

$z = new Complex(3, 4);
print_r($z->toArray());
// Output: [3.0, 4.0]

Summary

Property Returns Description
shape() array Dimensions [rows, cols, ...]
ndim() int Number of dimensions
size() int Total element count
dtype() DType Data type enum
itemsize() int Bytes per element
nbytes() int Total memory usage
strides() array Byte steps per dimension
isView() bool Whether shares memory
isContiguous() bool Whether row-major

Next Steps