Nodes Catalog¶
Every node available in cuvis-ai pipelines, in one place. Built-in nodes ship
with the cuvis_ai package; plugin nodes come from separately-installable
manifests — see Plugin Development.

AnomalyBCEWithLogitscuvis_ai.node.losseslossBinary cross-entropy loss for anomaly detection with logits.
AnomalyBCEWithLogits
¶
Bases: LossNode
Binary cross-entropy loss for anomaly detection with logits.
Computes BCE loss between predicted anomaly scores and ground truth masks. Uses BCEWithLogitsLoss for numerical stability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 1.0) |
1.0
|
pos_weight
|
float
|
Weight for positive class (anomaly) to handle class imbalance (default: None) |
None
|
reduction
|
str
|
Reduction method: 'mean', 'sum', or 'none' (default: 'mean') |
'mean'
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute weighted BCE loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
Tensor
|
Predicted scores [B, H, W, 1] |
required |
targets
|
Tensor
|
Ground truth masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing scalar loss |
Source code in cuvis_ai/node/losses.py

DeepSVDDSoftBoundaryLosscuvis_ai.node.losseslossSoft-boundary Deep SVDD objective operating on BHWD embeddings.
DeepSVDDSoftBoundaryLoss
¶
Bases: LossNode
Soft-boundary Deep SVDD objective operating on BHWD embeddings.
Source code in cuvis_ai/node/losses.py
forward
¶
Compute Deep SVDD soft-boundary loss.
The loss consists of the hypersphere radius R² plus a slack penalty for points outside the hypersphere. The radius R is learned via an unconstrained parameter with softplus activation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Embedded feature representations [B, H, W, D] from the network. |
required |
center
|
Tensor
|
Center of the hypersphere [D] computed during initialization. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing the scalar loss value. |
Notes
The loss formula is: loss = weight * (R² + (1/ν) * mean(ReLU(dist - R²))) where dist is the squared distance from embeddings to the center.
Source code in cuvis_ai/node/losses.py

DistinctnessLosscuvis_ai.node.losseslossRepulsion loss encouraging different selectors to choose different bands.
DistinctnessLoss
¶
Bases: LossNode
Repulsion loss encouraging different selectors to choose different bands.
This loss is designed for band/channel selector nodes that output a
2D weight matrix [output_channels, input_channels]. It computes the
mean pairwise cosine similarity between all pairs of selector weight
vectors and penalizes high similarity:
Minimizing this loss encourages selectors to focus on different bands, preventing the common failure mode where all channels collapse onto the same band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 0.1). |
0.1
|
eps
|
float
|
Small constant for numerical stability when normalizing (default: 1e-6). |
1e-06
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute mean pairwise cosine similarity penalty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selection_weights
|
Tensor
|
Weight matrix of shape [output_channels, input_channels]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with a single key |
Source code in cuvis_ai/node/losses.py

