Browse documentation
aner.tensor · Reference

SemanticTensor

Native Tensor values with explicit coordinate identity, physical units, exact arithmetic, reindexing and acknowledged numerical boundaries.

Implemented

SemanticTensor is an opt in native facade over existing Tensor storage. It retains scientific axes, ordered coordinate identity and declared physical units. Import aner.tensor. Plain Tensor operations retain their existing lightweight contracts; scientific values use registered semantic operations or an explicitly acknowledged raw export.

Coordinate aware station anomalies demonstrates the practical difference. Current measurements in A/B order and a baseline in B/A order have equal shapes but cannot be subtracted positionally. Explicit reindexing produces the correct anomalies 1 and 8.

Return to the aner.tensor module guide for construction, numerical operations and placement. This specialized reference covers the tensor.semantic constructor and SemanticTensor receiver methods. No separate aner.tensor.semantic import is required.

Run a complete coordinate example

After installation, use the bundle's examples directory or download the complete source:

sh
aner check examples/contextual_coordinates.aner
aner run examples/contextual_coordinates.aner

The fixture is entirely in source and uses CPU Float64; it requires no external files or service.

aner
// Two station files have equal shapes but different coordinate order.
import aner.tensor

let current = tensor.semantic([[10.0], [20.0]], "station", List("A", "B"), "degC")
let baseline = tensor.semantic([[12.0], [9.0]], "station", List("B", "A"), "degC")
// Reindexing explicitly reconciles the declared coordinate identities.
let aligned = baseline.reindex_like(current)
let anomaly = current.subtract(aligned)

print("Baseline aligned to A, B")
print(aligned.value(0, 0))
print(aligned.value(1, 0))
print("Station anomalies")
print(anomaly.value(0, 0))
print(anomaly.value(1, 0))
print(anomaly.unit())
print("Coordinate order is preserved")
print(anomaly.coordinates())
print("First current temperature in Kelvin")
print(current.convert("K").value(0, 0))

Expected output:

text
Baseline aligned to A, B
9.0
12.0
Station anomalies
1.0
8.0
delta_degC
Coordinate order is preserved
List("A", "B")
First current temperature in Kelvin
283.15

The station anomaly application explains the coordinate order failure and includes a runnable program that intentionally rejects an unsafe positional subtraction.

Construction and coordinate identity

tensor.semantic(values, axis, coordinates, unit) creates a single column observation tensor with one declared sample axis and a unique ordered String coordinate per row. Duplicate labels and extent mismatches fail. Declaring identical display text does not silently prove independently constructed scientific domains are the same.

Arithmetic requires exact axis, coordinate and unit compatibility. reindex_like(reference) explicitly reconciles a complete coordinate set with the reference order and domain. It rejects missing, extra or duplicate coordinates; there is no implicit intersection, interpolation or dropped station. Gather and unit conversion apply the same transformation to values and their retained descriptors.

Contextual model batches can carry ordered heterogeneous feature units. That schema is not equivalent to assigning the entire input matrix the unit of its first feature. A derived model internal representation needs the registered contract appropriate to that operation.

Units and absolute temperatures

The bounded native registry currently contains 23 exact unit codes: 1, m, cm, mm, km, s, h, m/s, km/h, N, N/m, kg, degC, degF, K, delta_degC, delta_degF, delta_K, J, kWh, W, kW, and Pa. Supported conversions use declared dimension, scale and quantity kind. Numeric values do not establish their own unit, and a String label is not a measurement verification.

Absolute Celsius, Fahrenheit and Kelvin temperatures are affine points. Subtracting two compatible absolute temperatures yields a temperature difference, such as delta_degC. Adding two absolute temperatures through ordinary addition fails; an explicitly defined mean of temperature points is a different operation. Compatible differences can be added to absolute points. Incompatible dimensions fail before executing the arithmetic.

Unit conversion applies its scale and offset to the values. A coordinate temperature of 10 degC becomes 283.15 K; 68 degF becomes 20 degC or 293.15 K. A difference of 18 delta_degF becomes 10 delta_degC or 10 delta_K, with no absolute temperature offset. Length conversion uses 100 cm = 1 m and 1,000 mm = 1 m. All conversion arithmetic uses the Tensor's explicitly selected precision.

