Skip to content
HPSCILPublic

About

Official code for MSTAS: A Multi-Pattern Spatiotemporal Adaptive Sampling Method for Environmental Sensor Placement

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MSTAS Unified Algorithm Package

This package integrates raw daily and monthly NetCDF processing, spatial regionalization, regional Gaussian processes (GPs), sequential sensor placement, and common evaluation. PM2.5 and NO2 share the algorithm and use separate configurations. Production settings default to 5,000 independent runs per sensor budget, with Windows multiprocessing, per-run checkpoints, and resuming.

Quick start

Use Python 3.10 or later in an isolated environment:

python -m venv .venv
.\.venv\Scripts\python -m pip install -r requirements.txt
.\.venv\Scripts\python make_demo.py
.\.venv\Scripts\python run_mstas.py --config configs/demo.yaml

The demonstration generates synthetic NC inputs and performs three runs per budget to check the complete workflow. It does not read production pollutant data.

Before production use, edit configs/pm25.yaml or configs/no2.yaml:

data:
  daily:
    path: 'D:/your-data/pm25/daily/*.nc'
    variable: PM2.5
    x: lon
    y: lat
    time: time
    crs: EPSG:4326
    unit: 'ug m-3'
  monthly:
    path: 'D:/your-data/pm25/monthly/*.nc'
    variable: PM2.5
    x: lon
    y: lat
    time: time
    crs: EPSG:4326
    unit: 'ug m-3'
execution:
  runs: 5000
  workers: 4

Paths, variable names, and units must match the actual NC files. Supplied NC settings are templates, not verified connections to production files. Raw NC data are not included. unit: unknown permits missing unit metadata but does not convert units. Specify actual units for production comparisons. Inconsistent daily and monthly units are rejected.

# Check paths, candidate grid, and parameters without sampling
python run_mstas.py --config configs/pm25.yaml --stage check

# Read and validate NC contents and construct aligned reference matrices
python run_mstas.py --config configs/pm25.yaml --stage prepare

# Compute regionalization and automatic K*, then inspect partition maps
python run_mstas.py --config configs/pm25.yaml --stage regionalize

# Small production-data smoke test with an explicit run-count override
python run_mstas.py --config configs/pm25.yaml --stage sample --runs 5 --workers 2

# Continue to 5,000 runs, retaining completed run IDs 1-5
python run_mstas.py --config configs/pm25.yaml --stage sample

# Alternatively, execute the entire workflow
python run_mstas.py --config configs/no2.yaml

Input conventions

  • Supply daily and monthly NC products separately; daily products are not automatically aggregated into monthly products.

  • Files can contain multiple time steps or one date per file. Without a time dimension, date_regex extracts a date using the named group date.

  • Coordinates must be monotonic one-dimensional arrays; ascending and descending axes are supported. Curvilinear grids and unspecified additional dimensions raise explicit errors. Use data.daily.select or data.monthly.select to select additional levels.

  • Requested dates must be complete and unique. Missing values may be interpolated, but missing daily or monthly files are not silently reconstructed.

  • CF decoding applies scaling, offsets, and missing-value masks exactly once.

  • Candidate CSV files contain stable location IDs and coordinates. The supplied Shenzhen reference grid has 2 km spacing and uses EPSG:32649. Other study areas require their own reference data and a suitable meter-based projection.

  • Candidates are filtered against the study boundary. excluded_boundary explicitly removes specified areas; islands and disconnected components are not automatically discarded.

  • Coordinates are checked against grid_spacing_m. Adjacency uses actual coordinate differences to avoid bridging missing grid rows or columns.

Four-cell extraction and missing values

For each candidate, select the contiguous 2 x 2 source-cell block whose center is nearest, and average its four cells equally. Daily and monthly products have separate mappings. Row and column indices are recorded in data_summary.json. A missing cell makes that candidate-time value missing, after which:

  1. Short gaps bracketed by valid observations at the same location are linearly interpolated using actual time intervals. Defaults allow seven consecutive daily records or one monthly record.

  2. Remaining gaps use same-time inverse-distance weighting: up to eight neighbors within 10 km, with distance exponent 2.

  3. Processing stops if the original missing fraction exceeds 10% at any location or no suitable spatial donors exist. Thresholds are configurable.

  4. Imputation masks are retained. Final evaluation reports both all-reference metrics and metrics restricted to non-imputed reference values.

Algorithm rules

Regionalization

Each site's daily sequence is standardized along time. Constant sequences become zero vectors. Shared-edge four-neighbor adjacency is a hard constraint. Ward merging uses the exact increase in squared error from standardized-sequence centroids. Partition evaluation uses Euclidean distance between standardized sequences. Regional weights are the CVs of unstandardized daily values, using population standard deviation (ddof=0).

The composite criterion subtracts regional-balance and preferred-count penalties from the weighted silhouette score. Selection first considers K values satisfying the balance constraint. Reference settings are K = 2-8, beta_balance = 0.15, beta_complexity = 0.08, K_prefer = 4.5, and tau = 0.5. fixed_k: null selects K automatically; an integer specifies the requested partition count.

Disconnected components are never merged, and K cannot be smaller than their count. A partition unable to support two initial sites and one unselected evaluation site per region is reported as infeasible; the program does not silently alter K or remove candidates.

Initialization

Every region receives at least two initial sites. initial_budget: null sets the total to 2K. For larger initial budgets, additional slots follow regional CV weights and the largest-remainder method, subject to regional capacity.