ForegroundContrastLosscuvis_ai.node.losseslossMaximize visual separation between foreground and background mean colors.
ForegroundContrastLoss
¶
ForegroundContrastLoss(
weight=1.0,
compactness_weight=0.0,
anchor_weight=0.0,
eps=1e-06,
color_space="rgb",
assume_srgb=True,
**kwargs,
)
Bases: LossNode
Maximize visual separation between foreground and background mean colors.
Loss per image::
-||mean_fg - mean_bg||_2
+ compactness_weight * Var_fg
+ anchor_weight * (||mean_fg - mean_img||^2 + ||mean_bg - mean_img||^2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 1.0). |
1.0
|
compactness_weight
|
float
|
Weight for foreground variance penalty (default: 0.0, disabled). |
0.0
|
anchor_weight
|
float
|
Anti-gaming penalty that keeps fg/bg means near the image mean, discouraging extreme color pushes (default: 0.0, disabled). |
0.0
|
eps
|
float
|
Small constant for numerical stability in sqrt (default: 1e-6). |
1e-06
|
color_space
|
``"rgb"`` or ``"oklab"``
|
Color space in which to compute the fg/bg distance (default: |
'rgb'
|
assume_srgb
|
bool
|
When |
True
|
Notes
-
When
color_space="oklab", the OKLab conversion expects linear RGB in [0, 1]. If the upstream RGB has no sRGB gamma curve applied (e.g. output ofLearnableChannelMixerwithnormalize_output=True), setassume_srgb=False. -
Vectorized over batch.
- Fallback loss uses
0.0 * rgb.sum()so it remains connected to the model graph.
Source code in cuvis_ai/node/losses.py
forward
¶
Compute foreground/background contrast loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb
|
Tensor
|
RGB image tensor of shape [B, H, W, 3]. |
required |
mask
|
Tensor
|
Segmentation mask of shape [B, H, W] where values > 0 are foreground. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with a single key |
Source code in cuvis_ai/node/losses.py

IoULosscuvis_ai.node.losseslossDifferentiable IoU (Intersection over Union) loss.
IoULoss
¶
Bases: LossNode
Differentiable IoU (Intersection over Union) loss.
Computes: 1 - (|A ∩ B| + smooth) / (|A U B| + smooth) Works directly on continuous scores (not binary decisions), preserving gradients.
The scores are normalized to [0, 1] range using sigmoid or clamp before computing IoU, ensuring differentiability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Overall weight for this loss component (default: 1.0) |
1.0
|
smooth
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
normalize_method
|
('sigmoid', 'clamp', 'minmax')
|
Method to normalize predictions to [0, 1] range (default: "sigmoid")
|
"sigmoid"
|
Examples:
>>> iou_loss = IoULoss(weight=1.0, smooth=1e-6)
>>> # Use with anomaly scores directly (no thresholding needed)
>>> loss = iou_loss.forward(predictions=anomaly_scores, targets=ground_truth_mask)
Source code in cuvis_ai/node/losses.py
forward
¶
Compute differentiable IoU loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
|
Tensor
|
Predicted anomaly scores [B, H, W, 1] (any real values) |
required |
targets
|
Tensor
|
Ground truth binary masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing scalar IoU loss |
Source code in cuvis_ai/node/losses.py

LossNodecuvis_ai.node.losseslossBase class for loss nodes that restricts execution to training stages.
LossNode
¶
Bases: Node
Base class for loss nodes that restricts execution to training stages.
Loss nodes should not execute during inference - only during train, val, and test.
Source code in cuvis_ai/node/losses.py

MSEReconstructionLosscuvis_ai.node.losseslossMean squared error reconstruction loss.
MSEReconstructionLoss
¶
Bases: LossNode
Mean squared error reconstruction loss.
Computes MSE between reconstruction and target. Useful for autoencoder-style architectures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for this loss component (default: 1.0) |
1.0
|
reduction
|
str
|
Reduction method: 'mean', 'sum', or 'none' (default: 'mean') |
'mean'
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute MSE reconstruction loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reconstruction
|
Tensor
|
Reconstructed data |
required |
target
|
Tensor
|
Target for reconstruction |
required |
**_
|
Any
|
Additional arguments (e.g., context) - ignored but accepted for compatibility |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing scalar loss |
Source code in cuvis_ai/node/losses.py

AnomalyDetectionMetricscuvis_ai.node.metricsmetricCompute anomaly detection metrics (precision, recall, F1, etc.).
AnomalyDetectionMetrics
¶
Bases: Node
Compute anomaly detection metrics (precision, recall, F1, etc.).
Uses torchmetrics for GPU-optimized, robust metric computation. Expects binary decisions and targets to be binary masks. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute anomaly detection metrics using torchmetrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
targets
|
Tensor
|
Ground truth binary masks [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |

AnomalyPixelStatisticsMetriccuvis_ai.node.metricsmetricCompute anomaly pixel statistics from binary decisions.
AnomalyPixelStatisticsMetric
¶
Bases: Node
Compute anomaly pixel statistics from binary decisions.
Calculates total pixels, anomalous pixels count, and anomaly percentage. Useful for monitoring the proportion of detected anomalies in batches. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute anomaly pixel statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

ComponentOrthogonalityMetriccuvis_ai.node.metricsmetricTrack orthogonality of PCA components during training.
ComponentOrthogonalityMetric
¶
Bases: Node
Track orthogonality of PCA components during training.
Measures how close the component matrix is to being orthonormal. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute component orthogonality metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Tensor
|
PCA components matrix [n_components, n_features] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

ExplainedVarianceMetriccuvis_ai.node.metricsmetricTrack explained variance ratio for PCA components.
ExplainedVarianceMetric
¶
Bases: Node
Track explained variance ratio for PCA components.
Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute explained variance metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
explained_variance_ratio
|
Tensor
|
Explained variance ratios from PCA node |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

ScoreStatisticsMetriccuvis_ai.node.metricsmetricCompute statistical properties of score distributions.
ScoreStatisticsMetric
¶
Bases: Node
Compute statistical properties of score distributions.
Tracks mean, std, min, max, median, and quantiles of scores. Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute score statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Score values [B, H, W] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |

SelectorDiversityMetriccuvis_ai.node.metricsmetricTrack diversity of channel selection.
SelectorDiversityMetric
¶
Bases: Node
Track diversity of channel selection.
Measures how spread out the selection weights are across channels. Uses Gini coefficient - lower values indicate more diverse selection.
Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute diversity metrics for selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

SelectorEntropyMetriccuvis_ai.node.metricsmetricTrack entropy of channel selection distribution.
SelectorEntropyMetric
¶
Bases: Node
Track entropy of channel selection distribution.
Measures the uncertainty/diversity in channel selection weights. Higher entropy indicates more uniform selection (less confident). Lower entropy indicates more peaked selection (more confident).
Executes only during validation and test stages.
Source code in cuvis_ai/node/metrics.py
forward
¶
Compute entropy of selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "metrics" key containing list of Metric objects |
Source code in cuvis_ai/node/metrics.py

ConcreteChannelMixercuvis_ai.node.channel_mixermodelConcrete/Gumbel-Softmax channel mixer for hyperspectral cubes.
ConcreteChannelMixer
¶
ConcreteChannelMixer(
input_channels,
output_channels=3,
tau_start=10.0,
tau_end=0.1,
max_epochs=20,
use_hard_inference=True,
eps=1e-06,
**kwargs,
)
Bases: Node
Concrete/Gumbel-Softmax channel mixer for hyperspectral cubes.
Learns K categorical distributions over T input bands,
and during training uses the Gumbel-Softmax trick to produce differentiable
approximate one-hot selection weights that become increasingly peaked as the
temperature :math:\tau is annealed.
For each output channel :math:c \in {1, \dots, K}, we learn logits
L_c in R^T and sample:
The resulting weights are used to form K-channel RGB-like images:
where X is the input hyperspectral cube in [0, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_channels
|
int
|
Number of input spectral channels (e.g., 61 for hyperspectral cube). |
required |
output_channels
|
int
|
Number of output channels (default: 3 for RGB/AdaClip compatibility). |
3
|
tau_start
|
float
|
Initial temperature for Gumbel-Softmax (default: 10.0). |
10.0
|
tau_end
|
float
|
Final temperature for Gumbel-Softmax (default: 0.1). |
0.1
|
max_epochs
|
int
|
Number of epochs over which to exponentially anneal :math: |
20
|
use_hard_inference
|
bool
|
If True, uses hard argmax selection at inference/validation time (one-hot weights). If False, uses softmax over logits (default: True). |
True
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6). |
1e-06
|
Notes
-
During training (
context.stage == 'train'), the node samples Gumbel noise and uses the Concrete relaxation with the current temperature :math:`\tau(\text{epoch})``. -
During validation/test/inference, it uses deterministic weights without Gumbel noise.
-
The node exposes
selection_weightsso that repulsion penalties (e.g., DistinctnessLoss) can be attached in the pipeline.
Source code in cuvis_ai/node/channel_mixer.py
get_selection_weights
¶
Return current selection weights without data dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
deterministic
|
bool
|
If True, uses softmax over logits (no Gumbel noise) at a
"midpoint" temperature (geometric mean of start/end). If False,
uses current logits with |
True
|
Source code in cuvis_ai/node/channel_mixer.py
get_selected_bands
¶
forward
¶
Apply Concrete/Gumbel-Softmax channel mixing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C_in] in BHWC format. |
required |
context
|
Context
|
Execution context with stage and epoch information. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with:
|
Source code in cuvis_ai/node/channel_mixer.py

DeepSVDDProjectioncuvis_ai.node.anomaly.deep_svddmodelProjection head that maps per-pixel features to Deep SVDD embeddings.
DeepSVDDProjection
¶
DeepSVDDProjection(
*,
in_channels,
rep_dim=32,
hidden=128,
kernel="linear",
n_rff=2048,
gamma=None,
mlp_forward_batch_size=65536,
**kwargs,
)
Bases: Node
Projection head that maps per-pixel features to Deep SVDD embeddings.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
forward
¶
Project BHWC features into a latent embedding space.
Source code in cuvis_ai/node/anomaly/deep_svdd.py

DeepSVDDScorescuvis_ai.node.anomaly.deep_svddmodelConvert Deep SVDD embeddings + center vector into anomaly scores.
DeepSVDDScores
¶
Bases: Node
Convert Deep SVDD embeddings + center vector into anomaly scores.
forward
¶
Compute anomaly scores as squared distance from center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Deep SVDD embeddings [B, H, W, D] from projection network. |
required |
center
|
Tensor
|
Center vector [D] from DeepSVDDCenterTracker. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing squared distances [B, H, W, 1]. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py

LADGlobalcuvis_ai.node.anomaly.lad_detectormodelLaplacian Anomaly Detector (global), variant 'C' (Cauchy), port-based.
LADGlobal
¶
Bases: Node
Laplacian Anomaly Detector (global), variant 'C' (Cauchy), port-based.
This is the new cuvis.ai v3 implementation of the LAD detector. It follows the
same mathematical definition as the legacy v2 LADGlobal, but exposes a
port-based interface compatible with CuvisPipeline, StatisticalTrainer,
and GradientTrainer.
Ports
INPUT_SPECS
data : float32, shape (-1, -1, -1, -1)
Input hyperspectral cube in BHWC format.
OUTPUT_SPECS
scores : float32, shape (-1, -1, -1, 1)
Per pixel anomaly scores in BHW1 format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Small epsilon value for numerical stability in Laplacian construction. |
1e-8
|
normalize_laplacian
|
bool
|
If True, applies symmetric normalization: L = D^{-½} (D - A) D^{-½}. If False, uses unnormalized Laplacian: L = D - A. |
True
|
use_numpy_laplacian
|
bool
|
If True, constructs the Laplacian matrix using NumPy (float64, 1e-12 eps) for parity with reference implementations. If False, uses pure PyTorch. |
True
|
Training
After statistical initialization via statistical_initialization(), the node can be made trainable
by calling unfreeze(). This converts the mean M and Laplacian L buffers
to trainable nn.Parameter objects, enabling gradient-based fine-tuning.
Example
lad = LADGlobal(num_channels=61) stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule) stat_trainer.fit() # Statistical initialization lad.unfreeze() # Enable gradient training grad_trainer = GradientTrainer(pipeline=pipeline, datamodule=datamodule, ...) grad_trainer.fit() # Gradient-based fine-tuning
Source code in cuvis_ai/node/anomaly/lad_detector.py
statistical_initialization
¶
Compute global mean M and Laplacian L from a port-based input stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS.
Expected format: |
required |
Source code in cuvis_ai/node/anomaly/lad_detector.py
update
¶
Update running mean statistics from a BHWC batch.
Source code in cuvis_ai/node/anomaly/lad_detector.py
finalize
¶
Finalize mean and Laplacian from accumulated statistics.
Source code in cuvis_ai/node/anomaly/lad_detector.py
reset
¶
Reset all statistics and model parameters to initial state.
Clears the streaming mean accumulator (_mean_run), sample count (_count), global mean (M), and Laplacian matrix (L). After reset, the detector must be re-initialized via statistical_initialization() before inference.
Notes
Use this method to re-initialize the detector with different training data or when switching between different spectral distributions.
Source code in cuvis_ai/node/anomaly/lad_detector.py
forward
¶
Compute LAD anomaly scores for a BHWC cube.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with key |
Source code in cuvis_ai/node/anomaly/lad_detector.py

LearnableChannelMixercuvis_ai.node.channel_mixermodelLearnable channel mixer for hyperspectral data reduction (DRCNN-style).
LearnableChannelMixer
¶
LearnableChannelMixer(
input_channels,
output_channels,
leaky_relu_negative_slope=0.01,
use_bias=True,
use_activation=True,
normalize_output=True,
inference_normalization="batchnorm_sigmoid",
init_method="xavier",
eps=1e-06,
reduction_scheme=None,
**kwargs,
)
Bases: Node
Learnable channel mixer for hyperspectral data reduction (DRCNN-style).
This node implements a learnable linear combination layer that reduces the number of spectral channels through spectral pixel-wise 1x1 convolutions. Based on the DRCNN approach, it uses:
- 1x1 convolution (linear combination across spectral dimension)
- Leaky ReLU activation (a=0.01)
- Bias parameters
- Optional PCA-based initialization
The mixer is designed to be trained end-to-end with a downstream model (e.g., AdaClip) while keeping the downstream model frozen. This allows the mixer to learn optimal spectral combinations for the specific task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_channels
|
int
|
Number of input spectral channels (e.g., 61 for hyperspectral cube) |
required |
output_channels
|
int
|
Number of output channels (e.g., 3 for RGB compatibility) |
required |
leaky_relu_negative_slope
|
float
|
Negative slope for Leaky ReLU activation (default: 0.01, as per DRCNN paper) |
0.01
|
use_bias
|
bool
|
Whether to use bias parameters (default: True, as per DRCNN paper) |
True
|
use_activation
|
bool
|
Whether to apply Leaky ReLU activation (default: True, as per DRCNN paper) |
True
|
normalize_output
|
bool
|
Whether to apply output normalization to [0, 1] range (default: True). During training this uses BatchNorm2d + sigmoid. |
True
|
inference_normalization
|
('batchnorm_sigmoid', 'per_frame_minmax', 'sigmoid_only', 'none')
|
Inference-time normalization mode used when |
"batchnorm_sigmoid"
|
init_method
|
('xavier', 'kaiming', 'pca', 'zeros')
|
Weight initialization method (default: "xavier")
|
"xavier"
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
reduction_scheme
|
list[int] | None
|
Multi-layer reduction scheme for gradual channel reduction (default: None). If None, uses single-layer reduction (input_channels → output_channels). If provided, must start with input_channels and end with output_channels. Example: [61, 16, 8, 3] means:
|
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
conv |
Conv2d
|
1x1 convolutional layer performing spectral mixing |
activation |
LeakyReLU or None
|
Leaky ReLU activation function (if use_activation=True) |
Examples:
>>> # Create mixer: 61 channels → 3 channels (single-layer)
>>> mixer = LearnableChannelMixer(
... input_channels=61,
... output_channels=3,
... leaky_relu_negative_slope=0.01,
... init_method="xavier"
... )
>>>
>>> # Create mixer with multi-layer reduction (matches DRCNN paper)
>>> mixer = LearnableChannelMixer(
... input_channels=61,
... output_channels=3,
... reduction_scheme=[61, 16, 8, 3], # Gradual reduction
... leaky_relu_negative_slope=0.01,
... init_method="xavier"
... )
>>>
>>> # Optional: Initialize from PCA
>>> # mixer.statistical_initialization(input_stream)
>>>
>>> # Enable gradient training
>>> mixer.unfreeze()
>>>
>>> # Forward pass: [B, H, W, 61] → [B, H, W, 3]
>>> output = mixer.forward(data=hsi_cube)
>>> rgb_like = output["rgb"] # [B, H, W, 3]
Source code in cuvis_ai/node/channel_mixer.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
requires_initial_fit
property
¶
Whether this node requires statistical initialization.
statistical_initialization
¶
Initialize mixer weights from PCA components.
This method computes PCA on the input data and initializes the mixer weights to the top principal components. This provides a good starting point for gradient-based optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is [B, H, W, C_in] |
required |
Notes
This method is only used when init_method="pca". For other initialization methods, weights are set in init.
Source code in cuvis_ai/node/channel_mixer.py
freeze
¶
Disable gradient-based training of mixer weights.
unfreeze
¶
Enable gradient-based training of mixer weights.
forward
¶
Apply learnable channel mixing to input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C_in] in BHWC format |
required |
context
|
Context
|
Execution context with epoch, batch_idx, stage info |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "rgb" key containing reduced channels [B, H, W, C_out] |
Source code in cuvis_ai/node/channel_mixer.py
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 | |

RXBasecuvis_ai.node.anomaly.rx_detectormodelBase class for RX anomaly detectors.

RXGlobalcuvis_ai.node.anomaly.rx_detectormodelRX anomaly detector with global background statistics.
RXGlobal
¶
Bases: RXBase
RX anomaly detector with global background statistics.
Uses global mean (μ) and covariance (Σ) estimated from training data to compute Mahalanobis distance scores. Supports two-phase training: statistical initialization followed by optional gradient-based fine-tuning.
The detector computes anomaly scores as:
RX(x) = (x - μ)ᵀ Σ⁻¹ (x - μ)
where x is a pixel spectrum, μ is the background mean, and Σ is the covariance matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_channels
|
int
|
Number of spectral channels in input data |
required |
eps
|
float
|
Small constant added to covariance diagonal for numerical stability (default: 1e-6) |
1e-06
|
cache_inverse
|
bool
|
If True, precompute and cache Σ⁻¹ for faster inference (default: True) |
True
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
mu |
Tensor or Parameter
|
Background mean spectrum, shape (C,). Initially a buffer, becomes Parameter after unfreeze() |
cov |
Tensor or Parameter
|
Background covariance matrix, shape (C, C) |
cov_inv |
Tensor or Parameter
|
Cached pseudo-inverse of covariance (if cache_inverse=True) |
_statistically_initialized |
bool
|
Flag indicating whether statistical_initialization() has been called |
Examples:
>>> from cuvis_ai.node.anomaly.rx_detector import RXGlobal
>>> from cuvis_ai_core.training import StatisticalTrainer
>>>
>>> # Create RX detector
>>> rx = RXGlobal(num_channels=61, eps=1.0e-6)
>>>
>>> # Phase 1: Statistical initialization
>>> stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule)
>>> stat_trainer.fit() # Computes μ and Σ from training data
>>>
>>> # Inference with frozen statistics
>>> output = rx.forward(data=hyperspectral_cube)
>>> scores = output["scores"] # [B, H, W, 1]
>>>
>>> # Phase 2: Optional gradient-based fine-tuning
>>> rx.unfreeze() # Convert buffers to nn.Parameters
>>> # Now μ and Σ can be updated with gradient descent
See Also
RXPerBatch : Per-batch RX variant without training MinMaxNormalizer : Recommended preprocessing before RX ScoreToLogit : Convert scores to logits for classification docs/usecases/rx-statistical.md : Complete RX pipeline tutorial
Notes
After statistical_initialization(), mu and cov are stored as buffers (frozen by default). Call unfreeze() to convert them to trainable nn.Parameters for gradient-based optimization.
Source code in cuvis_ai/node/anomaly/rx_detector.py
statistical_initialization
¶
Initialize mu and Sigma from data iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is BHWC |
required |
Source code in cuvis_ai/node/anomaly/rx_detector.py
update
¶
Update streaming statistics with a new batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_bhwc
|
Tensor
|
Input batch in BHWC format, shape (B, H, W, C) |
required |
Source code in cuvis_ai/node/anomaly/rx_detector.py
finalize
¶
Compute final mean and covariance from accumulated streaming statistics.
This method converts the running accumulators (_mean, _M2) into the final mean (mu) and covariance (cov) matrices. The covariance is regularized with eps * I for numerical stability, and optionally caches the pseudo-inverse.
Returns:
| Type | Description |
|---|---|
RXGlobal
|
Returns self for method chaining |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 2 samples were accumulated (insufficient for covariance estimation) |
Notes
After finalization, mu and cov are stored as buffers (frozen by default). Call unfreeze() to convert them to nn.Parameters for gradient-based training.
Source code in cuvis_ai/node/anomaly/rx_detector.py
reset
¶
Reset all statistics and accumulators to empty state.
Clears mu, cov, cov_inv, and all streaming accumulators (_mean, _M2, _n). After reset, the detector must be re-initialized via statistical_initialization() before it can be used for inference.
Notes
Use this method when you need to re-initialize the detector with different training data or when switching between different dataset distributions.
Source code in cuvis_ai/node/anomaly/rx_detector.py
forward
¶
Forward pass computing anomaly scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing BHW1 anomaly scores |
Source code in cuvis_ai/node/anomaly/rx_detector.py

RXPerBatchcuvis_ai.node.anomaly.rx_detectormodelComputes μ, Σ per image in the batch on the fly; no fit/finalize.
RXPerBatch
¶
Bases: RXBase
Computes μ, Σ per image in the batch on the fly; no fit/finalize.
Source code in cuvis_ai/node/anomaly/rx_detector.py
forward
¶
Forward pass computing per-batch anomaly scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "scores" key containing BHW1 anomaly scores |
Source code in cuvis_ai/node/anomaly/rx_detector.py

SoftChannelSelectorcuvis_ai.node.channel_selectormodelSoft channel selector with temperature-based Gumbel-Softmax selection.
SoftChannelSelector
¶
SoftChannelSelector(
n_select,
input_channels,
init_method="uniform",
temperature_init=5.0,
temperature_min=0.1,
temperature_decay=0.9,
hard=False,
eps=1e-06,
**kwargs,
)
Bases: Node
Soft channel selector with temperature-based Gumbel-Softmax selection.
This is a selector node — it gates/reweights individual channels independently:
output[c] = weight[c] * input[c] (diagonal operation, preserves channel count).
For cross-channel linear projection that reduces channel count, see
:class:cuvis_ai.node.channel_mixer.ConcreteChannelMixer or
:class:cuvis_ai.node.channel_mixer.LearnableChannelMixer.
This node learns to select a subset of input channels using differentiable channel selection with temperature annealing. Supports:
- Statistical initialization (uniform or importance-based)
- Gradient-based optimization with temperature scheduling
- Entropy and diversity regularization
- Hard selection at inference time
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_select
|
int
|
Number of channels to select |
required |
input_channels
|
int
|
Number of input channels |
required |
init_method
|
('uniform', 'variance')
|
Initialization method for channel weights (default: "uniform") |
"uniform"
|
temperature_init
|
float
|
Initial temperature for Gumbel-Softmax (default: 5.0) |
5.0
|
temperature_min
|
float
|
Minimum temperature (default: 0.1) |
0.1
|
temperature_decay
|
float
|
Temperature decay factor per epoch (default: 0.9) |
0.9
|
hard
|
bool
|
If True, use hard selection at inference (default: False) |
False
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
Attributes:
| Name | Type | Description |
|---|---|---|
channel_logits |
Parameter or Tensor
|
Unnormalized channel importance scores [n_channels] |
temperature |
float
|
Current temperature for Gumbel-Softmax |
Source code in cuvis_ai/node/channel_selector.py
statistical_initialization
¶
Initialize channel selection weights from data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is BHWC |
required |
Source code in cuvis_ai/node/channel_selector.py
update_temperature
¶
Update temperature with decay schedule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Current epoch number (used for per-epoch decay) |
None
|
step
|
int
|
Current training step (for more granular control) |
None
|
Source code in cuvis_ai/node/channel_selector.py
get_selection_weights
¶
Get current channel selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hard
|
bool
|
If True, use hard selection (top-k). If None, uses self.hard. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Selection weights [n_channels] summing to n_select |
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Apply soft channel selection to input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor [B, H, W, C] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "selected" key containing reweighted channels and optional "weights" key containing selection weights |
Source code in cuvis_ai/node/channel_selector.py

SpectralAngleMappercuvis_ai.node.spectral_angle_mappermodelCompute per-pixel spectral angle against one or more reference spectra.
SpectralAngleMapper
¶
Bases: Node
Compute per-pixel spectral angle against one or more reference spectra.
Source code in cuvis_ai/node/spectral_angle_mapper.py
forward
¶
Run spectral-angle scoring for all references.
Source code in cuvis_ai/node/spectral_angle_mapper.py

SupervisedCIRSelectorcuvis_ai.node.channel_selectormodelSupervised CIR/NIR band selection with window constraints.
SupervisedCIRSelector
¶
SupervisedCIRSelector(
windows=(
(840.0, 910.0),
(650.0, 720.0),
(500.0, 570.0),
),
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: SupervisedSelectorBase
Supervised CIR/NIR band selection with window constraints.
Windows are typically set to:
- NIR: 840-910 nm
- Red: 650-720 nm
- Green: 500-570 nm
The selector chooses one band per window using a supervised score (Fisher + AUC + MI) with an mRMR-style redundancy penalty.
Source code in cuvis_ai/node/channel_selector.py

SupervisedFullSpectrumSelectorcuvis_ai.node.channel_selectormodelSupervised selection without window constraints.
SupervisedFullSpectrumSelector
¶
Bases: SupervisedSelectorBase
Supervised selection without window constraints.
Picks the top-3 discriminative bands globally with an mRMR-style redundancy penalty applied over the full spectrum.
Source code in cuvis_ai/node/channel_selector.py

SupervisedSelectorBasecuvis_ai.node.channel_selectormodelBase class for supervised band selection strategies.
SupervisedSelectorBase
¶
SupervisedSelectorBase(
num_spectral_bands,
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: ChannelSelectorBase
Base class for supervised band selection strategies.
This class adds an optional mask input port and implements common
logic for statistical initialization via :meth:fit.
The mask is assumed to be binary (0/1), where 1 denotes the positive class (e.g. stone) and 0 denotes the negative class (e.g. lentil/background).
Source code in cuvis_ai/node/channel_selector.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for supervised band selectors. |
statistical_initialization
¶
Initialize band selection using supervised scoring.
Computes Fisher, AUC, and MI scores for each band, delegates to
:meth:_select_bands for strategy-specific selection, and stores
the 3 selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with cube, mask, and wavelengths. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If band selection doesn't return exactly 3 bands. |
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Generate false-color RGB from selected bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
ndarray
|
Wavelengths for each channel [C]. |
required |
mask
|
Tensor
|
Ground truth mask (unused in forward, required for initialization). |
None
|
context
|
Context
|
Pipeline execution context (unused). |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info" metadata. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the node has not been statistically initialized. |
Source code in cuvis_ai/node/channel_selector.py

SupervisedWindowedSelectorcuvis_ai.node.channel_selectormodelSupervised band selection constrained to visible RGB windows.
SupervisedWindowedSelector
¶
SupervisedWindowedSelector(
windows=(
(440.0, 500.0),
(500.0, 580.0),
(610.0, 700.0),
),
score_weights=(1.0, 1.0, 1.0),
lambda_penalty=0.5,
**kwargs,
)
Bases: SupervisedSelectorBase
Supervised band selection constrained to visible RGB windows.
Similar to :class:HighContrastSelector, but uses label-driven scores.
Default windows:
- Blue: 440-500 nm
- Green: 500-580 nm
- Red: 610-700 nm
Source code in cuvis_ai/node/channel_selector.py

TrainablePCAcuvis_ai.node.dimensionality_reductionmodelTrainable PCA node with orthogonality regularization.
TrainablePCA
¶
Bases: PCA
Trainable PCA node with orthogonality regularization.
Source code in cuvis_ai/node/dimensionality_reduction.py
statistical_initialization
¶
Initialize PCA components from data using covariance eigen decomposition.
Source code in cuvis_ai/node/dimensionality_reduction.py
forward
¶
Project data onto statistically initialized global components.
Source code in cuvis_ai/node/dimensionality_reduction.py

OrthogonalityLosscuvis_ai.node.lossesregularizerOrthogonality regularization loss for TrainablePCA.
OrthogonalityLoss
¶
Bases: LossNode
Orthogonality regularization loss for TrainablePCA.
Encourages PCA components to remain orthonormal during training. Loss = weight * ||W @ W.T - I||^2_F
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for orthogonality loss (default: 1.0) |
1.0
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute weighted orthogonality loss from PCA components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
components
|
Tensor
|
PCA components matrix [n_components, n_features] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing weighted loss |
Source code in cuvis_ai/node/losses.py

SelectorDiversityRegularizercuvis_ai.node.lossesregularizerDiversity regularization for SoftChannelSelector.
SelectorDiversityRegularizer
¶
Bases: LossNode
Diversity regularization for SoftChannelSelector.
Encourages diverse channel selection by penalizing concentration on few channels. Uses negative variance to encourage spread (higher variance = more diverse).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for diversity regularization (default: 0.01) |
0.01
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute weighted diversity loss from selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing weighted loss |
Source code in cuvis_ai/node/losses.py

SelectorEntropyRegularizercuvis_ai.node.lossesregularizerEntropy regularization for SoftChannelSelector.
SelectorEntropyRegularizer
¶
Bases: LossNode
Entropy regularization for SoftChannelSelector.
Encourages exploration by penalizing low-entropy (over-confident) selections. Computes entropy from selection weights and applies regularization.
Higher entropy = more uniform selection (encouraged early in training) Lower entropy = more peaked selection (emerges naturally as training progresses)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
float
|
Weight for entropy regularization (default: 0.01) Positive weight encourages exploration (maximizes entropy) Negative weight encourages exploitation (minimizes entropy) |
0.01
|
target_entropy
|
float
|
Target entropy for regularization (default: None, no target) If set, uses squared error: (entropy - target)^2 |
None
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
Source code in cuvis_ai/node/losses.py
forward
¶
Compute entropy regularization loss from selection weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "loss" key containing regularization loss |
Source code in cuvis_ai/node/losses.py

CocoTrackBBoxWritercuvis_ai.node.json_filesinkWrite tracked bbox outputs into COCO tracking JSON.
CocoTrackBBoxWriter
¶
CocoTrackBBoxWriter(
output_json_path,
category_id_to_name=None,
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseCocoTrackWriter
Write tracked bbox outputs into COCO tracking JSON.
Source code in cuvis_ai/node/json_file.py
forward
¶
Store one frame of tracked bounding boxes for later export.
Source code in cuvis_ai/node/json_file.py

CocoTrackMaskWritercuvis_ai.node.json_filesinkWrite mask tracking outputs into video_coco JSON.
CocoTrackMaskWriter
¶
CocoTrackMaskWriter(
output_json_path,
default_category_name="object",
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseCocoTrackWriter
Write mask tracking outputs into video_coco JSON.
Source code in cuvis_ai/node/json_file.py
forward
¶
forward(
frame_id,
mask,
object_ids,
detection_scores,
category_ids=None,
category_semantics=None,
context=None,
**_,
)
Store one frame of tracked masks and metadata for later JSON export.
Source code in cuvis_ai/node/json_file.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |

DetectionCocoJsonNodecuvis_ai.node.json_filesinkWrite frame-wise detections into COCO detection JSON.
DetectionCocoJsonNode
¶
DetectionCocoJsonNode(
output_json_path,
category_id_to_name=None,
write_empty_frames=True,
atomic_write=True,
flush_interval=0,
**kwargs,
)
Bases: _BaseJsonWriterNode
Write frame-wise detections into COCO detection JSON.
Source code in cuvis_ai/node/json_file.py
forward
¶
Store one frame of detections for COCO JSON serialization.
Source code in cuvis_ai/node/json_file.py

NumpyFeatureWriterNodecuvis_ai.node.numpy_filesinkSave per-frame feature tensors to ``.npy`` files.
NumpyFeatureWriterNode
¶
Bases: Node
Save per-frame feature tensors to .npy files.
Writes one .npy file per frame, named
{prefix}_{frame_id:06d}.npy. Useful for offline analysis,
clustering, or evaluation of ReID embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory to write |
required |
prefix
|
str
|
Filename prefix (default |
'features'
|
Source code in cuvis_ai/node/numpy_file.py
forward
¶
Write features to a .npy file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
Tensor
|
|
required |
frame_id
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node). |
Source code in cuvis_ai/node/numpy_file.py

TensorBoardMonitorNodecuvis_ai.node.monitorsinkTensorBoard monitoring node for logging artifacts and metrics.
TensorBoardMonitorNode
¶
Bases: Node
TensorBoard monitoring node for logging artifacts and metrics.
This is a SINK node that logs visualizations (artifacts) and metrics to TensorBoard. Accepts optional inputs for artifacts and metrics, allowing predecessors to be filtered by execution_stage without causing errors.
Executes during all stages (ALWAYS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str
|
Directory for TensorBoard logs (default: "./runs") |
'./runs'
|
comment
|
str
|
Comment to append to log directory name (default: "") |
''
|
flush_secs
|
int
|
How often to flush pending events to disk (default: 120) |
120
|
Examples:
>>> heatmap_viz = AnomalyHeatmap(cmap='hot', up_to=10)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (heatmap_viz.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/monitor.py
forward
¶
Log artifacts and metrics to TensorBoard.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
Execution context with stage, epoch, batch_idx, global_step |
None
|
artifacts
|
list[Artifact]
|
List of artifacts to log (default: None) |
None
|
metrics
|
list[Metric]
|
List of metrics to log (default: None) |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node has no outputs) |
Source code in cuvis_ai/node/monitor.py
log
¶
Log a scalar value to TensorBoard.
This method provides a simple interface for external trainers to log metrics directly, complementing the port-based logging. Used by GradientTrainer to log train/val losses to the same TensorBoard directory as graph metrics and artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name/tag for the scalar (e.g., "train/loss", "val/accuracy") |
required |
value
|
float
|
Scalar value to log |
required |
step
|
int
|
Global step number |
required |
Examples:
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> # From external trainer
>>> tensorboard_node.log("train/loss", 0.5, step=100)
Source code in cuvis_ai/node/monitor.py

ToVideoNodecuvis_ai.node.videosinkWrite incoming RGB frames directly to a video file via ffmpeg.
ToVideoNode
¶
ToVideoNode(
output_video_path,
frame_rate=10.0,
frame_rotation=None,
video_codec="libx264",
bitrate="12M",
overlay_title=None,
**kwargs,
)
Bases: Node
Write incoming RGB frames directly to a video file via ffmpeg.
This node lazily starts a single ffmpeg subprocess on the first frame and
pipes raw rgb24 bytes to its stdin; ffmpeg handles encoding, bitrate
control, and muxing. close() sends EOF and waits for ffmpeg to flush the
trailer — callers must invoke it explicitly (e.g. in a finally block of
the enclosing pipeline driver) to surface encoder errors.
The ffmpeg binary is resolved via imageio_ffmpeg by default (bundled with
the wheel — no system install needed). Override with the
CUVIS_AI_FFMPEG_BIN environment variable to point at a custom build
(e.g. one with h264_nvenc / vaapi / amf hardware encoders).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_video_path
|
str
|
Output path for the generated video file (for example |
required |
frame_rate
|
float
|
Video frame rate in frames per second. Must be positive. Default is |
10.0
|
frame_rotation
|
int | None
|
Optional frame rotation in degrees. Supported values are |
None
|
video_codec
|
str
|
ffmpeg |
'libx264'
|
bitrate
|
str
|
ffmpeg |
'12M'
|
overlay_title
|
str | None
|
Optional static title rendered at the top center with its own slim
darkened background block. Default is |
None
|
Source code in cuvis_ai/node/video.py
forward
¶
Append incoming RGB frames to the configured video file.
Returns:
| Type | Description |
|---|---|
dict
|
Empty dict (sink node). |
Source code in cuvis_ai/node/video.py
close
¶
Flush EOF to ffmpeg, wait for mux, and surface any encoder errors.
Idempotent — repeated calls are no-ops. Must be called explicitly by the
pipeline driver; do not rely on __del__ for normal teardown.
Source code in cuvis_ai/node/video.py

_BaseCocoTrackWritercuvis_ai.node.json_filesinkShared tensor parsing helpers for tracking writers.
_BaseCocoTrackWriter
¶
Bases: _BaseJsonWriterNode
Shared tensor parsing helpers for tracking writers.
Source code in cuvis_ai/node/json_file.py

_BaseJsonWriterNodecuvis_ai.node.json_filesinkShared JSON write lifecycle for sink nodes.
_BaseJsonWriterNode
¶
Bases: Node
Shared JSON write lifecycle for sink nodes.
Source code in cuvis_ai/node/json_file.py

BBoxPromptcuvis_ai.node.promptssourceEmit scheduled runtime bbox prompts plus overlay-friendly debug tensors.
BBoxPrompt
¶
Bases: Node
Emit scheduled runtime bbox prompts plus overlay-friendly debug tensors.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the scheduled bbox prompt list for frame_id or an empty list.
Source code in cuvis_ai/node/prompts.py

CU3SDataNodecuvis_ai.node.datasourceGeneral-purpose data node for CU3S hyperspectral sequences.
CU3SDataNode
¶
Bases: Node
General-purpose data node for CU3S hyperspectral sequences.
This node normalizes common CU3S batch inputs for pipelines:
- converts
cubefrom uint16 to float32 - passes optional
maskthrough unchanged - extracts 1D
wavelengthsfrom batched input
forward
¶
Normalize CU3S batch data for pipeline consumption.
Source code in cuvis_ai/node/data.py

DetectionJsonReadercuvis_ai.node.json_filesourceRead COCO detection JSON and emit tensors per frame.
DetectionJsonReader
¶
Bases: Node
Read COCO detection JSON and emit tensors per frame.
Outputs per call:
- frame_id: int64 [1]
- bboxes: float32 [1, N, 4] (xyxy)
- category_ids: int64 [1, N]
- confidences: float32 [1, N]
- orig_hw: int64 [1, 2]
Source code in cuvis_ai/node/json_file.py
reset
¶
forward
¶
Emit detections for the next frame in the detection JSON stream.
Source code in cuvis_ai/node/json_file.py

LentilsAnomalyDataNodecuvis_ai.node.datasourceLentils-specific CU3S data node with binary anomaly label mapping.
LentilsAnomalyDataNode
¶
Bases: CU3SDataNode
Lentils-specific CU3S data node with binary anomaly label mapping.
Inherits shared CU3S normalization (cube + wavelengths) and additionally maps multi-class masks to binary anomaly masks.
Source code in cuvis_ai/node/data.py
forward
¶
Apply CU3S normalization and optional Lentils binary mask mapping.
Source code in cuvis_ai/node/data.py

MaskPromptcuvis_ai.node.promptssourceEmit a scheduled label-map prompt mask for the requested frame.
MaskPrompt
¶
Bases: Node
Emit a scheduled label-map prompt mask for the requested frame.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the scheduled prompt label map for frame_id or an empty mask.
Source code in cuvis_ai/node/prompts.py

NpyReadercuvis_ai.node.numpy_filesourceLoad a `.npy` file once and return the same tensor every forward call.
NpyReader
¶
Bases: Node
Load a .npy file once and return the same tensor every forward call.
Source code in cuvis_ai/node/numpy_file.py
forward
¶

TextPromptcuvis_ai.node.promptssourceEmit a runtime text prompt for the requested frame.
TextPrompt
¶
Bases: Node
Emit a runtime text prompt for the requested frame.
Source code in cuvis_ai/node/prompts.py
forward
¶
Emit the resolved prompt text for frame_id or an empty string.
Source code in cuvis_ai/node/prompts.py

TrackingResultsReadercuvis_ai.node.json_filesourceRead tracking results JSON (bbox or mask format) and emit per-frame tensors.
TrackingResultsReader
¶
Bases: Node
Read tracking results JSON (bbox or mask format) and emit per-frame tensors.
Supports two JSON formats:
-
COCO bbox tracking —
images+annotationswithbboxandtrack_idfields. Emitsbboxes,category_ids,confidences,track_ids. -
Video COCO —
videos+annotationswithsegmentationslist of RLE dicts. Emitsmasklabel map andobject_ids.
Optional outputs are None when the format doesn't provide them.
Frame synchronization: When the optional frame_id input is connected
(e.g. from CU3SDataNode.mesu_index), the reader looks up detections for
that specific frame instead of cursor-advancing. This guarantees that the
emitted bboxes/masks correspond to the same frame as the cube data. When
frame_id is not connected, the reader uses the internal cursor (legacy
behavior).
Source code in cuvis_ai/node/json_file.py
reset
¶
forward
¶
Emit tracking tensors for an explicit frame or the next cursor frame.
Source code in cuvis_ai/node/json_file.py

VideoFrameNodecuvis_ai.node.videosourcePassthrough source node that receives RGB frames from the batch.
VideoFrameNode
¶
Bases: Node
Passthrough source node that receives RGB frames from the batch.
forward
¶
Pass through RGB frames and optional frame IDs from the batch.
Source code in cuvis_ai/node/video.py

BBoxRoiCropNodecuvis_ai.node.preprocessorstransformDifferentiable bbox cropping via torchvision roi_align.
BBoxRoiCropNode
¶
Bases: Node
Differentiable bbox cropping via torchvision roi_align.
Accepts BHWC images and xyxy bboxes, outputs NCHW crops resized to a
fixed output_size. Padding rows (all coords <= 0) are filtered out,
so the output N equals the number of valid detections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_size
|
tuple[int, int]
|
Target crop size |
(256, 128)
|
aligned
|
bool
|
Use sub-pixel aligned roi_align (recommended). |
True
|
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Crop and resize bounding-box regions from images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
required |
bboxes
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in cuvis_ai/node/preprocessors.py

BBoxSpectralExtractorcuvis_ai.node.spectral_extractortransformExtract per-bbox spectral signatures with trimmed median/mean and std.
BBoxSpectralExtractor
¶
BBoxSpectralExtractor(
center_crop_scale=0.65,
min_crop_pixels=4,
trim_fraction=0.1,
l2_normalize=True,
aggregation="median",
**kwargs,
)
Bases: Node
Extract per-bbox spectral signatures with trimmed median/mean and std.
Given an HSI cube [B, H, W, C] and detection bboxes [B, N, 4]
(xyxy format), extracts a center-cropped spectral signature for each bbox.
Outputs the per-band aggregated signature, per-band std, and a binary
validity mask.
Notes
Only the first batch element (cube[0], bboxes[0]) is processed.
Outputs are always shaped [1, N, …]. Feed one frame at a time
(B == 1).
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Extract per-bbox spectral signatures. See class docstring for batch semantics.
Source code in cuvis_ai/node/spectral_extractor.py

BandpassByWavelengthcuvis_ai.node.preprocessorstransformSelect channels by wavelength interval from BHWC tensors.
BandpassByWavelength
¶
Bases: Node
Select channels by wavelength interval from BHWC tensors.
This node filters hyperspectral data by keeping only channels within a specified wavelength range. Wavelengths must be provided via the input port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_wavelength_nm
|
float
|
Minimum wavelength (inclusive) to keep, in nanometers |
required |
max_wavelength_nm
|
float | None
|
Maximum wavelength (inclusive) to keep. If None, selects all wavelengths
|
None
|
Examples:
>>> # Create bandpass node
>>> bandpass = BandpassByWavelength(
... min_wavelength_nm=500.0,
... max_wavelength_nm=700.0,
... )
>>> # Filter cube in BHWC format with wavelengths from input port
>>> wavelengths_tensor = torch.from_numpy(wavelengths).float()
>>> filtered = bandpass.forward(data=cube_bhwc, wavelengths=wavelengths_tensor)["filtered"]
>>>
>>> # For single HWC images, add a batch dimension first:
>>> # filtered = bandpass.forward(data=cube_hwc.unsqueeze(0), wavelengths=wavelengths_tensor)["filtered"]
>>>
>>> # Use with wavelengths from upstream node
>>> pipeline.connect(
... (data_node.outputs.cube, bandpass.data),
... (data_node.outputs.wavelengths, bandpass.wavelengths),
... )
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Filter cube by wavelength range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelengths tensor [C] in nanometers. |
required |
**kwargs
|
Any
|
Additional keyword arguments (unused). |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "filtered" key containing filtered cube [B, H, W, C_filtered] |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no channels are selected by the provided wavelength range |
Source code in cuvis_ai/node/preprocessors.py

BinaryAnomalyLabelMappercuvis_ai.node.labelstransformConvert multi-class segmentation masks to binary anomaly targets.
BinaryAnomalyLabelMapper
¶
Bases: Node
Convert multi-class segmentation masks to binary anomaly targets.
Masks are remapped to torch.long tensors with 0 representing normal pixels and 1 indicating anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
normal_class_ids
|
Iterable[int]
|
Class IDs that should be considered normal (default: (0, 2)). |
required |
anomaly_class_ids
|
Iterable[int] | None
|
Explicit anomaly IDs. When |
None
|
Source code in cuvis_ai/node/labels.py
forward
¶
Map multi-class labels to binary anomaly labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Features/scores to pass through [B, H, W, C] |
required |
mask
|
Tensor
|
Multi-class segmentation masks [B, H, W, 1] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "cube" (pass-through) and "mask" (binary bool) keys |
Source code in cuvis_ai/node/labels.py

BinaryDecidercuvis_ai.node.deciders.binary_decidertransformSimple decider node using a static threshold to classify data.
BinaryDecider
¶
Bases: BinaryDecider
Simple decider node using a static threshold to classify data.
Accepts logits as input, applies sigmoid transformation to convert to probabilities [0, 1], then applies threshold to produce binary decisions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
The threshold to use for classification after sigmoid. Values >= threshold are classified as anomalies (True). Default: 0.5 |
0.5
|
Examples:
>>> from cuvis_ai.node.deciders.binary_decider import BinaryDecider
>>> import torch
>>>
>>> # Create decider with default threshold
>>> decider = BinaryDecider(threshold=0.5)
>>>
>>> # Apply to RX anomaly logits
>>> logits = torch.randn(4, 256, 256, 1) # [B, H, W, C]
>>> output = decider.forward(logits=logits)
>>> decisions = output["decisions"] # [4, 256, 256, 1] boolean mask
>>>
>>> # Use in pipeline
>>> pipeline.connect(
... (logit_head.logits, decider.logits),
... (decider.decisions, visualizer.mask),
... )
See Also
QuantileBinaryDecider : Adaptive per-batch thresholding ScoreToLogit : Convert scores to logits before decisioning
Source code in cuvis_ai/node/deciders/binary_decider.py
forward
¶
Apply sigmoid and threshold-based decisioning on channels-last data.
Args: logits: Tensor shaped (B, H, W, C) containing logits.
Returns: Dictionary with "decisions" key containing (B, H, W, 1) decision mask.
Source code in cuvis_ai/node/deciders/binary_decider.py

CIETristimulusRGBSelectorcuvis_ai.node.channel_selectortransformCIE 1931 tristimulus-based RGB rendering.
CIETristimulusRGBSelector
¶
Bases: ChannelSelectorBase
CIE 1931 tristimulus-based RGB rendering.
Converts a hyperspectral cube to sRGB by integrating each pixel's spectrum with the CIE 1931 2-degree standard observer color matching functions (x_bar, y_bar, z_bar), applying a D65 white point normalization, and converting from CIE XYZ to linear sRGB.
Normalization and sRGB gamma are handled by ChannelSelectorBase (see
apply_gamma parameter inherited from the base class).
This produces a faithful (true) RGB rendering and lands closest to the distribution SAM3's Perception Encoder expects.
For wavelengths outside the visible range (approx. >780 nm), the CMFs are zero, so NIR bands do not contribute to the output.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Convert HSI cube to sRGB via CIE 1931 tristimulus integration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor | ndarray
|
Wavelength array [C] in nanometers. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info". |
Source code in cuvis_ai/node/channel_selector.py

CIRSelectorcuvis_ai.node.channel_selectortransformColor Infrared (CIR) false color composition.
CIRSelector
¶
Bases: ChannelSelectorBase
Color Infrared (CIR) false color composition.
Maps NIR to Red, Red to Green, Green to Blue for false-color composites. This is useful for highlighting vegetation and certain anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nir_nm
|
float
|
Near-infrared wavelength in nm. Default: 860.0 |
860.0
|
red_nm
|
float
|
Red wavelength in nm. Default: 670.0 |
670.0
|
green_nm
|
float
|
Green wavelength in nm. Default: 560.0 |
560.0
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Select CIR bands and compose false-color image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/channel_selector.py

CameraEmulationFalseRGBSelectorcuvis_ai.node.channel_selectortransformCamera-emulation false RGB using smooth Gaussian sensitivity curves.
CameraEmulationFalseRGBSelector
¶
CameraEmulationFalseRGBSelector(
r_peak=610.0,
g_peak=540.0,
b_peak=460.0,
r_sigma=40.0,
g_sigma=35.0,
b_sigma=30.0,
**kwargs,
)
Bases: ChannelSelectorBase
Camera-emulation false RGB using smooth Gaussian sensitivity curves.
Defines three broad, smooth Gaussian weighting curves over the spectral
bands that mimic R/G/B camera sensitivity (peaks at configurable
wavelengths). The weight matrix W is [3, num_bands], applied as
rgb = W @ spectrum. Non-negativity is enforced by construction.
This is simple, stable, and requires no training. Good middle ground between single-band selection and learned mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r_peak
|
float
|
Red channel peak wavelength in nm. Default: 610.0 |
610.0
|
g_peak
|
float
|
Green channel peak wavelength in nm. Default: 540.0 |
540.0
|
b_peak
|
float
|
Blue channel peak wavelength in nm. Default: 460.0 |
460.0
|
r_sigma
|
float
|
Red channel Gaussian sigma in nm. Default: 40.0 |
40.0
|
g_sigma
|
float
|
Green channel Gaussian sigma in nm. Default: 35.0 |
35.0
|
b_sigma
|
float
|
Blue channel Gaussian sigma in nm. Default: 30.0 |
30.0
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Convert HSI cube to false RGB using Gaussian camera sensitivity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor | ndarray
|
Wavelength array [C] in nanometers. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" [B, H, W, 3] and "band_info". |
Source code in cuvis_ai/node/channel_selector.py

ChannelNormalizeNodecuvis_ai.node.preprocessorstransformPer-channel mean/std normalization for NCHW tensors.
ChannelNormalizeNode
¶
Bases: Node
Per-channel mean/std normalization for NCHW tensors.
Defaults to ImageNet statistics but accepts any per-channel values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
tuple[float, ...]
|
Per-channel mean. |
IMAGENET_MEAN
|
std
|
tuple[float, ...]
|
Per-channel std. |
IMAGENET_STD
|
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Normalize images per channel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Tensor
|
|
required |
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in cuvis_ai/node/preprocessors.py

ChannelSelectorBasecuvis_ai.node.channel_selectortransformBase class for hyperspectral band selection strategies.
ChannelSelectorBase
¶
ChannelSelectorBase(
norm_mode=RUNNING,
apply_gamma=True,
freeze_running_bounds_after_frames=20,
running_warmup_frames=_WARMUP_FRAMES,
**kwargs,
)
Bases: Node
Base class for hyperspectral band selection strategies.
This base class defines the common input/output ports for band selection nodes and provides shared percentile-based RGB normalization (see module docstring for design rationale).
Subclasses should implement forward() and _compute_raw_rgb() (the
latter is used by statistical_initialization and _running_normalize).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
norm_mode
|
str | NormMode
|
RGB normalization mode. Default |
RUNNING
|
apply_gamma
|
bool
|
Apply sRGB gamma curve after normalization. Default |
True
|
freeze_running_bounds_after_frames
|
int | None
|
When |
20
|
running_warmup_frames
|
int
|
Number of initial |
_WARMUP_FRAMES
|
Ports
INPUT_SPECS
cube : float32, shape (-1, -1, -1, -1)
Hyperspectral cube in BHWC format.
wavelengths : float32, shape (-1,)
Wavelength array in nanometers.
OUTPUT_SPECS
rgb_image : float32, shape (-1, -1, -1, 3)
Composed RGB image in BHWC format (0-1 range).
band_info : dict
Metadata about selected bands.
Source code in cuvis_ai/node/channel_selector.py
statistical_initialization
¶
Compute global percentile bounds across the entire dataset.
Uses _compute_raw_rgb() to convert each batch, then accumulates
per-channel percentile bounds (min-of-lows, max-of-highs).
Source code in cuvis_ai/node/channel_selector.py

DecisionToMaskcuvis_ai.node.conversiontransformCombine binary decisions and identity labels into a single int32 mask.
DecisionToMask
¶
Bases: Node
Combine binary decisions and identity labels into a single int32 mask.
The output mask keeps per-pixel identity IDs where the decision is True and sets all non-matching pixels to 0.
forward
¶
Apply decisions to identities and return the final segmentation mask.
Source code in cuvis_ai/node/conversion.py

DeepSVDDCenterTrackercuvis_ai.node.anomaly.deep_svddtransformTrack and expose Deep SVDD center statistics with optional logging.
DeepSVDDCenterTracker
¶
Bases: Node
Track and expose Deep SVDD center statistics with optional logging.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for center tracking initialization. |
statistical_initialization
¶
Initialize the Deep SVDD center from training embeddings.
Computes the mean embedding across all training samples to initialize the hypersphere center.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Training data stream with embeddings [B, H, W, D]. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If no embeddings are received from the input stream. |
ValueError
|
If embedding dimensions don't match initialized rep_dim. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py
forward
¶
Track and output the Deep SVDD center with exponential moving average.
Updates the center using EMA during training (and optionally during eval), then outputs the current center and center norm metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embeddings
|
Tensor
|
Deep SVDD embeddings [B, H, W, D]. |
required |
context
|
Context
|
Execution context determining whether to update center. |
None
|
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with:
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If statistical_initialization() has not been called. |
ValueError
|
If embedding dimensions don't match initialized rep_dim. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py

FastRGBSelectorcuvis_ai.node.channel_selectortransformcuvis-next parity FastRGB renderer.
FastRGBSelector
¶
FastRGBSelector(
red_range=(580.0, 650.0),
green_range=(500.0, 580.0),
blue_range=(420.0, 500.0),
normalization_strength=0.75,
**kwargs,
)
Bases: ChannelSelectorBase
cuvis-next parity FastRGB renderer.
This selector mirrors the cuvis fast_rgb user-plugin behavior:
- Per-channel contiguous spectral range averaging.
- Dynamic per-frame normalization by global RGB mean when enabled.
- Static reflectance-style scaling when normalization is disabled.
- 8-bit quantization before returning float RGB in [0, 1].
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Render fast_rgb output with cuvis-next parity scaling.
Source code in cuvis_ai/node/channel_selector.py

FixedWavelengthSelectorcuvis_ai.node.channel_selectortransformFixed wavelength band selection (e.g., 650, 550, 450 nm).
FixedWavelengthSelector
¶
FixedWavelengthSelector(
target_wavelengths=(650.0, 550.0, 450.0),
normalize_output=True,
**kwargs,
)
Bases: ChannelSelectorBase
Fixed wavelength band selection (e.g., 650, 550, 450 nm).
Selects bands nearest to the specified target wavelengths for R, G, B channels. This is the simplest band selection strategy that produces "true color-ish" images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_wavelengths
|
tuple[float, float, float]
|
Target wavelengths for R, G, B channels in nanometers. Default: (650.0, 550.0, 450.0) |
(650.0, 550.0, 450.0)
|
normalize_output
|
bool
|
If |
True
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Select bands and compose RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/channel_selector.py

HighContrastSelectorcuvis_ai.node.channel_selectortransformData-driven band selection using spatial variance + Laplacian energy.
HighContrastSelector
¶
Bases: ChannelSelectorBase
Data-driven band selection using spatial variance + Laplacian energy.
For each wavelength window, selects the band with the highest score based on: score = variance + alpha * Laplacian_energy
This produces "high contrast" images that may work better for visual anomaly detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
windows
|
Sequence[tuple[float, float]]
|
Wavelength windows for Blue, Green, Red channels. Default: ((440, 500), (500, 580), (610, 700)) for visible spectrum. |
((440, 500), (500, 580), (610, 700))
|
alpha
|
float
|
Weight for Laplacian energy term. Default: 0.1 |
0.1
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Select high-contrast bands and compose RGB image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
wavelengths
|
Tensor
|
Wavelength array [C]. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with "rgb_image" and "band_info" keys. |
Source code in cuvis_ai/node/channel_selector.py

IdentityNormalizercuvis_ai.node.normalizationtransformNo-op normalizer; preserves incoming scores.
IdentityNormalizer
¶
Bases: _ScoreNormalizerBase
No-op normalizer; preserves incoming scores.
Source code in cuvis_ai/node/normalization.py

InsetComposercuvis_ai.node.compositingtransformPaste a fixed-size inset frame into a corner of a larger base frame.
InsetComposer
¶
InsetComposer(
corner="top-right",
margin_px=16,
border_px=2,
border_color=(1.0, 1.0, 1.0),
**kwargs,
)
Bases: Node
Paste a fixed-size inset frame into a corner of a larger base frame.
Picture-in-picture compositor. The inset is expected to already be at its
final pixel size (e.g. produced by :class:ROIZoomNode); this node only
places it onto the base, optionally with a coloured border. When
valid == 0 for a frame the base passes through untouched, so the
inset never lies about a stale ROI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corner
|
str
|
One of |
'top-right'
|
margin_px
|
int
|
Distance in pixels between the inset and the closest base edges.
Default |
16
|
border_px
|
int
|
Border thickness in pixels. |
2
|
border_color
|
tuple[float, float, float]
|
Border RGB in [0, 1]. Default white |
(1.0, 1.0, 1.0)
|
Source code in cuvis_ai/node/compositing.py

MaskRobustifiercuvis_ai.node.mask_opstransformClean a binary/labelled mask with morphology + largest-component filter.
MaskRobustifier
¶
Bases: Node
Clean a binary/labelled mask with morphology + largest-component filter.
Applies morphological opening (remove speckle), then closing (fill small
holes), optionally drops connected components below min_area pixels,
and optionally keeps only the single largest component.
Output is an int32 mask with the same spatial shape as the input; non-zero values are preserved where the original mask was non-zero and survives the cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opening_kernel
|
int
|
Side length of the square structuring element used for |
0
|
closing_kernel
|
int
|
Side length for |
3
|
min_area
|
int
|
Drop connected components with fewer than this many pixels. |
10
|
keep_largest
|
bool
|
If True, keep only the single largest surviving component. Default
|
True
|
Source code in cuvis_ai/node/mask_ops.py

MaskToBBoxKalmancuvis_ai.node.mask_opstransformMask -> bounding box with constant-velocity Kalman smoothing.
MaskToBBoxKalman
¶
MaskToBBoxKalman(
padding_fraction=0.2,
min_size_px=96,
min_hits=3,
max_predict_frames=20,
process_noise=0.01,
measurement_noise=1.0,
**kwargs,
)
Bases: Node
Mask -> bounding box with constant-velocity Kalman smoothing.
Each frame the bbox tight to the non-zero extent of the mask (with padding) is used as a measurement to update an 8-state Kalman filter (cx, cy, w, h, vx, vy, vw, vh). When the mask is empty the filter is stepped in prediction-only mode, so the downstream ROI stays pinned to a plausible location for a few frames rather than vanishing.
A warm-up of min_hits consecutive measurement frames is required
before the track is confirmed; hits during the warm-up never leak to
downstream consumers (valid=0), and a single missed frame during
warm-up resets the hit counter. This suppresses isolated false-positive
detections that would otherwise briefly pop the inset into view.
Output valid encodes track state per frame:
1- measurement used this frame on a confirmed track.2- predicted only (mask empty on a confirmed track, within budget).0- unconfirmed warm-up, no track, or post-drop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
padding_fraction
|
float
|
Fractional padding applied to the measurement bbox before it is fed
to the filter. |
0.2
|
min_size_px
|
int
|
Lower bound on the output bbox edge length (post-Kalman). Small
measurements are expanded around the centre. Default |
96
|
min_hits
|
int
|
Number of consecutive measurement frames required to confirm a new
track. Missed frames during warm-up reset the hit counter back to
zero, so transient false positives never graduate. Default |
3
|
max_predict_frames
|
int
|
After this many consecutive empty frames (on a confirmed track) the
track is dropped and subsequent empty frames emit |
20
|
process_noise
|
float
|
Scalar multiplier for the Kalman process-noise covariance. |
0.01
|
measurement_noise
|
float
|
Scalar multiplier for the Kalman measurement-noise covariance. |
1.0
|
Source code in cuvis_ai/node/mask_ops.py

MaskedMeanSpectrumcuvis_ai.node.spectral_extractortransformPer-frame mean spectrum of a hyperspectral cube over a binary mask.
MaskedMeanSpectrum
¶
Bases: Node
Per-frame mean spectrum of a hyperspectral cube over a binary mask.
For each frame, averages cube values at pixels where mask > 0 and
emits the resulting [C] spectrum. When the mask is empty for a given
frame the output is a zero vector and valid is 0.

MinMaxNormalizercuvis_ai.node.normalizationtransformMin-max normalization per sample and channel (keeps gradients).
MinMaxNormalizer
¶
Bases: _ScoreNormalizerBase
Min-max normalization per sample and channel (keeps gradients).
Scales data to [0, 1] range using (x - min) / (max - min) transformation. Can operate in two modes:
- Per-sample normalization (use_running_stats=False): min/max computed per batch
- Global normalization (use_running_stats=True): uses running statistics from statistical initialization
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eps
|
float
|
Small constant for numerical stability, prevents division by zero (default: 1e-6) |
1e-06
|
use_running_stats
|
bool
|
If True, use global min/max from statistical_initialization(). If False, compute min/max per batch during forward pass (default: True) |
True
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
running_min |
Tensor
|
Global minimum value computed during statistical initialization |
running_max |
Tensor
|
Global maximum value computed during statistical initialization |
Examples:
>>> from cuvis_ai.node.normalization import MinMaxNormalizer
>>> from cuvis_ai_core.training import StatisticalTrainer
>>> import torch
>>>
>>> # Mode 1: Global normalization with statistical initialization
>>> normalizer = MinMaxNormalizer(eps=1.0e-6, use_running_stats=True)
>>> stat_trainer = StatisticalTrainer(pipeline=pipeline, datamodule=datamodule)
>>> stat_trainer.fit() # Computes global min/max from training data
>>>
>>> # Inference uses global statistics
>>> output = normalizer.forward(data=hyperspectral_cube)
>>> normalized = output["normalized"] # [B, H, W, C], values in [0, 1]
>>>
>>> # Mode 2: Per-sample normalization (no initialization required)
>>> normalizer_local = MinMaxNormalizer(use_running_stats=False)
>>> output = normalizer_local.forward(data=hyperspectral_cube)
>>> # Each sample normalized independently using its own min/max
See Also
ZScoreNormalizer : Z-score standardization SigmoidNormalizer : Sigmoid-based normalization docs/usecases/rx-statistical.md : RX pipeline with MinMaxNormalizer
Notes
Global normalization (use_running_stats=True) is recommended for RX detectors to ensure consistent scaling between training and inference. Per-sample normalization can be useful for real-time processing when training data is unavailable.
Source code in cuvis_ai/node/normalization.py
statistical_initialization
¶
Compute global min/max from data iterator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"data": tensor} where tensor is the scores/data |
required |
Source code in cuvis_ai/node/normalization.py

NDVISelectorcuvis_ai.node.channel_selectortransformNormalized Difference Vegetation Index renderer.
NDVISelector
¶
NDVISelector(
nir_nm=827.0,
red_nm=668.0,
colormap_min=-0.7,
colormap_max=0.5,
eps=1e-06,
**kwargs,
)
Bases: _NormalizedDifferenceIndexBase
Normalized Difference Vegetation Index renderer.
Computes:
(CUBE(nir_nm) - CUBE(red_nm)) / (CUBE(nir_nm) + CUBE(red_nm))
Bands are resolved by nearest available sensor wavelength. The raw NDVI map
is returned via index_image and rgb_image contains a colour-mapped
render. The scalar NDVI image is mapped with the HSV-style colormap used
by the Blood_OXY plugin XML.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Compute NDVI plus colour-mapped RGB output.
Source code in cuvis_ai/node/channel_selector.py

OcclusionNodeBasecuvis_ai.node.occlusiontransformBase class for synthetic occlusion from tracking masks.
OcclusionNodeBase
¶
OcclusionNodeBase(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
**kwargs,
)
Bases: Node, ABC
Base class for synthetic occlusion from tracking masks.
Source code in cuvis_ai/node/occlusion.py
forward
¶
Conditionally occlude an RGB batch using tracking-derived masks.
Source code in cuvis_ai/node/occlusion.py

PCAcuvis_ai.node.dimensionality_reductiontransformProject each frame independently onto its principal components.
PCA
¶
Bases: Node
Project each frame independently onto its principal components.
Source code in cuvis_ai/node/dimensionality_reduction.py
forward
¶
Fit PCA independently on each frame and return the per-frame projection.
Source code in cuvis_ai/node/dimensionality_reduction.py

PerPixelUnitNormcuvis_ai.node.normalizationtransformPer-pixel mean-centering and L2 normalization across channels.
PerPixelUnitNorm
¶
Bases: _ScoreNormalizerBase
Per-pixel mean-centering and L2 normalization across channels.
Source code in cuvis_ai/node/normalization.py

PoissonCubeOcclusionNodecuvis_ai.node.occlusiontransformDeprecated alias of PoissonOcclusionNode with cube-only ports.
PoissonCubeOcclusionNode
¶
PoissonCubeOcclusionNode(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
fill_color="poisson",
*,
input_key=None,
max_iter=1000,
tol=1e-06,
occlusion_shape="bbox",
bbox_mode="static",
static_bbox_scale=1.2,
static_bbox_padding_px=0,
static_full_width_x=False,
**kwargs,
)
Bases: PoissonOcclusionNode
Deprecated alias of PoissonOcclusionNode with cube-only ports.
Source code in cuvis_ai/node/occlusion.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
forward
¶
Apply cube-only occlusion using the parent implementation.
Source code in cuvis_ai/node/occlusion.py

PoissonOcclusionNodecuvis_ai.node.occlusiontransformPure-PyTorch occlusion node for either RGB frames or hyperspectral cubes.
PoissonOcclusionNode
¶
PoissonOcclusionNode(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
fill_color="poisson",
*,
input_key=None,
max_iter=1000,
tol=1e-06,
occlusion_shape="bbox",
bbox_mode="static",
static_bbox_scale=1.2,
static_bbox_padding_px=0,
static_full_width_x=False,
**kwargs,
)
Bases: OcclusionNodeBase
Pure-PyTorch occlusion node for either RGB frames or hyperspectral cubes.
Source code in cuvis_ai/node/occlusion.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
forward
¶
Occlude either the provided RGB batch or cube batch for the current frame.
Source code in cuvis_ai/node/occlusion.py

QuantileBinaryDecidercuvis_ai.node.deciders.binary_decidertransformQuantile-based thresholding node operating on BHWC logits or scores.
QuantileBinaryDecider
¶
Bases: BinaryDecider
Quantile-based thresholding node operating on BHWC logits or scores.
This decider computes a tensor-valued threshold per batch item using the requested quantile over one or more non-batch dimensions, then produces a binary mask where values greater than or equal to that threshold are marked as anomalies. Useful for adaptive thresholding when score distributions vary across batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantile
|
float
|
Quantile in the closed interval [0, 1] used for the threshold computation (default: 0.995). Higher values (e.g., 0.99, 0.995) are typical for anomaly detection to capture rare events. |
0.995
|
reduce_dims
|
Sequence[int] | None
|
Axes (relative to the input tensor) over which to compute the quantile.
When |
None
|
Examples:
>>> from cuvis_ai.node.deciders.binary_decider import QuantileBinaryDecider
>>> import torch
>>>
>>> # Create quantile-based decider (99.5th percentile)
>>> decider = QuantileBinaryDecider(quantile=0.995)
>>>
>>> # Apply to anomaly scores
>>> scores = torch.randn(4, 256, 256, 1) # [B, H, W, C]
>>> output = decider.forward(logits=scores)
>>> decisions = output["decisions"] # [4, 256, 256, 1] boolean mask
>>>
>>> # Per-channel thresholding (reduce H, W only)
>>> decider_perchannel = QuantileBinaryDecider(
... quantile=0.99,
... reduce_dims=[1, 2], # Compute threshold per channel
... )
See Also
BinaryDecider : Fixed threshold decisioning
Source code in cuvis_ai/node/deciders/binary_decider.py
forward
¶
Apply quantile-based thresholding to produce binary decisions.
Computes per-batch thresholds using the specified quantile over reduce_dims, then classifies values >= threshold as anomalies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Input logits or anomaly scores, shape (B, H, W, C) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary containing:
|
Source code in cuvis_ai/node/deciders/binary_decider.py

ROIZoomNodecuvis_ai.node.compositingtransformCrop a region defined by a bbox and resize it to a fixed output frame.
ROIZoomNode
¶
Bases: Node
Crop a region defined by a bbox and resize it to a fixed output frame.
Emits one RGB frame per input frame at (zoom_height, zoom_width).
When valid is provided and equals 0 for a frame, the output is a
solid bg_color frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zoom_height
|
int
|
Output frame dimensions in pixels. Defaults 320 x 320. |
320
|
zoom_width
|
int
|
Output frame dimensions in pixels. Defaults 320 x 320. |
320
|
bg_color
|
tuple[float, float, float]
|
Background RGB (in [0, 1]) used when |
(0.0, 0.0, 0.0)
|
Source code in cuvis_ai/node/compositing.py

RangeAverageFalseRGBSelectorcuvis_ai.node.channel_selectortransformRange-based false RGB selection by averaging bands per channel.
RangeAverageFalseRGBSelector
¶
RangeAverageFalseRGBSelector(
red_range=(580.0, 650.0),
green_range=(500.0, 580.0),
blue_range=(420.0, 500.0),
**kwargs,
)
Bases: ChannelSelectorBase
Range-based false RGB selection by averaging bands per channel.
For each output channel (R/G/B), all spectral bands within the configured wavelength range are averaged per pixel. Channels with no matching bands are filled with zeros.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
red_range
|
tuple[float, float]
|
Inclusive wavelength range for red channel in nanometers. |
(580.0, 650.0)
|
green_range
|
tuple[float, float]
|
Inclusive wavelength range for green channel in nanometers. |
(500.0, 580.0)
|
blue_range
|
tuple[float, float]
|
Inclusive wavelength range for blue channel in nanometers. |
(420.0, 500.0)
|
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Average spectral bands inside RGB ranges and compose normalized RGB.
Source code in cuvis_ai/node/channel_selector.py

ScoreToLogitcuvis_ai.node.conversiontransformTrainable head that converts RX scores to anomaly logits.
ScoreToLogit
¶
Bases: Node
Trainable head that converts RX scores to anomaly logits.
This node takes RX anomaly scores (typically Mahalanobis distances) and applies a learned affine transformation to produce logits suitable for binary classification with BCEWithLogitsLoss.
The transformation is: logit = scale * (score - bias)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
init_scale
|
float
|
Initial value for the scale parameter |
1.0
|
init_bias
|
float
|
Initial value for the bias parameter (threshold) |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
scale |
Parameter or Tensor
|
Scale factor applied to scores |
bias |
Parameter or Tensor
|
Bias (threshold) subtracted from scores before scaling |
Examples:
>>> # After RX detector
>>> rx = RXGlobal(eps=1e-6)
>>> logit_head = ScoreToLogit(init_scale=1.0, init_bias=5.0)
>>> logit_head.unfreeze() # Enable gradient training
>>> graph.connect(rx.scores, logit_head.scores)
Source code in cuvis_ai/node/conversion.py
statistical_initialization
¶
Initialize bias from statistics of RX scores using streaming approach.
Uses Welford's algorithm for numerically stable online computation of mean and standard deviation, similar to RXGlobal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_stream
|
InputStream
|
Iterator yielding dicts matching INPUT_SPECS (port-based format) Expected format: {"scores": tensor} where tensor is the RX scores |
required |
Source code in cuvis_ai/node/conversion.py
update
¶
Update running statistics with a batch of scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Batch of RX scores in BHWC format |
required |
Source code in cuvis_ai/node/conversion.py
finalize
¶
Finalize statistics and set bias to mean + 2*std.
This threshold (mean + 2*std) is a common heuristic for anomaly detection, capturing ~95% of normal data under Gaussian assumption.
Source code in cuvis_ai/node/conversion.py
reset
¶
Reset all statistics and accumulators.
Source code in cuvis_ai/node/conversion.py
forward
¶
Transform RX scores to logits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Input RX scores with shape (B, H, W, 1) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "logits" key containing transformed scores |
Source code in cuvis_ai/node/conversion.py
get_threshold
¶
Get the current anomaly threshold (bias value).
Returns:
| Type | Description |
|---|---|
float
|
Current threshold value |
set_threshold
¶
Set the anomaly threshold (bias value).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
float
|
New threshold value |
required |
predict_anomalies
¶
Convert logits to binary anomaly predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits from forward pass, shape (B, H, W, 1) |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Binary predictions (0=normal, 1=anomaly), shape (B, H, W, 1) |
Source code in cuvis_ai/node/conversion.py

SigmoidNormalizercuvis_ai.node.normalizationtransformMedian-centered sigmoid squashing per sample and channel.
SigmoidNormalizer
¶
Bases: _ScoreNormalizerBase
Median-centered sigmoid squashing per sample and channel.
Applies sigmoid transformation centered at the median with standard deviation scaling:
sigmoid((x - median) / std)
Produces values in [0, 1] range with median mapped to 0.5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
std_floor
|
float
|
Minimum standard deviation threshold to prevent division by zero (default: 1e-6) |
1e-06
|
**kwargs
|
dict
|
Additional arguments passed to Node base class |
{}
|
Examples:
>>> from cuvis_ai.node.normalization import SigmoidNormalizer
>>> import torch
>>>
>>> # Create sigmoid normalizer
>>> normalizer = SigmoidNormalizer(std_floor=1.0e-6)
>>>
>>> # Apply to hyperspectral data
>>> data = torch.randn(4, 256, 256, 61) # [B, H, W, C]
>>> output = normalizer.forward(data=data)
>>> normalized = output["normalized"] # [4, 256, 256, 61], values in [0, 1]
See Also
MinMaxNormalizer : Min-max scaling to [0, 1] ZScoreNormalizer : Z-score standardization
Notes
Sigmoid normalization is robust to outliers because extreme values are squashed asymptotically to 0 or 1. This makes it suitable for data with heavy-tailed distributions or sporadic anomalies.
Source code in cuvis_ai/node/normalization.py

SigmoidTransformcuvis_ai.node.normalizationtransformApplies sigmoid transformation to convert logits to probabilities [0,1].
SigmoidTransform
¶
Bases: Node
Applies sigmoid transformation to convert logits to probabilities [0,1].
General-purpose sigmoid node for converting raw scores/logits to probability space. Useful for visualization or downstream nodes that expect bounded [0,1] values.
Examples:
>>> sigmoid = SigmoidTransform()
>>> # Route logits to both loss (raw) and visualization (sigmoid)
>>> graph.connect(
... (rx.scores, loss_node.predictions), # Raw logits to loss
... (rx.scores, sigmoid.data), # Logits to sigmoid
... (sigmoid.transformed, viz.scores), # Probabilities to viz
... )
Source code in cuvis_ai/node/normalization.py
forward
¶
Apply sigmoid transformation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "transformed" key containing sigmoid output |
Source code in cuvis_ai/node/normalization.py

SolidOcclusionNodecuvis_ai.node.occlusiontransformDeprecated alias of PoissonOcclusionNode.
SolidOcclusionNode
¶
SolidOcclusionNode(
tracking_json_path,
track_ids,
occlusion_start_frame,
occlusion_end_frame,
fill_color="poisson",
*,
input_key=None,
max_iter=1000,
tol=1e-06,
occlusion_shape="bbox",
bbox_mode="static",
static_bbox_scale=1.2,
static_bbox_padding_px=0,
static_full_width_x=False,
**kwargs,
)
Bases: PoissonOcclusionNode
Deprecated alias of PoissonOcclusionNode.
Source code in cuvis_ai/node/occlusion.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |

SpatialRotateNodecuvis_ai.node.preprocessorstransformRotate spatial dimensions of cubes, masks, and RGB images.
SpatialRotateNode
¶
Bases: Node
Rotate spatial dimensions of cubes, masks, and RGB images.
Applies a fixed rotation (90, -90, or 180 degrees) to the H and W dimensions of all provided inputs. Wavelengths pass through unchanged.
Place immediately after a data node so all downstream consumers see correctly oriented data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rotation
|
int | None
|
Rotation in degrees. Supported: 90, -90, 180 (and aliases 270, -270, -180). None or 0 means passthrough. |
None
|
Source code in cuvis_ai/node/preprocessors.py
forward
¶
Apply the configured rotation to the cube, mask, and rgb_image tensors.
Source code in cuvis_ai/node/preprocessors.py

SpectralSignatureExtractorcuvis_ai.node.spectral_extractortransformExtract per-object spectral signatures from SAM-style label masks.
SpectralSignatureExtractor
¶
SpectralSignatureExtractor(
trim_fraction=0.1,
min_mask_pixels=10,
zero_norm_threshold=1e-08,
**kwargs,
)
Bases: Node
Extract per-object spectral signatures from SAM-style label masks.
Notes
Only the first batch element of cube is processed; mask is required
to be [1, H, W] by INPUT_SPECS. Outputs are always shaped
[1, N, C]. Feed one frame at a time.
Source code in cuvis_ai/node/spectral_extractor.py
forward
¶
Extract per-object signatures. See class docstring for batch semantics.
Source code in cuvis_ai/node/spectral_extractor.py

TopKIndicescuvis_ai.node.channel_selectortransformUtility node that surfaces the top-k channel indices from selector weights.
TopKIndices
¶
Bases: Node
Utility node that surfaces the top-k channel indices from selector weights.
This node extracts the indices of the top-k weighted channels from a selector's weight vector. Useful for introspection and reporting which channels were selected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of top indices to return |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
k |
int
|
Number of top indices to return |
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Return the indices of the top-k weighted channels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Channel selection weights [n_channels] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "indices" key containing top-k indices |
Source code in cuvis_ai/node/channel_selector.py

TwoStageBinaryDecidercuvis_ai.node.deciders.two_stage_decidertransformTwo-stage binary decider: image-level gate + pixel quantile mask.
TwoStageBinaryDecider
¶
TwoStageBinaryDecider(
image_threshold=0.5,
top_k_fraction=0.001,
quantile=0.995,
reduce_dims=None,
**kwargs,
)
Bases: BinaryDecider
Two-stage binary decider: image-level gate + pixel quantile mask.
Source code in cuvis_ai/node/deciders/two_stage_decider.py
forward
¶
Apply two-stage binary decision: image-level gate + pixel quantile.
Stage 1: Compute image-level anomaly score from top-k pixel scores. If below threshold, return blank mask (no anomalies).
Stage 2: For images passing the gate, apply pixel-level quantile thresholding to create binary anomaly mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Anomaly scores [B, H, W, C] or [B, H, W, 1]. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "decisions" key containing binary masks [B, H, W, 1]. |
Notes
The image-level score is computed as the mean of the top-k% highest pixel scores. For multi-channel inputs, the max across channels is used for each pixel.
Source code in cuvis_ai/node/deciders/two_stage_decider.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |

ZScoreNormalizercuvis_ai.node.normalizationtransformZ-score (standardization) normalization along specified dimensions.
ZScoreNormalizer
¶
Bases: _ScoreNormalizerBase
Z-score (standardization) normalization along specified dimensions.
Computes: (x - mean) / (std + eps) along specified dims. Per-sample normalization with no statistical initialization required.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
list[int]
|
Dimensions to compute statistics over (default: [1,2] for H,W in BHWC format) |
None
|
eps
|
float
|
Small constant for numerical stability (default: 1e-6) |
1e-06
|
keepdim
|
bool
|
Whether to keep reduced dimensions (default: True) |
True
|
Examples:
>>> # Normalize over spatial dimensions (H, W)
>>> zscore = ZScoreNormalizer(dims=[1, 2])
>>>
>>> # Normalize over all spatial and channel dimensions
>>> zscore_all = ZScoreNormalizer(dims=[1, 2, 3])
Source code in cuvis_ai/node/normalization.py

ZScoreNormalizerGlobalcuvis_ai.node.anomaly.deep_svddtransformPort-based Deep SVDD z-score normalizer for BHWC cubes.
ZScoreNormalizerGlobal
¶
Bases: Node
Port-based Deep SVDD z-score normalizer for BHWC cubes.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
requires_initial_fit
property
¶
Whether this node requires statistical initialization from training data.
Returns:
| Type | Description |
|---|---|
bool
|
Always True for Z-score normalization. |
statistical_initialization
¶
Estimate per-band z-score statistics from the provided stream.
Source code in cuvis_ai/node/anomaly/deep_svdd.py
forward
¶
Apply per-channel Z-score normalization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input feature tensor [B, H, W, C]. |
required |
**_
|
Any
|
Additional unused keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "normalized" key containing Z-score normalized data [B, H, W, C]. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If statistical_initialization() has not been called. |
ValueError
|
If input channel count doesn't match initialized num_channels. |
Source code in cuvis_ai/node/anomaly/deep_svdd.py

_NormalizedDifferenceIndexBasecuvis_ai.node.channel_selectortransformAbstract base for two-band normalized-difference indices.
_NormalizedDifferenceIndexBase
¶
Bases: ChannelSelectorBase, ABC
Abstract base for two-band normalized-difference indices.
Subclasses define the semantic labels and strategy name, while this base handles nearest-band resolution, stable normalized-difference computation, and delegates RGB rendering to subclasses.
Source code in cuvis_ai/node/channel_selector.py
forward
¶
Compute raw index image plus RGB render.
Source code in cuvis_ai/node/channel_selector.py

_ScoreNormalizerBasecuvis_ai.node.normalizationtransformBase class for differentiable score normalizers operating on BHWC tensors.
_ScoreNormalizerBase
¶
Bases: Node
Base class for differentiable score normalizers operating on BHWC tensors.
Notes
All normalization nodes in this module expect inputs in BHWC format
([batch, height, width, channels]). Callers are responsible for adding
a batch dimension when working with HWC tensors (use x.unsqueeze(0)).
Source code in cuvis_ai/node/normalization.py
forward
¶
Normalize input data (BHWC only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
Input tensor in BHWC format [B, H, W, C] |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
Dictionary with "normalized" key containing normalized tensor |
Source code in cuvis_ai/node/normalization.py

AnomalyMaskcuvis_ai.node.anomaly_visualizationvisualizerVisualize anomaly detection with GT and predicted masks.
AnomalyMask
¶
Bases: Node
Visualize anomaly detection with GT and predicted masks.
Creates side-by-side visualizations showing ground truth masks, predicted masks, and overlay comparisons on hyperspectral cube images. The overlay shows:
- Green: True Positives (correct anomaly detection)
- Red: False Positives (false alarms)
- Yellow: False Negatives (missed anomalies)
Also displays IoU and other metrics. Returns a list of Artifact objects for logging to monitoring systems.
Executes during validation and inference stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
channel
|
int
|
Channel index to use for cube visualization (required) |
required |
up_to
|
int
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> decider = BinaryDecider(threshold=0.2)
>>> viz_mask = AnomalyMask(channel=30, up_to=5)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (logit_head.logits, decider.data),
... (decider.decisions, viz_mask.decisions),
... (data_node.mask, viz_mask.mask),
... (data_node.cube, viz_mask.cube),
... (viz_mask.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Create anomaly mask visualizations with GT/pred comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
mask
|
Tensor | None
|
Ground truth anomaly mask [B, H, W, 1] (optional) |
None
|
cube
|
Tensor
|
Original cube [B, H, W, C] for visualization |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/anomaly_visualization.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |

BBoxesOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerTorch-only bounding-box overlay renderer for YOLO-style detections.
BBoxesOverlayNode
¶
BBoxesOverlayNode(
line_thickness=2,
draw_labels=False,
draw_sparklines=False,
sparkline_height=24,
hide_untracked=False,
**kwargs,
)
Bases: Node
Torch-only bounding-box overlay renderer for YOLO-style detections.
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
forward(
rgb_image,
bboxes,
category_ids,
frame_id=None,
confidences=None,
spectral_signatures=None,
**_,
)
Overlay bbox edges with deterministic per-class colors.
Source code in cuvis_ai/node/anomaly_visualization.py

ChannelSelectorFalseRGBVizcuvis_ai.node.anomaly_visualizationvisualizerVisualize false RGB output from channel selectors with optional mask overlay.
ChannelSelectorFalseRGBViz
¶
ChannelSelectorFalseRGBViz(
mask_overlay_alpha=0.4,
max_samples=4,
log_every_n_batches=1,
**kwargs,
)
Bases: ImageArtifactVizBase
Visualize false RGB output from channel selectors with optional mask overlay.
Produces per-sample image artifacts:
false_rgb_sample_{b}: Normalized false RGB image [H, W, 3]mask_overlay_sample_{b}: False RGB with red alpha-blend on foreground pixels (if mask provided)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_overlay_alpha
|
float
|
Alpha value for red mask overlay on foreground pixels (default: 0.4). |
0.4
|
max_samples
|
int
|
Maximum number of batch elements to visualize (default: 4). |
4
|
log_every_n_batches
|
int
|
Log every N-th batch (default: 1). |
1
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Generate false RGB and mask overlay artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb_output
|
Tensor
|
False RGB tensor [B, H, W, 3]. |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx. |
required |
mask
|
Tensor | None
|
Optional segmentation mask [B, H, W]. |
None
|
mesu_index
|
Tensor | None
|
Optional measurement indices [B] for frame-identified artifact naming. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing image artifacts. |
Source code in cuvis_ai/node/anomaly_visualization.py

ChannelWeightsVizcuvis_ai.node.anomaly_visualizationvisualizerVisualize channel mixer weights as a heatmap.
ChannelWeightsViz
¶
Bases: ImageArtifactVizBase
Visualize channel mixer weights as a heatmap.
Produces a [K, C] mixing matrix heatmap with output channels on the
y-axis and input channels on the x-axis. Uses a diverging blue-white-red
colormap centred at zero so positive/negative contributions are immediately
visible.
Implemented in pure PyTorch (no matplotlib) so it adds negligible overhead to the training loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_samples
|
int
|
Ignored (weights are per-model, not per-sample). Kept for base class compatibility. Default: 1. |
1
|
log_every_n_batches
|
int
|
Log every N-th batch (default: 1). |
1
|
cell_height
|
int
|
Pixel height per matrix row (default: 40). |
60
|
cell_width
|
int
|
Pixel width per matrix column (default: 6). |
12
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Generate mixing matrix heatmap artifact.
Pure-torch rendering with R/G/B indicator bars, grid lines, and a diverging colorbar — no matplotlib for training-loop speed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
Tensor
|
Mixing matrix |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx. |
required |
wavelengths
|
ndarray
|
Wavelengths |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with |
Source code in cuvis_ai/node/anomaly_visualization.py
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 | |

CubeRGBVisualizercuvis_ai.node.pipeline_visualizationvisualizerCreates false-color RGB images from hyperspectral cube using channel weights.
CubeRGBVisualizer
¶
Bases: Node
Creates false-color RGB images from hyperspectral cube using channel weights.
Selects 3 channels with highest weights for R, G, B channels and creates a false-color visualization with wavelength annotations.
Source code in cuvis_ai/node/pipeline_visualization.py
forward
¶
Generate false-color RGB visualizations from hyperspectral cube.
Selects the 3 channels with highest weights and creates RGB images with wavelength annotations. Also generates a bar chart showing channel weights with the selected channels highlighted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cube
|
Tensor
|
Hyperspectral cube [B, H, W, C]. |
required |
weights
|
Tensor
|
Channel selection weights [C] indicating importance of each channel. |
required |
wavelengths
|
Tensor
|
Wavelengths for each channel [C] in nanometers. |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx information. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of visualization artifacts. |
Source code in cuvis_ai/node/pipeline_visualization.py

ImageArtifactVizBasecuvis_ai.node.anomaly_visualizationvisualizerBase class for visualization nodes that produce image artifacts.
ImageArtifactVizBase
¶
Bases: Node
Base class for visualization nodes that produce image artifacts.
Source code in cuvis_ai/node/anomaly_visualization.py

MaskOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerAlpha-blend a coloured mask overlay onto RGB frames.
MaskOverlayNode
¶
Bases: Node
Alpha-blend a coloured mask overlay onto RGB frames.
Pure PyTorch processing node (no matplotlib, no gradients). When mask is
None or entirely zero the input RGB is passed through unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Blend factor for the overlay colour (default: 0.4). |
0.4
|
overlay_color
|
tuple[float, float, float]
|
RGB overlay colour in [0, 1] (default: red |
(1.0, 0.0, 0.0)
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Apply mask overlay to RGB frames.
Source code in cuvis_ai/node/anomaly_visualization.py

PCAVisualizationcuvis_ai.node.pipeline_visualizationvisualizerVisualize PCA-projected data with scatter and image plots.
PCAVisualization
¶
Bases: Node
Visualize PCA-projected data with scatter and image plots.
Creates visualizations for each batch element showing:
- Scatter plot of H*W points in 2D PC space (using first 2 PCs)
- Image representation of the 2D projection reshaped to [H, W, 2]
Points in scatter plot are colored by spatial position. Returns artifacts for monitoring systems.
Executes only during validation stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int
|
Maximum number of batch elements to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> pca_viz = PCAVisualization(up_to=10)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (pca.projected, pca_viz.data),
... (pca_viz.artifacts, tensorboard_node.artifacts),
... )
Source code in cuvis_ai/node/pipeline_visualization.py
forward
¶
Create PCA projection visualizations as Artifact objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Tensor
|
PCA-projected data tensor [B, H, W, C] (uses first 2 components) |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/pipeline_visualization.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | |

PipelineComparisonVisualizercuvis_ai.node.pipeline_visualizationvisualizerTensorBoard visualization node for comparing pipeline stages.
PipelineComparisonVisualizer
¶
Bases: Node
TensorBoard visualization node for comparing pipeline stages.
Creates image artifacts for logging to TensorBoard:
- Input HSI cube visualization (false-color RGB from selected channels)
- Mixer output (3-channel RGB-like image that downstream model sees)
- Ground truth anomaly mask
- Anomaly scores (as heatmap)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsi_channels
|
list[int]
|
Channel indices to use for false-color RGB visualization of HSI input (default: [0, 20, 40] for a simple false-color representation) |
None
|
max_samples
|
int
|
Maximum number of samples to log per batch (default: 4) |
4
|
log_every_n_batches
|
int
|
Log images every N batches to reduce TensorBoard size (default: 1, log every batch) |
1
|
Source code in cuvis_ai/node/pipeline_visualization.py
forward
¶
Create image artifacts for TensorBoard logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hsi_cube
|
Tensor
|
Input HSI cube [B, H, W, C] |
required |
mixer_output
|
Tensor
|
Mixer output (RGB-like) [B, H, W, 3] |
required |
ground_truth_mask
|
Tensor
|
Ground truth anomaly mask [B, H, W, 1] |
required |
anomaly_scores
|
Tensor
|
Anomaly scores [B, H, W, 1] |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx info |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/pipeline_visualization.py
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |

RGBAnomalyMaskcuvis_ai.node.anomaly_visualizationvisualizerVisualize anomaly detection with GT and predicted masks on RGB images.
RGBAnomalyMask
¶
Bases: Node
Visualize anomaly detection with GT and predicted masks on RGB images.
Similar to AnomalyMask but designed for RGB images (e.g., from band selectors). Creates side-by-side visualizations showing ground truth masks, predicted masks, and overlay comparisons on RGB images. The overlay shows:
- Green: True Positives (correct anomaly detection)
- Red: False Positives (false alarms)
- Yellow: False Negatives (missed anomalies)
Also displays IoU and other metrics. Returns a list of Artifact objects for logging to monitoring systems.
Executes during validation and inference stages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Examples:
>>> decider = BinaryDecider(threshold=0.2)
>>> viz_mask = RGBAnomalyMask(up_to=5)
>>> tensorboard_node = TensorBoardMonitorNode(output_dir="./runs")
>>> graph.connect(
... (decider.decisions, viz_mask.decisions),
... (data_node.mask, viz_mask.mask),
... (band_selector.rgb_image, viz_mask.rgb_image),
... (viz_mask.artifacts, tensorboard_node.artifacts),
... )
Initialize RGBAnomalyMask visualizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
up_to
|
int | None
|
Maximum number of images to visualize. If None, visualizes all (default: None) |
None
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Create anomaly mask visualizations with GT/pred comparison on RGB images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
decisions
|
Tensor
|
Binary anomaly decisions [B, H, W, 1] |
required |
rgb_image
|
Tensor
|
RGB image [B, H, W, 3] for visualization |
required |
mask
|
Tensor | None
|
Ground truth anomaly mask [B, H, W, 1] (optional) |
None
|
context
|
Context | None
|
Execution context with stage, epoch, batch_idx |
None
|
scores
|
Tensor | None
|
Optional anomaly logits/scores [B, H, W, 1] |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with "artifacts" key containing list of Artifact objects |
Source code in cuvis_ai/node/anomaly_visualization.py
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 | |

ScalarHSVColormapNodecuvis_ai.node.colormapvisualizerMap a scalar BHWC image to RGB using an HSV colormap.
ScalarHSVColormapNode
¶
Bases: Node
Map a scalar BHWC image to RGB using an HSV colormap.
Source code in cuvis_ai/node/colormap.py
forward
¶
Colorize a scalar image in BHWC format.
Source code in cuvis_ai/node/colormap.py

ScoreHeatmapVisualizercuvis_ai.node.anomaly_visualizationvisualizerLog LAD/RX score heatmaps as TensorBoard artifacts.
ScoreHeatmapVisualizer
¶
Bases: Node
Log LAD/RX score heatmaps as TensorBoard artifacts.
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Generate heatmap visualizations of anomaly scores.
Creates color-mapped heatmaps of anomaly scores for visualization in TensorBoard. Optionally normalizes scores to [0, 1] range for consistent visualization across batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Tensor
|
Anomaly scores [B, H, W, 1] from detection nodes (e.g., RX, LAD). |
required |
context
|
Context
|
Execution context with stage, epoch, batch_idx information. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[Artifact]]
|
Dictionary with "artifacts" key containing list of heatmap artifacts. |
Source code in cuvis_ai/node/anomaly_visualization.py

SpectrumPlotNodecuvis_ai.node.spectrum_plotvisualizerRender a per-frame line plot of tracked vs reference spectrum.
SpectrumPlotNode
¶
SpectrumPlotNode(
wavelengths,
reference_wavelengths,
plot_width=960,
plot_height=720,
dpi=150,
xlabel="wavelength in [nm]",
ylabel="spectral radiance in [W/m²/sr/µm]",
tracked_label="",
reference_label="",
tracked_color="red",
reference_color="lime",
bg_color="black",
fg_color="white",
y_fixed_range=(0.0, 12.0),
y_num_ticks=12,
tracked_hold_frames=15,
**kwargs,
)
Bases: Node
Render a per-frame line plot of tracked vs reference spectrum.
The tracked line is plotted against wavelengths (typically the full
cube grid), while the reference line is plotted against
reference_wavelengths (typically the narrower bandpass subset where
the SAM reference is defined). Both are drawn on a single axes with a
fixed x-range so the axis does not re-scale from frame to frame.
Output shape is fixed to (plot_height, plot_width) so downstream
ToVideoNode gets consistent frame dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wavelengths
|
ndarray
|
Full wavelength grid in nm, shape |
required |
reference_wavelengths
|
ndarray
|
Wavelength grid for the reference line in nm, shape |
required |
plot_width
|
int
|
Pixel dimensions of the rendered frame. Default 960 x 720. |
960
|
plot_height
|
int
|
Pixel dimensions of the rendered frame. Default 960 x 720. |
960
|
dpi
|
int
|
Figure dpi. Default 150. |
150
|
xlabel
|
str
|
Axis labels. |
'wavelength in [nm]'
|
ylabel
|
str
|
Axis labels. |
'wavelength in [nm]'
|
tracked_label
|
str
|
Legend labels. |
''
|
reference_label
|
str
|
Legend labels. |
''
|
tracked_color
|
str
|
Matplotlib colour specs for the two lines. |
'red'
|
reference_color
|
str
|
Matplotlib colour specs for the two lines. |
'red'
|
bg_color
|
str
|
Background / foreground colours. |
'black'
|
fg_color
|
str
|
Background / foreground colours. |
'black'
|
y_fixed_range
|
tuple[float, float] | None
|
If set, fixes the y-axis range. Otherwise auto-scales per-frame on the union of tracked+reference values, with a small headroom. |
(0.0, 12.0)
|
y_num_ticks
|
int
|
When |
12
|
tracked_hold_frames
|
int
|
When |
15
|
Source code in cuvis_ai/node/spectrum_plot.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |

TrackingOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerAlpha-blend per-object coloured masks onto RGB frames.
TrackingOverlayNode
¶
Bases: Node
Alpha-blend per-object coloured masks onto RGB frames.
Converts a SAM3-style label map (mask) into per-object binary masks and
renders a coloured overlay with optional contour lines and object-ID labels
using :func:cuvis_ai.utils.torch_draw.overlay_instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Blend factor for the overlay colour (default 0.4). |
0.4
|
draw_contours
|
bool
|
Draw contour outlines on mask edges (default True). |
True
|
draw_ids
|
bool
|
Render numeric object-ID labels above each mask (default True). |
True
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Render coloured per-object mask overlays onto rgb_image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rgb_image
|
Tensor
|
Single RGB frame |
required |
mask
|
Tensor
|
SAM3 label map |
required |
object_ids
|
Tensor or None
|
Active object IDs |
None
|
frame_id
|
Tensor or None
|
Frame / measurement index |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Source code in cuvis_ai/node/anomaly_visualization.py
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 | |

TrackingPointerOverlayNodecuvis_ai.node.anomaly_visualizationvisualizerDraw downward triangle pointers for all tracked objects.
TrackingPointerOverlayNode
¶
Bases: Node
Draw downward triangle pointers for all tracked objects.
The node is composable by design: it renders only the pointer markers on top
of an incoming RGB frame and does not perform any mask tinting itself.
Colours are derived from object IDs using the same palette as
:class:TrackingOverlayNode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Reserved for API compatibility with :class: |
0.4
|
draw_contours
|
bool
|
Reserved for API compatibility with :class: |
True
|
draw_ids
|
bool
|
Reserved for API compatibility with :class: |
True
|
Source code in cuvis_ai/node/anomaly_visualization.py
forward
¶
Render pointer overlays for all objects onto rgb_image.
Source code in cuvis_ai/node/anomaly_visualization.py
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 | |