The registry accepts these exact Strings and is shared with aner.units, which provides immutable scalar Quantity<m>/Point<degC> types and unit literals such as 2.0@m and 20.0@degC in Aner 0.0.4 or newer. Scalar values do not replace this facade: SemanticTensor retains axes, numerical dtype/device and its supported differentiation graph. Its constructors still take raw Tensor magnitudes and an explicit unit String; scalar values are not automatically packed into Tensor storage.

The registry does not parse arbitrary composed units. Scalar quantity products derive only an existing scale one linear registry result, while SemanticTensor retains its own registered API. Existing contextual per column unit labels remain declarations; they do not themselves request numerical normalization. Explicit CSV unit schemas and scan conversion now retain source interpretation and normalize into a declared target before filters/projection, with typed scalar/array retrieval. This does not construct SemanticTensor coordinates or its differentiation graph. Packed unit bearing Array/DynamicArray/NDArray buffers are implemented separately with exact Quantity/Point element types, a single unit descriptor and explicit raw export. They do not supply this facade's coordinate or differentiation contracts. Currency conversion, coordinate reference systems and arbitrary scientific equivalencies remain outside the current APIs.

This complete conversion example retains one coordinate domain while converting units:

aner
import aner.tensor

let temperature = tensor.semantic([[68.0]], "sensor", List("room"), "degF")
let celsius = temperature.convert("degC")
let difference = temperature.subtract(celsius)
print(celsius.value(0, 0) > 19.999999999 && celsius.value(0, 0) < 20.000000001)
print(difference.unit())
print(difference.value(0, 0) > -0.000000001 && difference.value(0, 0) < 0.000000001)

let length = tensor.semantic([[100.0]], "sample", List("one"), "cm")
print(length.convert("mm").value(0, 0) > 999.999999999 && length.convert("mm").value(0, 0) < 1000.000000001)

The output is true, delta_degF, true, then true. Save it as unit_conversion.aner and run aner check unit_conversion.aner, followed by aner run unit_conversion.aner. Adding two absolute temperatures fails; a point and a compatible interval use the supported addition/subtraction rules. Conversion preserves existing differentiation where supported; an affine Fahrenheit to Celsius conversion scales its derivative by 5/9.

Numerical boundaries and placement

The scientific facade preserves context through its registered operations. Tracked scientific transformations retain at most 64 registered operation records, including records merged from both branches. Additional operations fail with a located E_RESOURCE_BUDGET diagnostic and leave earlier values intact. The records retain old/new units and derived meaning; they are not a general replayable provenance graph.

Scalar value(row, column) is a readout, useful for inspection. Reconstructing a new Tensor from readout scalars does not recover source identities, fit permissions or uncertainty.

Raw export requires an explicit reason and reports the discarded contracts. It is intended for an acknowledged interoperability boundary, not ordinary contextual model training. Unsupported transformations must fail rather than reuse coordinate labels after their meaning has changed.

Placement and precision follow explicitly supported native Tensor operations. Availability is probed at runtime; transfers and dtype changes are explicit and preserve the registered scientific context. Actual storage precision and device remain inspectable. Backend support is operation specific and must not be inferred merely from a physical GPU name. reindex_like and gather_rows currently require CPU storage and reject differentiable graphs until a backward permutation rule is implemented. Registered arithmetic and explicit compatible transfers have their separate supported rules.

Native API signatures

Qualified functions and the corresponding recognized receiver methods use the same native contracts. self denotes the receiver in the qualified signature. Lists of names or units contain Strings; index lists contain Int64 values. Wrong List element types fail instead of coercing values.

Native signatureResult
tensor.summary(self: SemanticTensor)String
tensor.explain(self: SemanticTensor)String
tensor.semantic(values: Tensor, axis: String, coordinates: List, unit: String)SemanticTensor
tensor.rows(self: SemanticTensor)Int64
tensor.cols(self: SemanticTensor)Int64
tensor.unit(self: SemanticTensor)String
tensor.dtype(self: SemanticTensor)String
tensor.device(self: SemanticTensor)String
tensor.coordinates(self: SemanticTensor)List
tensor.value(self: SemanticTensor, row: Int64, column: Int64)Float64
tensor.gather_rows(self: SemanticTensor, indices: List)SemanticTensor
tensor.add(self: SemanticTensor, other: SemanticTensor)SemanticTensor
tensor.subtract(self: SemanticTensor, other: SemanticTensor)SemanticTensor
tensor.convert(self: SemanticTensor, unit: String)SemanticTensor
tensor.astype(self: SemanticTensor, dtype: String)SemanticTensor
tensor.to(self: SemanticTensor, device: String)SemanticTensor
tensor.reindex_like(self: SemanticTensor, reference: SemanticTensor)SemanticTensor
tensor.export_values(self: SemanticTensor, reason: String)ContextExport
ContextExport.values(self: ContextExport)Tensor
ContextExport.report(self: ContextExport)String