Within-region sampling weights are the squared relative ranks of temporal CV. With selected sites present, weights also include the square root of the nearest-site distance relative to the largest such distance among currently feasible candidates. Region initialization order is randomized to avoid systematic boundary priority. cv_power and distance_power control these preferences.

All initial sites obey the global distance constraint. Initialization allows 100 attempts by default; inability to find a feasible design is recorded without relaxing spacing.

Regional GPs and sequential selection

  • Monthly concentrations remain on their original scale, centered by the current regional training mean. Predictions restore this mean.

  • The covariance is spatial Matern multiplied by temporal Ornstein-Uhlenbeck. Coordinates are divided by grid spacing; time uses 30-day units.

  • Signal variance, spatial and temporal length scales, and noise variance use bounded marginal-likelihood optimization. Matern smoothness candidates 0.5, 1.5, and 2.5 are compared by likelihood.

  • Variance bounds use selected training values only. Each regional model uses its own selected sites. Numerical jitter is separate from model noise.

  • Each step selects the feasible region with the largest regional RMSE, followed by its feasible location with the largest time-averaged latent posterior variance.

  • Regional RMSE includes every unselected location-time pair. The objective is the equally weighted mean of regional RMSE values.

  • Minimum spacing defaults to 2.5 grid intervals, configurable from 2 to 3. It is checked against all selected sites across the study area and never automatically relaxed.

  • Sampling stops at the target budget or when no feasible candidate remains. Empty regional evaluation sets produce null metrics rather than artificial zero errors.

Fixed evaluation and best-run selection

The global evaluation GP is separate from the sampling GPs. Its fixed covariance also uses Matern times Ornstein-Uhlenbeck. evaluation.params contains [signal variance, spatial length scale, temporal length scale, noise variance], defaulting to [1, 3, 3, 0.05], with smoothness 1.5. Coordinate and time units are as above; variance uses squared concentration units.

These are explicit numerical starting settings, not estimates from unselected targets or guaranteed optimal values. Establish the configuration before formal comparisons and retain it across methods, budgets, and repeated runs for the same pollutant. Evaluation fits selected-site values without optimizing kernel parameters.

The best run minimizes global RMSE. Ties within tolerance are resolved by run ID. All reported best-run metrics and locations come from that same run. Means and population standard deviations include only completed runs with valid metrics. R-squared is null for constant reference targets.

Parallel execution and resuming

The default is 5,000 independent complete-design attempts per budget, not 5,000 trials per candidate. Seeds depend on the base seed, budget, and run ID; serial and process execution use identical seeds. Random initialization can produce duplicates; reports provide unique initialization and final-design counts.

Each run is atomically saved as JSON. Repeating a command skips saved complete, incomplete, and failed attempts. Increasing the run count appends new runs; failures are not retried indefinitely. Installing or unpacking the package does not launch production experiments.

Defaults are two worker processes and one internal numerical thread per worker. Adjust workers to available CPU and memory. Budgets run sequentially, with parallelism within each budget.

Input file contents, algorithm source, and scientific parameters define an experiment fingerprint. Changes create a new experiment directory. Worker count, reporting settings, and run-count extensions do not change experiment identity. A lock prevents concurrent writers. If a crash leaves .running.lock, confirm the original process has stopped before removing it.

Outputs and figures

Results are stored under outputs/<experiment>_<fingerprint>/:

File or directory Contents
resolved_config.yaml Fully merged experiment parameters
manifest.json Inputs, fingerprint, Python and dependency versions
candidates.csv / prepared.npz Candidates, time-series matrices, and imputation masks
data_summary.json Extraction mappings, shapes, imputation counts, and units
regionalization/ K scores, merging history, partition tables and maps
budget_B/runs/ Designs, sequential traces, fitted parameters, and stopping reasons
budget_B/summary.csv Status and metrics of all attempts
budget_B/statistics.json Completion rate, unique-design counts, means and standard deviations
budget_B/best_scheme.csv Best-run locations, coordinates, selection order and regions
budget_B/best_run.json / best_trace.csv Complete metrics and trace from the same best run
comparison/ Cross-budget summaries and performance curves

Internal region indices start at zero. User-facing partition and design tables use one-based numbering corresponding to A1, A2, etc.; original location IDs are retained. JSON fields selected, initial, and added are zero-based row indices in candidates.csv.

Figure output defaults to 300 DPI. Legends are placed to the right or below the axes, with tight bounding boxes to avoid clipping. Formats and resolution are controlled by reporting.

Regenerate reports and figures without accessing the original NC files:

python run_mstas.py --stage report --results 'outputs/experiment_directory'

Existing experiments retain their saved configuration. If created with an older resolution, set reporting.dpi: 300 in their resolved_config.yaml before regenerating figures.

Modules and tests

data.py handles NC inputs and grids; regionalization.py computes partitions; gp.py fits exact GPs; sampling.py implements initialization and selection; evaluation.py provides common evaluation; runner.py manages multiprocessing and checkpoints; reporting.py generates summaries and figures. These modules are in mstas/.

python -m pytest tests -q

Tests cover extraction and scaling, missing dates, interpolation, adjacency, disconnected partitions, CV scoring, GP conditioning, global spacing, random initialization, serial/process consistency, resuming, and configuration/input changes.

About

Official code for MSTAS: A Multi-Pattern Spatiotemporal Adaptive Sampling Method for Environmental Sensor Placement

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages