Worked Examples
Develop and test temporal visualization — Visualization & Graphing
Develop and test temporal visualization — Visualization & Graphing Cross-application area: Visualization & Graphing Status: Initial scientific graphics guidance; platform-specific features not verified. Rendering contract objectiv
Application area: Visualization & Graphing
Article classification: Developer guide / Rendering contract / Software quality assurance
Audience: Scientific software engineers, frontend developers, data engineers, researchers, QA engineers, and platform maintainers
Technical level: Intermediate to advanced
Reference environment: Python 3, NumPy, pytest, and Plotly
Primary outputs: Validated rendering contract, deterministic test fixtures, automated test results, visual acceptance evidence, and release-verification record
Estimated reading time: 12–15 minutes; additional time for implementation and testing
1. Implementation objective
A temporal visualization renderer converts scientific observations or model outputs into graphical states associated with defined times.
The renderer must preserve the temporal meaning, numerical values, units, provenance, and uncertainty semantics of its input data. It must not silently create, modify, interpolate, or discard scientific observations.
The implementation should separate four responsibilities:
- Data validation: Verify the source schema, timestamps, units, values, and observation classifications.
- Temporal processing: Apply explicitly requested alignment, interpolation, aggregation, or filtering.
- Rendering: Convert validated data and processing results into graphical frames.
- Verification: Demonstrate that rendered frames correspond to the expected scientific states.
Core acceptance condition: A user must be able to distinguish actual observations from interpolated, extrapolated, simulated, and otherwise derived states.
This distinction must survive interactive rendering, animation playback, export, and publication.
2. Define the temporal rendering contract
2.1 Required input fields
A temporal rendering contract should identify the following information.
| Field | Type | Requirement |
|---|---|---|
| dataset_id | String | Stable source dataset identifier |
| dataset_version | String | Immutable or content-addressed source revision |
| timestamp | Datetime or numeric time coordinate | Unambiguous temporal coordinate |
| value | Numeric or typed measurement | Scientific value associated with a timestamp |
| unit | String | Documented measurement unit |
| status | Enumeration | Observed, interpolated, simulated, or another defined classification |
| missing_flag | Boolean or enumeration | Explicit missing-value indicator |
| uncertainty | Optional structured object | Uncertainty method, units, and bounds |
| source_object_id | String | Source record or artifact reference |
| render_config | Object | Axes, scales, colors, frame timing, and filters |
| permissions | Policy-controlled metadata | Access and export authorization context |
This table defines a proposed logical contract, not a confirmed Sustainable Catalyst database schema or API.
2.2 Suggested data-state enumeration
{
"data_status": [
"observed",
"interpolated",
"extrapolated",
"simulated",
"derived",
"missing"
]
}
These states are mutually distinguishable classifications for a specific workflow. More detailed schemas may require separate fields for data origin, processing method, observation quality, and uncertainty.
For example, a measured value that has been corrected for instrument bias may remain observation-derived while also requiring a processing-history record.
3. Establish numerical invariants
A rendering pipeline must preserve defined mathematical invariants. These invariants should be tested independently of the graphical backend.
3.1 Observation preservation
For an authoritative observation series:
O = {(t_i, y_i)}
the rendering process must preserve the original numerical values unless an explicit transformation is applied and documented.
For a lossless processing path:
y_render_input(t_i) = y_source(t_i)
For floating-point transformations where exact equality is not appropriate, numerical agreement may be tested using:
|y_result - y_reference|
<= absolute_tolerance
+ relative_tolerance * |y_reference|
Tolerances must be justified by the precision and numerical method of the specific computation. A broad tolerance should not be used merely to make a failing test pass.
3.2 Temporal ordering
For a series that requires unique, strictly increasing timestamps:
t_0 < t_1 < ... < t_n
Duplicate timestamps must be rejected or handled through an explicitly defined policy. Do not silently average, overwrite, or discard duplicate records.
3.3 Interpolation
Linear interpolation between adjacent observations is:
y(t) = y_i
+ (y_(i+1) - y_i)
* (t - t_i) / (t_(i+1) - t_i)
The result is valid only under the selected interpolation assumptions and within the defined source interval.
Interpolation must not be confused with additional measurement.
3.4 Temporal alignment error
The timestamp discrepancy between a rendered state and its intended source coordinate can be defined as:
e_t = |t_rendered - t_expected|
For exact timestamp preservation:
e_t = 0
For deliberate nearest-neighbor alignment, a bounded tolerance may be appropriate:
e_t <= alignment_tolerance
The tolerance must reflect the scientific sampling process, not merely the desired animation smoothness.
4. Implement a deterministic reference fixture
A golden fixture is a small dataset with independently known outputs. It allows developers to distinguish numerical-processing defects from visualization defects.
Use the following synthetic observations:
| Time (hours) | Value | Classification |
|---|---|---|
| 0 | 10 | Observed |
| 2 | 14 | Observed |
| 4 | 12 | Observed |
For hourly linear interpolation, the expected output is:
Time: 0 1 2 3 4
Value: 10 12 14 13 12
Status: O I O I O
O = synthetic observation
I = interpolated value
The expected result contains five temporal states, of which three correspond to synthetic observations and two are derived estimates.
5. Develop the validation module
5.1 Prepare a test environment
mkdir temporal-renderer-tests
cd temporal-renderer-tests
python3 -m venv .venv
source .venv/bin/activate
python -m pip install numpy pytest plotly
python -m pip freeze > requirements-lock.txt
Use a supported Python version and pin dependencies before release qualification. Record the actual versions used for testing.
5.2 Create the temporal processing module
Save as temporal_engine.py.
from dataclasses import dataclass
import numpy as np
@dataclass(frozen=True)
class TemporalSeries:
time: np.ndarray
values: np.ndarray
status: np.ndarray
unit: str
def validate_series(series):
t = np.asarray(series.time, dtype=float)
y = np.asarray(series.values, dtype=float)
status = np.asarray(series.status)
if t.ndim != 1 or y.ndim != 1:
raise ValueError("Expected one-dimensional arrays")
if len(t) == 0:
raise ValueError("Empty temporal series")
if not (
len(t) == len(y) == len(status)
):
raise ValueError("Array length mismatch")
if not np.isfinite(t).all():
raise ValueError("Invalid timestamps")
if not np.isfinite(y).all():
raise ValueError("Invalid numeric values")
if not np.all(np.diff(t) > 0):
raise ValueError(
"Timestamps must be strictly increasing"
)
valid_status = {
"observed",
"interpolated",
"simulated"
}
if not set(status).issubset(valid_status):
raise ValueError("Unsupported data status")
if not series.unit.strip():
raise ValueError("Missing measurement unit")
return True
def interpolate_series(series, new_time):
validate_series(series)
t = np.asarray(series.time, dtype=float)
y = np.asarray(series.values, dtype=float)
new_time = np.asarray(new_time, dtype=float)
if new_time.ndim != 1 or len(new_time) == 0:
raise ValueError("Invalid output time grid")
if not np.isfinite(new_time).all():
raise ValueError("Invalid output timestamps")
if not np.all(np.diff(new_time) > 0):
raise ValueError("Output grid must be ordered")
if new_time[0] < t[0] or new_time[-1] > t[-1]:
raise ValueError(
"Extrapolation is not permitted"
)
values = np.interp(new_time, t, y)
# Preserve the status of exact source records.
index = np.searchsorted(t, new_time)
exact = index < len(t)
exact[exact] = (
t[index[exact]] == new_time[exact]
)
statuses = np.full(
len(new_time),
"interpolated",
dtype=object
)
statuses[exact] = np.asarray(
series.status
)[index[exact]]
result = TemporalSeries(
time=new_time,
values=values,
status=statuses,
unit=series.unit
)
validate_series(result)
return result
def golden_fixture():
return TemporalSeries(
time=np.array([0., 2., 4.]),
values=np.array([10., 14., 12.]),
status=np.array([
"observed",
"observed",
"observed"
]),
unit="synthetic_units"
)
This module intentionally operates on numeric time coordinates expressed in hours. It does not implement time-zone conversion, model calendars, duplicate aggregation, missing-value interpolation, or arbitrary uncertainty propagation.
Those capabilities require additional contracts and tests rather than implicit assumptions.
6. Create automated acceptance tests
Automated tests should cover normal behavior, known reference values, malformed inputs, and conditions that could silently corrupt scientific interpretation.
6.1 Golden-fixture and negative tests
Save as test_temporal_engine.py.
import numpy as np
import pytest
from temporal_engine import (
TemporalSeries,
golden_fixture,
validate_series,
interpolate_series
)
def test_golden_fixture():
source = golden_fixture()
result = interpolate_series(
source,
np.arange(0., 5., 1.)
)
expected = np.array([
10., 12., 14., 13., 12.
])
np.testing.assert_allclose(
result.values,
expected,
rtol=0,
atol=1e-12
)
assert result.status.tolist() == [
"observed",
"interpolated",
"observed",
"interpolated",
"observed"
]
def test_original_values_preserved():
source = golden_fixture()
result = interpolate_series(
source,
source.time
)
np.testing.assert_array_equal(
source.values,
result.values
)
def test_empty_series_rejected():
series = TemporalSeries(
np.array([]),
np.array([]),
np.array([]),
"units"
)
with pytest.raises(ValueError):
validate_series(series)
def test_duplicate_timestamps_rejected():
series = TemporalSeries(
np.array([0., 1., 1.]),
np.array([2., 3., 4.]),
np.array([
"observed",
"observed",
"observed"
]),
"units"
)
with pytest.raises(ValueError):
validate_series(series)
@pytest.mark.parametrize(
"invalid",
[np.nan, np.inf, -np.inf]
)
def test_nonfinite_values_rejected(invalid):
source = golden_fixture()
values = source.values.copy()
values[1] = invalid
broken = TemporalSeries(
source.time,
values,
source.status,
source.unit
)
with pytest.raises(ValueError):
validate_series(broken)
def test_extrapolation_rejected():
source = golden_fixture()
with pytest.raises(ValueError):
interpolate_series(
source,
np.array([-1., 0., 1.])
)
def test_unsorted_grid_rejected():
source = golden_fixture()
with pytest.raises(ValueError):
interpolate_series(
source,
np.array([0., 2., 1.])
)
def test_source_not_mutated():
source = golden_fixture()
original = source.values.copy()
interpolate_series(
source,
np.arange(0., 5., 1.)
)
np.testing.assert_array_equal(
source.values,
original
)
6.2 Execute the test suite
python -m pytest -v test_temporal_engine.py
The suite contains nine test cases, including the three parameterized non-finite-value cases. All nine are expected to pass for the supplied implementation under a compatible environment.
These are expected results, not evidence that the tests have been executed against a deployed Sustainable Catalyst release.
6.3 Required additional test coverage
The reference suite is a starting point. Production acceptance should additionally cover:
- Actual timezone-aware and calendar-aware timestamps.
- Duplicate records under each approved duplicate-handling policy.
- Missing-value masks and bounded interpolation gaps.
- Extremely large and small numeric values.
- Unit conversion and dimensional consistency.
- Temporal filtering and selected time windows.
- Uncertainty-field preservation and propagation.
- Source-object identifiers and dataset revisions.
- Large datasets and memory usage.
- Renderer-to-data correspondence and export integrity.
7. Implement the rendering adapter
The scientific processing stage and rendering adapter should remain separate. The renderer consumes a validated series and produces graphical output without modifying the authoritative numerical input.
For example, Plotly’s documented animation system uses figure frames and layout configuration. Automatic axis scaling can make comparisons misleading if frame ranges are not controlled (Plotly Technologies Inc., n.d.).
7.1 Example rendering adapter
Save as render_temporal.py.
import numpy as np
import plotly.graph_objects as go
from temporal_engine import (
golden_fixture,
interpolate_series
)
source = golden_fixture()
series = interpolate_series(
source,
np.arange(0., 5., 1.)
)
observed = series.status == "observed"
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=series.time,
y=series.values,
mode="lines",
name="Interpolated trajectory"
)
)
fig.add_trace(
go.Scatter(
x=series.time[observed],
y=series.values[observed],
mode="markers",
marker={"size": 11},
name="Synthetic observations"
)
)
# Preserve a fixed quantitative reference scale.
fig.update_layout(
title="Synthetic Temporal Reference",
xaxis={
"title": "Time (hours)",
"range": [0, 4]
},
yaxis={
"title": "Value (synthetic units)",
"range": [8, 16]
}
)
fig.write_html(
"temporal-reference.html",
include_plotlyjs=True
)
This example generates a static reference chart for use in renderer comparison. It deliberately avoids animation until the numerical fixture and graphical encodings have been checked.
For an animated renderer, each frame should be generated from the validated series or a separately validated time slice. All scientific observations and derived values must retain their classifications.
8. Frame sequencing and rendering state
A temporal rendering system should explicitly model its playback state.
Recommended logical states include:
INITIALIZED
|
v
READY
|
v
PLAYING
|
+----> PAUSED
| |
| v
| PLAYING
|
v
COMPLETED
Errors should transition to a documented failure state rather than leaving the interface with an apparently valid but incomplete animation.
A renderer’s state model should support:
- Deterministic frame ordering.
- Explicit frame timestamps.
- Pause and resume operations.
- Seek and restart behavior.
- Frame-state inspection.
- Fixed quantitative scales where required.
- Predictable behavior when records are missing.
- Accessible controls and equivalent numerical content.
Playback state must not be confused with scientific data state. Pausing, seeking, or replaying must not mutate stored observations.
9. Performance and large-dataset testing
Temporal datasets may contain millions of observations or substantial multidimensional arrays.
For a dense numeric array, approximate raw storage is:
M = N * b
where:
Nis the number of numeric elements.bis the number of bytes per element.
For one million 64-bit floating-point values:
M = 1,000,000 * 8
M = 8,000,000 bytes
This is approximately 8 MB in decimal units, excluding timestamps, masks, metadata, indexes, rendering structures, and runtime overhead.
Rendering performance should be evaluated separately from numerical-processing performance.
9.1 Recommended benchmark categories
| Test | Purpose |
|---|---|
| Small fixture | Verify correctness with known outputs |
| Medium dataset | Assess ordinary interactive performance |
| Large dataset | Evaluate memory, serialization, and rendering cost |
| Long animation | Detect frame accumulation or memory leaks |
| Rapid seeking | Check frame-order integrity and responsiveness |
| Concurrent viewers | Evaluate isolation and resource usage |
| Interrupted rendering | Verify cancellation and recovery |
Performance limits should be established through measured results on the target deployment environment. Do not present arbitrary frame-rate or latency targets as verified platform capabilities.
10. Security and export controls
Scientific visualization artifacts may contain confidential values, identifying metadata, source references, and executable or active web content.
Rendering authorization and export authorization must be enforced independently where the platform’s access-control model requires it.
Potential export threats include:
- Cross-site scripting in generated HTML or SVG.
- Disclosure of private data embedded in exported figures.
- Unauthorized retrieval of source datasets.
- Untrusted external dependencies or resources.
- Exposure of internal identifiers or access tokens.
- Malicious metadata or unsafe file content.
Apply context-appropriate output encoding, safe DOM APIs, maintained sanitization where untrusted HTML is permitted, and restrictive security policies as appropriate. Input validation alone does not prevent cross-site scripting (OWASP, n.d.).
For exported HTML, review embedded JavaScript and linked assets. For SVG, inspect active content and external references before publication. Treat exported artifacts as potentially active documents rather than automatically safe images.
Exports must not include unauthorized records even when the interactive view correctly restricts access.
11. Accessibility acceptance
Temporal visualization must provide accessible mechanisms for understanding time-dependent results.
For moving content covered by WCAG 2.2 Success Criterion 2.2.2, appropriate pause, stop, or hide mechanisms are required unless an applicable exception is met (W3C, 2023).
Verify:
- Keyboard operation of playback controls.
- Visible focus indicators.
- Pause, stop, restart, and seek behavior as applicable.
- Accessible timestamp labels.
- Numerical equivalents for essential information.
- Non-color-only differentiation of observations and estimates.
- Readable legends and axis labels.
- Appropriate reduced-motion behavior.
- Static alternatives for essential temporal relationships.
Automated accessibility scanners can identify some failures, but keyboard testing, assistive-technology review, and human inspection remain necessary.
12. Visual regression and scientific acceptance
Visual regression tests compare rendered results with approved references. They are useful for detecting unexpected changes to marks, labels, color scales, layouts, and interaction states.
However, pixel-level similarity does not establish mathematical or scientific correctness.
A robust validation process should contain independent layers:
- Numerical validation: Confirm source and derived values.
- Temporal validation: Confirm timestamps, frame order, and interpolation classification.
- Structural rendering validation: Inspect plotted coordinates, marks, frame records, and renderer configuration.
- Visual regression: Compare reference screenshots under controlled rendering conditions.
- Accessibility validation: Confirm controls and equivalent content.
- Scientific review: Confirm the interpretation is supported by the model and evidence.
A changed screenshot should trigger investigation. An unchanged screenshot should not automatically pass numerical validation.
13. CI and release verification
Temporal visualization tests should run within the application development and release process.
A proposed continuous-integration workflow is:
Source code change
|
v
Static analysis and dependency checks
|
v
Schema validation
|
v
Golden-fixture numerical tests
|
v
Negative and boundary tests
|
v
Renderer structural tests
|
v
Visual and accessibility tests
|
v
Security and export checks
|
v
Release acceptance receipt
13.1 Suggested acceptance receipt
The following JSON is an illustrative record, not an official Sustainable Catalyst schema. Its statuses are intentionally unverified.
{
"contract": "temporal-renderer-v1",
"execution_status": "not_executed",
"repository": null,
"commit": null,
"renderer_version": null,
"deployment_identifier": null,
"tests": {
"schema": "not_tested",
"numerical": "not_tested",
"negative_cases": "not_tested",
"frame_sequence": "not_tested",
"visual": "not_tested",
"accessibility": "not_tested",
"security": "not_tested",
"export": "not_tested"
},
"artifacts": [],
"reviewer": null,
"release_decision": "NO_GO"
}
Populate the receipt from actual test execution and verified artifacts. A release decision must not be changed to GO merely because code has been committed or a test definition exists.
14. Source audit and deployment verification
Before certifying a Sustainable Catalyst temporal-rendering capability, identify the actual implementation and its deployed behavior.
| Evidence item | Required information |
|---|---|
| Repository | Actual owning repository and revision |
| Code path | Renderer implementation and related validation modules |
| Renderer | Installed engine, version, and backend |
| Input contract | Actual schema, validation rules, and supported data types |
| Processing | Implemented interpolation, resampling, and missing-data policies |
| API | Verified endpoint or integration contract, if applicable |
| Tests | Executed commands, results, and failure records |
| Runtime | Deployment revision and execution environment |
| Visual evidence | Screenshots and inspected output artifacts |
| Security | Export, authorization, and data-isolation results |
| Accessibility | Applicable automated and manual test evidence |
| Limitations | Known defects and unsupported behaviors |
Code presence, successful import, or a passing unit test does not by itself establish production deployment or end-to-end operational acceptance.
15. Sustainable Catalyst integration responsibilities
The following describes intended cross-application responsibilities. Actual interfaces and integration paths must be verified.
| Application | Intended responsibility |
|---|---|
| Library | Source dataset identity, version, rights, metadata, and provenance |
| Workbench | Reproducible processing, computational execution, and derived outputs where supported |
| Research Lab | Scientific validation and numerical model investigation |
| Visualization & Graphing | Rendering contracts, graphical frames, scales, and exports |
| Site Intelligence | Spatial and temporal alignment of geographic datasets where supported |
| Decision Studio | Time-dependent scenario comparisons where supported |
| Research | Validated scientific figures, methods, references, and publication evidence |
| Workspace | Ownership, testing, approvals, and release or publication decisions |
The desired architectural separation is between authoritative scientific data, reproducible transformations, renderer configuration, and publication artifacts.
16. Release acceptance matrix
| Category | Pass condition |
|---|---|
| Data integrity | Original observations and source references are preserved |
| Time integrity | Timestamp semantics and frame ordering are correct |
| Interpolation | Derived states are explicitly distinguishable |
| Units | Measurement dimensions and conversions are validated |
| Missing data | Missing values cannot silently become observations |
| Uncertainty | Uncertainty representation matches documented semantics |
| Rendering | Graphical marks match validated numerical input |
| Performance | Measured results meet defined deployment requirements |
| Accessibility | Applicable controls and alternatives pass review |
| Security | Unauthorized data access and unsafe exports are prevented |
| Reproducibility | Outputs can be regenerated from retained inputs and configuration |
| Scientific review | Conclusions remain supported by the underlying evidence |
Decision rule: Record each applicable criterion as Pass, Fail, or Not Tested. Mandatory criteria that fail or remain untested prevent certification of the affected capability.
17. Technical references
- Harris, C.R. et al. (2020). ‘Array programming with NumPy’, Nature, 585, pp. 357–362. Available at: https://doi.org/10.1038/s41586-020-2649-2.
- McKinney, W. (2010). ‘Data Structures for Statistical Computing in Python’, Proceedings of the 9th Python in Science Conference, pp. 56–61. Available at: https://doi.org/10.25080/Majora-92bf1922-00a.
- NumPy Developers (n.d.). NumPy Reference Documentation. Available at: https://numpy.org/doc/stable/.
- pytest Development Team (n.d.). pytest Documentation. Available at: https://docs.pytest.org/en/stable/.
- Plotly Technologies Inc. (n.d.). Intro to Animations in Python. Available at: https://plotly.com/python/animations/.
- OWASP Foundation (n.d.). Cross Site Scripting Prevention Cheat Sheet. Available at: OWASP Cheat Sheet Series.
- World Wide Web Consortium (W3C) (2023). Web Content Accessibility Guidelines (WCAG) 2.2. Available at: https://www.w3.org/TR/WCAG22/.
- W3C Web Accessibility Initiative (n.d.). Understanding Success Criterion 2.2.2: Pause, Stop, Hide. Available at: WCAG Understanding Document.
18. Completion and verification record
The implementation is ready for release consideration only when its source code, actual runtime behavior, and applicable acceptance evidence can be independently inspected.
Record the verified repository revision, renderer version, executed test results, configuration, artifact identifiers, source dataset versions, reviewer, outstanding defects, and release decision.
Completion criterion: The renderer must preserve numerical and temporal integrity, distinguish observed measurements from generated states, satisfy the approved security and accessibility requirements, and produce reproducible output under the verified deployment configuration.
Current implementation status: Proposed technical contract and independently executable reference code documented. No specific Sustainable Catalyst temporal renderer, animation service, API, or production feature is certified without actual source inspection, execution evidence, and release-specific acceptance.