Method contracts and failures

add and subtract require identical ordered axis domains, compatible homogeneous units and matching dtype/device. Equal labels created independently do not automatically establish one domain; reindex_like explicitly reconciles a complete coordinate set and matching axis names. gather_rows takes a nonempty List of zero based Int64 indices. Repeated indices preserve the same observation identity rather than creating independent observations. coordinates() returns the ordered row labels, subject to the managed List export bound.

value(row, column) uses zero based in bounds coordinates. unit() returns a homogeneous declared unit or the String "feature_schema" for a heterogeneous contextual model input facade. The latter is an inspection marker rather than one physical unit; unit arithmetic requires a homogeneous compatible quantity. astype and to follow the underlying Tensor precision/placement contracts; they do not choose a fallback implicitly. export_values(reason) requires a nonempty UTF-8 reason of at most 1,024 bytes without control characters. It returns ContextExport, with the underlying immutable nominal Tensor from .values() and the loss of context report from .report(). Export does not implicitly detach an existing numerical differentiation graph.

Scientific runtime diagnostics use R3502 and an underlying semantic code. E_AXIS_ALIGNMENT identifies incompatible coordinates/shapes, E_UNIT_INCOMPATIBLE incompatible or unsupported units, E_AFFINE_QUANTITY invalid absolute temperature arithmetic, and E_BACKEND_UNSUPPORTED unsupported storage for the requested operation. Tracked population mismatches use E_ROW_DOMAIN or E_FEATURE_SCHEMA; a transformation with no registered backward/context rule fails with E_CONTEXT_LOSS. Bounded metadata/history failures use E_RESOURCE_BUDGET. Wrong static argument types and missing imports fail aner check.

Time and space complexity

Let n be rows, p columns, r rank and b total coordinate bytes.

OperationTimeAdditional space
Validate imported coordinatesO(n log n) String comparisons plus coordinate byte inspectionO(n + b) coordinate descriptors and validation index
Exact checked arithmeticO(np + n + b)O(np) numerical output plus retained descriptor references
Explicit exact reindexingO(n log n) String comparisons plus O(np) value packingO(n + np) permutation/index and copied values
Unit conversionO(np) plus descriptor validationO(np) converted output
Gather rowsO(np) for selected outputO(np + n) selected values and coordinate descriptors
Read one scalarO(1), plus any device synchronizationO(1) readout

Axes admit at most 65,536 coordinates, with at most 1,024 bytes per label and 8 MiB coordinate bytes. Public model input facades respect the same coordinate bound even when an underlying packed batch can hold more rows.

Reindexing is a real allocation when values change order. Newly imported descriptors require validation; sharing validated descriptors can avoid repeated coordinate construction. Transfers add O(np) destination storage and actual synchronization time, independently of semantic meaning. Reported transfer/cast destination buffer bytes include the actual retained numerical buffers: CPU Float32 includes its typed buffer and widened read cache. These counts exclude the source/parent value, temporary workspace, gradients, descriptor and allocator overhead and process RSS. They are not a peak live memory measurement.

Dependencies, backends and limitations

Use Aner 0.0.4 or newer and VS Code helper 0.1.38 or newer. The station example is CPU Float64, deterministic, contains its complete dataset in source and requires no external files or service. Native CPU Float64 and local Metal/MPS Float32 semantic arithmetic were exercised in this implementation. Compatible CUDA Tensor placement is supported by the runtime, but contextual CUDA execution has not been tested on a remote GPU. Metal/MPS requires Float32; a requested unsupported precision does not silently change here.

Named axis broadcasting, general contractions, blind scientific reshape, interpolation, geographic regridding and arbitrary nonlinear unit aware differentiation remain future operations. Measurement uncertainty is opt in EvidenceTensor; ordinary semantic values do not invent uncertainty or probability.

Aner documentation · Reference and guides