Public orbitalpv API#

Install the distribution with pip install orbital-pv and import it as orbitalpv.

Public OrbitalPV API.

Install with pip install orbital-pv and import this package as orbitalpv.

class orbitalpv.ArxivConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

One explicit paper per request; reuse cache and observe arXiv rate limits.

The original Atom bytes are cached with SHA-256, URL and retrieval time. This connector does not extract or promote scientific claims from PDFs. Downloading an accessible paper does not grant redistribution rights.

Parameters:
paper(paper_id, *, cache_path=None, refresh=False)[source]

Fetch pinned metadata, or validate and read its existing local cache.

Parameters:
Return type:

ResearchResponse

download_paper(paper_id, destination, *, max_bytes=20000000)[source]

Download a selected version with a checksum receipt; no bulk crawl.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.BayesianLinearCalibration(model, coefficient_covariance, observation_noise_std, prior_std)[source]

Normal likelihood + zero-mean normal coefficient prior, known noise.

Parameters:
  • model (LinearCalibration)

  • coefficient_covariance (ndarray)

  • observation_noise_std (float)

  • prior_std (float)

predict(features, *, timestamps=None, coverage=0.95, include_observation_noise=True)[source]

Return posterior mean and Gaussian credible/predictive intervals.

Coverage is a model-based probability, not verified frequentist coverage. Future model discrepancy and parameter drift are not included.

Parameters:
  • coverage (float)

  • include_observation_noise (bool)

Return type:

DataFrame

class orbitalpv.BirdsEPSConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Connector for the public BIRDS on-orbit EPS dataset.

Parameters:
download(satellite, destination)[source]

Download one satellite workbook from the upstream BIRDS repository.

Parameters:
Return type:

DownloadReceipt

download_frame(satellite, destination, *, normalized=True, campaign_year=None)[source]

Download and load a BIRDS EPS workbook.

campaign_year supplies the year only for campaign sheet names that omit it; see load_birds_eps_workbook() for the time convention.

Parameters:
  • satellite (str)

  • destination (str | Path)

  • normalized (bool)

  • campaign_year (int | None)

Return type:

DataFrame

class orbitalpv.BlockConformalVI(quantile, scales, coverage, block_size, calibration_blocks, calibration_samples, discarded_tail_samples, trained_through, calibrated_through, horizons)[source]

Maximum normalized residual over channels, horizons and each time block.

Parameters:
predict(predicted, *, origin_times)[source]

Apply frozen intervals after the last calibration target timestamp.

Return type:

VIPredictionIntervals

class orbitalpv.DataverseConnector(*, base_url='https://darus.uni-stuttgart.de', timeout_s=30.0)[source]

Public Dataverse search and versioned dataset access; defaults to DaRUS.

Another public installation can be selected with base_url. Dataset and file licenses are provider-specific. Private/restricted data are not fetched.

Parameters:
search(query, *, start=0, page_size=25, cache_path=None, refresh=False)[source]

Search public datasets; start is a zero-based record offset.

Parameters:
Return type:

ResearchResponse

dataset(persistent_id, *, version=':latest-published', cache_path=None, refresh=False)[source]

Fetch published dataset metadata; pin version='1.0' for reproducibility.

Parameters:
Return type:

ResearchResponse

download_file(persistent_id, filename, destination, *, version=':latest-published', max_bytes=100000000)[source]

Download the original public file and verify its dataset checksum.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.DeSotoParameters(alpha_sc: 'float', a_ref: 'float', i_l_ref: 'float', i_o_ref: 'float', r_sh_ref: 'float', r_s: 'float', eg_ref: 'float' = 1.121, degdt: 'float' = -0.0002677)[source]
Parameters:
class orbitalpv.DiscosConnector(*, token, timeout_s=30.0)[source]

ESA DISCOS v2 metadata; free registration and an explicit token required.

DISCOS IDs and NORAD catalog numbers are different identifiers. This API supplies object/launch metadata, not ephemerides or universal PV ratings.

Parameters:
objects(*, filter_expression=None, page=1, page_size=100, cache_path=None, refresh=False)[source]

Get one page of objects using the provider’s filter syntax.

Parameters:
  • filter_expression (str | None)

  • page (int)

  • page_size (int)

  • cache_path (str | Path | None)

  • refresh (bool)

Return type:

ResearchResponse

object(discos_id, *, cache_path=None, refresh=False)[source]

Retrieve one object by its DISCOS internal ID.

Parameters:
Return type:

ResearchResponse

by_norad(norad_id, *, cache_path=None, refresh=False)[source]

Search the NORAD satno field; preserve an empty or ambiguous result.

Parameters:
Return type:

ResearchResponse

class orbitalpv.DonkiConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NASA CCMC DONKI event catalog, accessed directly without a NASA API key.

Uses the September 2026 CCMC endpoint, not the retired kauai host. Events are research context, not spacecraft-specific dose or causation evidence. Follow CCMC’s attribution and publication rules for event studies.

Parameters:
events(event_type, *, start, stop, cache_path=None, refresh=False)[source]

Get an explicit UTC date window (provider endDate is inclusive).

The raw empty response may be null or an empty list. Event links and associated instruments/spacecraft are kept, without assigning them to other missions.

Parameters:
Return type:

ResearchResponse

class orbitalpv.FlyingLaptopConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve CC BY 4.0 Flying Laptop monthly archives from DaRUS.

The archive contains many housekeeping packets. The normalizer reads only packet 4900, whose calibrated array currents and voltages have documented units of A and V. Downloads retain a checksum-bearing provenance sidecar.

Parameters:
download_month(month, destination)[source]

Download one YYYY-MM archive after checking its catalog checksum.

Parameters:
Return type:

DownloadReceipt

download_frame(month, destination, *, time_min=None, time_max=None)[source]

Download a month and normalize the requested UTC time interval.

Parameters:
Return type:

DataFrame

class orbitalpv.GHSLSettlementConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve JRC GHS-SMOD context while preserving its edition and epoch.

The official R2023A V2.0 global ZIP is downloaded once and reused; the 2015 archive is about 29 MB. Only a bounded native-resolution window is read into memory. The ZIP size is capped before and during downloading, and its member is validated before Rasterio opens it.

Original R2019A downloads are no longer served at the official URL as of October 2026. Use edition='R2019A', source_path=... with a retained native historical GeoTIFF. No fallback to a different edition occurs.

Parameters:
fetch_settlement(*, bbox, cache_path, source_cache_dir=None, source_path=None, edition='R2023A', epoch=2015, refresh=False, offline=False, max_download_bytes=67108864, max_pixels=1000000)[source]

Return a native crop for WGS84 (west, south, east, north).

offline permits an existing validated crop or local source, and prevents HTTP calls. refresh replaces a crop from the same source; archived versioned source files remain cached. A local source_path is hashed and its edition/epoch are caller declarations recorded in provenance; filenames alone cannot verify those declarations.

Parameters:
Return type:

SettlementRaster

class orbitalpv.GroundImage(data, crs, transform, bounds, scene_id, asset_key, source_url, asset_metadata, bbox_wgs84, item_metadata, nodata_values, retrieved_at)[source]

A native-resolution rectangular crop, retaining raw pixel semantics.

data has shape (bands, rows, columns); True mask entries mean missing data. transform holds affine (a, b, c, d, e, f) coefficients and bounds is (left, bottom, right, top) in crs. Pixel-aligned bounds can extend slightly beyond the requested bbox_wgs84.

visual is a rendered RGB product, not calibrated reflectance. scl is a categorical scene-classification product, not a power or irradiance measurement. No cloud masking is applied implicitly.

Parameters:
reflectance()[source]

Return raw * scale + offset using explicit STAC band metadata.

Only assets declaring the reflectance role are accepted. Missing data remain masked before calibration; negative reflectance values are retained. The raw data is never modified. For example, Collection 1 commonly declares scale 0.0001 and offset -0.1, so dividing every product by 10000 without its offset would be wrong.

Return type:

MaskedArray

save_geotiff(destination, *, overwrite=False)[source]

Save raw pixels, georeferencing, calibration and provenance.

The .meta.json sidecar includes the complete source STAC item, asset metadata, requested/actual bounds and the output SHA-256. The checksum identifies this derived crop, not the original full tile. A GeoTIFF internal mask is used when all band masks agree. Distinct band masks are retained through a shared nodata value when possible; unsupported mask combinations raise rather than discard information.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.GroundTrackSample(timestamp: 'datetime', longitude_deg: 'float', latitude_deg: 'float', altitude_m: 'float', speed_m_s: 'float', velocity_gcrs_m_s: 'tuple[float, float, float]', illumination_fraction: 'float')[source]
Parameters:
class orbitalpv.HorizonsConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Public NASA/JPL ephemerides for supported targets, including spacecraft.

Returns the original JSON envelope containing the ephemeris text, headers, units and API signature. Vectors use ICRF axes, TDB time, geometric (no light-time) corrections and AU/day units. No spacecraft attitude or PV output is implied. Target coverage is determined by JPL.

Parameters:
vectors(target, *, start, stop, step='1 d', center='500@10', cache_path=None, refresh=False)[source]

Retrieve geometric vectors; default center is the Sun’s center.

Dates are YYYY-MM-DD in TDB, with both endpoints requested. The provider may omit the final instant if the step does not land on it. Negative spacecraft IDs (e.g. '-61' for Juno) avoid ambiguous name matches.

Parameters:
Return type:

ResearchResponse

class orbitalpv.LaggedVIData(features, targets, origin_values, origin_times, target_end_times, feature_names, lags, horizons, cadence_s, source_windows)[source]

Features available at each origin and future measured V/I targets.

Array axes are sample, horizon, then (voltage, current). Horizons denote source-sample steps; actual origin/end timestamps are retained. No gaps are filled and any window containing a large cadence departure is excluded.

Parameters:
class orbitalpv.LinearCalibration(coefficients, feature_mean, feature_scale, trained_from, trained_through, purpose, evidence, samples)[source]

A ridge/least-squares fit with training-only feature normalization.

Parameters:
predict(features, *, timestamps=None, held_out=True)[source]

Predict; supplied held-out timestamps must follow all fit labels.

Omit timestamps only for algebraic/in-sample model inspection. A caller doing an evaluation should always supply them; no function can discover hidden future information in caller-constructed feature columns.

Parameters:

held_out (bool)

Return type:

ndarray

class orbitalpv.LinearVIForecaster(model, horizons, feature_names)[source]

Multi-output ridge baseline trained only on preceding V/I labels.

Parameters:
  • model (LinearCalibration)

  • horizons (tuple[int, ...])

  • feature_names (tuple[str, ...])

class orbitalpv.LisirdConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve bounded, measured TSIS-1/SORCE irradiance datasets.

The LaTiS jsond response carries parameter order and units. Cache files contain the original JSON bytes plus a .meta.json sidecar binding the response to its dataset, time range and SHA-256. Reusing a different query with the same cache path raises an error instead of returning stale data. Data access is public; retain LASP/instrument-team attribution and consult the product release notes for the version used.

Parameters:
total_solar_irradiance(dataset_id='tsis_tsi_24hr', *, time_min, time_max, cache_path=None)[source]

Return measured daily or six-hourly TSI in W/m².

The interval is [time_min, time_max) in UTC, applied to the nominal averaging-bin timestamp. At-1-AU and actual-Earth-distance irradiances remain separate. Source zero fill values become NaN; missing intervals are not interpolated. valid_measurement requires both irradiances to be finite and positive. provisional_flag is preserved when present and is not interpreted as a missing-value flag.

Parameters:
Return type:

DataFrame

spectral_irradiance(dataset_id='tsis_ssi_24hr', *, time_min, time_max, cache_path=None)[source]

Return measured TSIS-1 SIM spectra as wavelength-resolved rows.

Wavelength is in nm, irradiance in W/m²/nm, and the time interval is end-exclusive. All source quality bits are retained as quality_flag; quality_good conservatively selects zero-flag bins. Flagged bins remain in the frame. Do not integrate across missing or rejected spectral intervals or assume this 200–2400 nm product covers all TSI. At most 31 days may be requested per call to bound response size.

Parameters:
Return type:

DataFrame

class orbitalpv.LossStage(name, power_column, category, evidence)[source]

One ordered, cumulative power prediction with a declared evidence basis.

power_column contains the prediction after this stage, not an independent loss estimate. Its contribution is the preceding prediction minus this prediction. evidence should identify the measurement, model, operating flag or explicit scenario assumption supporting the attribution. This label records the caller’s evidence; it does not verify causality.

category must be a key in LOSS_CATEGORIES, except unexplained which is reserved for the final model-minus-actual residual. Names must be unique snake_case identifiers within a breakdown.

Parameters:
  • name (str)

  • power_column (str)

  • category (str)

  • evidence (str)

class orbitalpv.MeasuredEnergyBudget(intervals, summary)[source]

Energy integrated over common valid observation intervals only.

Parameters:
class orbitalpv.N2YOConnector(*, api_key=None, timeout_s=30)[source]

N2YO REST v1. Keep API keys on the server, outside browser bundles.

Positions are provider predictions, not satellite GPS telemetry. The free service documents 1,000 position calls/hour and at most 300 samples/call. No retries are made here. Bulk tracking should use cached GP + local SGP4. https://www.n2yo.com/api/

Parameters:
  • api_key (str | None)

  • timeout_s (float)

positions(norad_id, *, observer_lat, observer_lon, observer_alt_m=0, seconds=60)[source]

Return the provider’s timestamped position JSON, including provenance.

sataltitude in the provider payload is km; observer altitude is m. Element epoch is not supplied by this endpoint and remains unknown.

Parameters:
Return type:

dict[str, Any]

class orbitalpv.NoaaSwpcConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NOAA Space Weather Prediction Center JSON feed connector.

Parameters:
solar_wind_magnetic_field()[source]

Return native real-time solar-wind magnetic-field records (L1).

Preserve provider coordinates, spacecraft identity and quality fields. This is upstream solar-wind context, not a local spacecraft field model.

Return type:

Any

solar_activity(product, *, cache_path=None, refresh=False)[source]

Return UTC X-ray, Kp or alert records with source provenance.

Products are xrays (primary GOES, rolling six hours), kp (estimated planetary Kp), and alerts (provider bulletin text). Original fields are retained. A cache is a frozen snapshot until explicitly refreshed; inspect timestamp/retrieved_at for freshness. X-rays are band-limited irradiance, not total sunlight or PV power.

Parameters:
Return type:

DataFrame

goes_integral_particle_flux(particle, *, role='primary', period='7-day', cache_path=None, refresh=False)[source]

Fetch measured GOES integral proton or electron flux.

period selects a rolling 6-hour, 1-day, 3-day or 7-day observation feed. This is not a historical-date API. role is primary or secondary; the actual GOES number is retained for each record.

A cache stores the original response with a JSON provenance sidecar. Subsequent calls reuse that exact snapshot unless refresh=True. A mismatched request or checksum raises instead of silently using data for another channel. Electron flux can be contaminated during energetic proton events; this feed does not supply a per-record contamination flag.

Parameters:
Return type:

DataFrame

class orbitalpv.NtrsConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NASA Technical Reports Server: public metadata and available documents.

No account is needed. A search hit can be metadata-only. Preserve each record’s copyright/distribution fields; public access is not a blanket license to redistribute every paper. Design goals in papers are not flight performance measurements.

Parameters:
search(query, *, offset=0, page_size=25, cache_path=None, refresh=False)[source]

Search one page; offset is the zero-based record offset.

Parameters:
Return type:

ResearchResponse

citation(citation_id, *, cache_path=None, refresh=False)[source]

Get metadata, original download links and access/copyright details.

Parameters:
Return type:

ResearchResponse

download_document(citation_id, filename, destination, *, max_bytes=100000000)[source]

Download an explicitly selected, publicly available original file.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.OpenStreetMapEnergyConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve small-area raw solar/wind features with original OSM structure.

generator:source and plant:source select the paper’s input features without requiring a second power tag. For older tagging, the query also includes power_source on power=generator or power=plant objects. This additional legacy selection is explicit and is not an exact replay of the paper’s 2020 search. solar can include solar thermal: inspect the source’s method/type tags before treating features as photovoltaic arrays.

The result is Overpass JSON, not GeoJSON. Nodes, way-node references, all tags, relation member roles and available geometry are preserved. The query requests full geometry rather than clipping outlines at the bounding box. A way/relation can therefore extend beyond the requested region. Nested relation references remain references and may need additional resolution. No polygon merging, geometry repair, capacity parsing or clustering occurs.

The current snapshot and source timestamp are retained. The optional cache stores original response bytes and a .meta.json sidecar containing the query, retrieval time, license and SHA-256. Public Overpass availability and rate limits apply; global extraction belongs in a regional/planet workflow.

Parameters:
fetch_energy_features(*, bbox, sources=('solar', 'wind'), cache_path=None, refresh=False)[source]

Return the raw source-tagged nodes, ways and relations for a region.

Parameters:
  • bbox (sequence of float) – (west, south, east, north) in WGS84 longitude/latitude degrees. At most one square degree is allowed. Antimeridian-crossing regions must be split into separate boxes. This is a feature-selection box, not an exact polygon-intersection test or an output-geometry clip.

  • sources (sequence of str) – Any nonempty subset of ("solar", "wind"). Input order and duplicate values do not change the query or cache identity.

  • cache_path (str or pathlib.Path, optional) – Original Overpass JSON cache. An existing cache must match both the complete query and its recorded checksum; mismatches raise errors.

  • refresh (bool) – Fetch a new snapshot and replace the cache only after a valid, complete response has been received. Defaults to offline cache reuse.

Returns:

Original decoded Overpass object, including elements and source metadata such as osm3s.timestamp_osm_base when provided. An empty elements list is a valid result; provider errors are never converted into an empty dataset.

Return type:

dict

class orbitalpv.OpsSatADConnector(*, timeout_s=120.0)[source]

Download the original telemetry CSV from the fixed OPSSAT-AD v2 release.

Data are CC BY 4.0, DOI 10.5281/zenodo.15108715. The 19 MB CSV contains measured magnetometer and photodiode channels, rather than the separate handcrafted-feature table. No credentials are required.

The source does not include engineering-unit declarations. Values are preserved in their published scale, without interpreting photodiodes as solar-panel current, irradiance, or generated electrical power.

Parameters:

timeout_s (float)

download(destination)[source]

Download, verify, and preserve the source CSV and a provenance sidecar.

Parameters:

destination (str | Path)

Return type:

DownloadReceipt

download_frame(destination, *, channels=None, split=None, refresh=False)[source]

Load selected channels/split, reusing only checksum-verified cached data.

channels is a sequence of source IDs, such as ["CADC0892"]. split is "train", "test", or None for both. Filtering keeps the source segment identifiers and the published benchmark split. A corrupt or different local file raises instead of silently replacing it.

Parameters:
Return type:

DataFrame

class orbitalpv.PVCapacityModel(boxcox_lambda, area_scale, intercept, slope, coefficient_covariance, residual_std_mw, training_area_range_m2, training_capacity_range_mw, n_training, n_excluded, min_area_m2, capacity_basis, area_basis, source, fit_rmse_mw, fit_mae_mw)[source]

A newly calibrated Gaussian-log-link area model, with source provenance.

The model form follows the published R script: transform positive area in km² with Box-Cox, divide by sample standard deviation, then fit E[capacity_MW] = exp(intercept + slope * transformed_area / scale). Preprocessing is fitted only on the supplied calibration observations. Lambda maximizes the Box-Cox normal likelihood over [-3, 3], with caret’s 0.2 tolerance around zero and one. Continuous optimization and nonlinear least squares can differ numerically from R’s grid/IRLS implementation. This is a recalibration, not the original authors’ trained model.

Parameters:
predict(area_m2, *, urban, area_basis, allow_extrapolation=False, confidence=0.95)[source]

Predict for matching area semantics, flagging unsupported observations.

Only explicitly nonurban observations above min_area_m2 qualify. Extrapolation outside the calibration area range is withheld by default and remains flagged when explicitly allowed. The caller must use the same area definition and AC/DC/reported capacity basis as the calibration data. Urban status can come from a declared GHSL edition.

Parameters:
Return type:

PVCapacityPrediction

class orbitalpv.PVCapacityPrediction(mean_mw, lower_mw, upper_mw, eligible, extrapolated, reasons, confidence, capacity_basis, area_basis)[source]

Conditional MW estimates and approximate Gaussian prediction intervals.

Ineligible or disallowed extrapolated estimates are NaN. Intervals include residual variance and fitted-coefficient uncertainty using a local linearization; they do not include mapping error, uncertain area/labels, Box-Cox parameter uncertainty, or geographic/technology domain shift. Their nominal coverage is not a guarantee on a new country or sensor.

Parameters:
class orbitalpv.PVFeatures(data, valid_mask, feature_names, crs, transform, bounds, bbox_wgs84, scene_id, pixel_area_m2, provenance)[source]

Derived spectral predictors and validity on one projected image grid.

data has shape (rows, columns, features). valid_mask=True means all predictors and the requested SCL quality filters are usable. Grid areas are projected areas, not an individual-module measurement.

Parameters:
class orbitalpv.PVFootprintModel(feature_names, trees, metadata)[source]

An explicitly trained spectral random forest with safe JSON persistence.

Fitting uses scikit-learn. Prediction reads only learned numeric decision trees and the supplied spectral stack; it never queries or consults OSM. JSON persistence stores numeric arrays instead of executable pickle data. Training provenance is retained so spatially overlapping evaluation can be rejected. Held-out-site metrics assess a supplied reference, not automatic worldwide validity of the model.

Parameters:
classmethod fit(samples, *, random_state=0, max_samples_per_class=5000, n_estimators=100, min_samples_leaf=3, max_depth=20)[source]

Fit a deterministic forest from caller-labelled scenes.

At most max_samples_per_class valid pixels of each class are sampled without replacement from each scene. Random seed, counts, site IDs, bounding boxes, scenes and label sources are recorded. Class weighting balances the retained training labels. This function performs no random-pixel train/test split: such a split cannot test transfer to an unseen farm.

Parameters:
  • samples (Sequence[PVTrainingSample])

  • random_state (int)

  • max_samples_per_class (int)

  • n_estimators (int)

  • min_samples_leaf (int)

  • max_depth (int)

Return type:

PVFootprintModel

property model_id: str

SHA-256 of the model’s canonical numeric JSON representation.

save(path, *, overwrite=False)[source]

Save non-executable JSON, refusing to overwrite by default.

Parameters:
Return type:

Path

classmethod load(path)[source]

Read and validate numeric JSON; never execute serialized Python.

Parameters:

path (str | Path)

Return type:

PVFootprintModel

predict(features, *, threshold=0.5, min_area_m2=1000.0)[source]

Infer PV scores and four-connected footprint polygons from imagery.

No OSM input is accepted. Area filtering removes entire components, retaining holes and the red grid’s pixel edges. GeoJSON is WGS84; areas are measured on the projected input grid. This is approximate array footprint area, not panel surface area or installed capacity.

Parameters:
  • features (PVFeatures)

  • threshold (float)

  • min_area_m2 (float)

Return type:

PVFootprintPrediction

evaluate(features, labels, *, site_id, label_source, threshold=0.5, min_area_m2=1000.0)[source]

Evaluate an unseen site against caller-labelled valid pixels.

Rejects a training site ID or geographic overlap, including a later image of the same farm under a different ID. Returns raw-threshold and area-filtered metrics separately. OSM labels yield agreement with that map snapshot; they do not establish ground-truth accuracy.

Parameters:
Return type:

dict[str, Any]

class orbitalpv.PVFootprintPrediction(probabilities, mask, geojson, metadata)[source]

Image-derived scores, filtered mask and WGS84 footprint polygons.

probabilities are uncalibrated forest scores before area filtering. mask retains only thresholded connected components meeting the area limit. Both arrays mask invalid pixels rather than coding them non-PV. GeoJSON contains grid-derived footprint area, not module surface area.

Parameters:
property area_m2: float

Sum of retained projected-grid footprint areas.

class orbitalpv.PVSite(name, bbox_wgs84, scenes, item, images, osm)[source]

Source imagery and mapped solar features for one inspection area.

images contains native-grid GroundImage objects keyed by STAC asset name. item is the selected scene from the bounded scenes search, and osm is the original Overpass response. Each image keeps its own resolution, mask and calibration; the map and image dates can differ.

The name is a display label, not a verified inventory record. Solar-tagged OSM features still need method-tag inspection before identifying them as photovoltaic. Neither this object nor its loader infers plant boundaries, panel area, capacity, generation or completeness of OSM mapping.

Parameters:
summary()[source]

Return JSON-serializable dates, search limits and native-grid facts.

Pixel sizes use the units of the asset CRS. OSM counts describe raw objects, not unique plants; SCL counts describe source quality classes, not panel labels. Masked pixels are excluded from SCL counts.

Return type:

dict[str, Any]

class orbitalpv.PVTrainingSample(features, labels, site_id, label_source)[source]

One labelled scene, with a stable site ID and explicit label source.

Parameters:
  • features (PVFeatures)

  • labels (ndarray)

  • site_id (str)

  • label_source (str)

class orbitalpv.PdsConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NASA PDS Search API: mission product metadata, labels and data links.

Archive coverage is incomplete. Retain labels to interpret product units and calibration; a search hit is not necessarily a power measurement.

Parameters:
search(query, *, limit=25, sort=None, search_after=None, cache_path=None, refresh=False)[source]

Search using PDS q expressions; cursor pagination requires sort.

Example: '(product_class eq "Product_Bundle")'. Use provider field names and operators, not SQL. The documented keywords parameter is not exposed: it was silently ignored by the live service in the access check.

Parameters:
  • query (str)

  • limit (int)

  • sort (str | None)

  • search_after (str | None)

  • cache_path (str | Path | None)

  • refresh (bool)

Return type:

ResearchResponse

product(identifier, *, cache_path=None, refresh=False)[source]

Resolve a PDS LID or versioned LIDVID to its product metadata.

Parameters:
Return type:

ResearchResponse

class orbitalpv.PowerLossBreakdown(samples, components_w, categories_w, stages, group_columns)[source]

Power ledger returned by power_loss_breakdown().

samples contains sorted timestamps, group identifiers, power predictions, signed total/attributed/unexplained losses and a common valid mask. components_w contains a column per stage plus unexplained. categories_w combines stage contributions into reporting buckets. The three frames share the same positional index. Positive values are losses; negative values are gains. Treat these frames as read-only inputs to summarize_power_losses().

Parameters:
class orbitalpv.PowerLossSummary(totals, components, categories)[source]

Observed-interval energy totals, components and categories, all in Wh.

totals reports the signed energy gap and common observation coverage per input group. components and categories report signed net_loss_wh, nonnegative loss_wh / gain_wh and the signed percentage of expected energy. Percentages are NaN when expected energy is zero. All energy values are NaN when there are no usable intervals.

Net contributions reconcile with the total gap. Gross positive/negative contributions can cancel between components, so their separate sums need not equal the total positive gap or total surplus.

Parameters:
class orbitalpv.PsaConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

ESA Planetary Science Archive TAP/EPN-TAP read-only ADQL queries.

JSON responses retain column names, units, types and data access links. max_records bounds a response; reaching it may indicate truncation. The service does not provide universal spacecraft EPS telemetry.

Parameters:
query(adql, *, max_records=100, cache_path=None, refresh=False)[source]

Run a SELECT ADQL query; results are bounded, not a complete archive.

Parameters:
Return type:

ResearchResponse

class orbitalpv.PvwattsReference(pdc0_w, gamma_pdc_per_c, reference_irradiance_w_m2=1361.0, reference_temperature_c=25.0)[source]

Calibrated BOL DC reference for a spacecraft panel/array.

pdc0_w is defined at reference_irradiance_w_m2 and reference_temperature_c. For space PV, this is intentionally a calibration contract instead of assuming a terrestrial STC reference is physically meaningful for every cell technology.

Parameters:
  • pdc0_w (float)

  • gamma_pdc_per_c (float)

  • reference_irradiance_w_m2 (float)

  • reference_temperature_c (float)

class orbitalpv.ResearchResponse(data, receipt, request_url, documentation)[source]

Provider metadata and the receipt for its original response bytes.

request_url includes non-secret query parameters; authentication headers are never serialized. JSON connectors retain provider units, licenses, pagination, versions and uncertainty fields. The arXiv connector documents its Atom-to-metadata normalization and can cache original XML bytes. Neither representation is a validated engineering or PV specification.

Parameters:
class orbitalpv.SatelliteCOTSConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Download the authors’ original files, pinned by commit and SHA-256.

Parameters:
class orbitalpv.Sentinel2GroundConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Search Sentinel-2 Collection 1 and retrieve ground-image assets.

Search needs only the base installation. Windowed reading needs the optional ground extra (Rasterio). STAC item metadata stays intact, including each asset’s native resolution, calibration and nodata values. The provider’s scene-wide cloud percentage is not an AOI cloud mask.

Parameters:
search(*, bbox, time_min, time_max, max_cloud_cover=20.0, max_items=20, cache_path=None, refresh=False)[source]

Return a bounded STAC FeatureCollection, clearest scenes first.

bbox is west/south/east/north in WGS84 degrees. Time bounds are inclusive UTC instants, as in STAC; a date alone means midnight. max_items caps unique items, not pages. context.limit_reached flags a filled cap: this result must not be assumed exhaustive.

POST/GET pagination is followed with its declared body/merge semantics. Cached snapshots preserve full item metadata and a SHA-256 sidecar binding the file to this query. A changed query or damaged snapshot raises an error; refresh=True explicitly replaces the snapshot.

Parameters:
Return type:

dict[str, Any]

static read_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]

Read a native-resolution COG window; see read_ground_image().

Parameters:
Return type:

GroundImage

download_asset(item, asset, destination, *, max_bytes=1000000000, overwrite=False)[source]

Stream a complete asset to disk with a checksum/provenance sidecar.

Full Sentinel-2 bands can be hundreds of MB. Prefer read_image for farm-sized areas. The size ceiling is enforced while streaming, and a failed request never replaces an existing destination.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.SettlementRaster(data, crs, transform, bounds, bbox_wgs84, epoch, edition, provenance)[source]

A native 1 km categorical GHSL crop and its source provenance.

data is a two-dimensional masked integer array. These classes describe settlement context at epoch; they do not describe current PV land use or validate an individual rooftop, ground-mounted plant or water boundary. The original grid is retained, unlike the paper’s Eckert IV reprojection.

Parameters:
sample_points(lon_lat)[source]

Sample WGS84 points without interpolation; unknown flags are None.

Supplying farm centroids implements a clearly defined centroid lookup. It does not calculate the fraction of an entire farm covered by water or urban cells. Outside-crop, masked and unknown-code results remain explicit rather than being counted as rural/non-water observations.

Parameters:

lon_lat (Sequence[Sequence[float]])

Return type:

list[dict[str, Any]]

save(destination, *, overwrite=False)[source]

Write raw classes and internal nodata mask with a SHA-256 sidecar.

Parameters:
Return type:

None

class orbitalpv.SolarGeometry(sun_vector_m: 'tuple[float, float, float]', sun_distance_m: 'float', sun_unit_vector: 'tuple[float, float, float]', illumination_fraction: 'float', cosine_aoi: 'float | None' = None)[source]
Parameters:
class orbitalpv.SpaceCellSimulation(technology, irradiance_w_m2, cell_temperature_c, fluence_1mev_e_cm2, radiation_factor, voltage_v, current_density_ma_cm2, power_density_w_m2, voc_v, isc_ma_cm2, vmp_v, imp_ma_cm2, pmp_w_m2, efficiency)[source]

Simulated I-V/P-V result for one cell technology and operating point.

Parameters:
class orbitalpv.SpaceCellTechnology(slug, name, family, junctions, efficiency_am0, voc_v, vmp_v, jsc_ma_cm2, jmp_ma_cm2, temp_coeff_current_per_c, temp_coeff_voltage_per_c, radiation_retention_at_1e15, reference_temperature_c=28.0, reference_irradiance_w_m2=1361.0, notes='')[source]

Reference parameterization for a space photovoltaic cell technology.

Parameters:
class orbitalpv.VIPredictionIntervals(prediction, lower, upper, power_prediction_w, power_lower_w, power_upper_w, coverage)[source]

Joint V/I rectangles and sign-safe extrema of their products.

Parameters:
empirical_coverage(observed)[source]

Measure simultaneous-horizon coverage, retaining unbounded widths.

Return type:

dict[str, float]

class orbitalpv.ZenodoConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Discover published research datasets and download open files anonymously.

Restricted files remain restricted. Each record supplies its own license; no deposit, publication or authenticated write endpoints are used.

Parameters:
search(query, *, page=1, page_size=25, cache_path=None, refresh=False)[source]

Search one page using Zenodo query syntax (anonymous maximum: 25).

Parameters:
Return type:

ResearchResponse

record(record_id, *, cache_path=None, refresh=False)[source]

Read a specific record/version, including DOI, license and file checksums.

Parameters:
Return type:

ResearchResponse

download_file(record_id, filename, destination, *, max_bytes=100000000)[source]

Select a public file by exact name and verify its provider checksum.

Parameters:
Return type:

DownloadReceipt

orbitalpv.add_robust_baseline(frame, *, reference_samples=500)[source]

Add a telemetry-only upper-envelope normalization.

Case 0 has no trusted Sun/eclipse/attitude state. Normalizing against a high reference quantile is intentionally safer than treating every low-power sample as a fault. Fault screening happens on daily upper-envelope health, not samples.

Parameters:
Return type:

DataFrame

orbitalpv.build_pv_features(images, *, excluded_scl=(0, 1, 2, 3, 6, 8, 9, 10, 11), max_pixels=4000000)[source]

Calibrate six bands and align them to the native red grid.

Requires blue, green, red, nir, swir16, swir22 and scl from the same scene and requested area. Reflectance uses each source’s explicit scale/offset, including negative valid values. Any different spectral grid is resampled bilinearly; SCL always uses nearest neighbour. No source array or metadata is modified. Upsampled SWIR still contains only its original 20 m spatial information.

The default excludes nodata, defective pixels, topographic/cloud shadow, water, cloud/cirrus and snow. This also excludes floating-PV water pixels; callers studying such systems must explicitly choose quality classes. The NDVI/NDBI/MNDWI denominator must have absolute value above 1e-6.

Parameters:
Return type:

PVFeatures

orbitalpv.calibrate_block_conformal_vi(observed, predicted, *, origin_times, target_end_times, trained_through, scales, coverage=0.9, block_size=20)[source]

Calibrate joint multi-horizon V/I envelopes on a later time partition.

scales is positive (V, A) or (horizon, 2), selected on training data or independently, never tuned on this calibration/evaluation block. Blocks are nonoverlapping consecutive forecast records. The incomplete trailing block is discarded from scores but its labels remain inside the embargo boundary. This row-block method is not a proof of temporal independence.

Parameters:
Return type:

BlockConformalVI

orbitalpv.chronological_forecast_split(data, *, training_stop, calibration_stop)[source]

Split by clock time and purge targets that cross either boundary.

Training/calibration labels end strictly before their stop. Subsequent origins start at or after the stop; lagged historical observations remain allowed because they were already observable at each forecast origin.

Parameters:

data (LaggedVIData)

Return type:

tuple[LaggedVIData, LaggedVIData, LaggedVIData]

orbitalpv.circular_eclipse_duration_s(altitude_m, beta_angle_deg)[source]

Estimate eclipse duration per circular orbit with a cylindrical shadow.

beta_angle_deg is the signed angle between the Earth-to-Sun direction and the orbital plane, in [-90, 90]. Returns seconds as an array with the input beta shape (a zero-dimensional array for a scalar).

A spherical Earth and a point Sun at infinite distance are assumed. The eclipse half-angle is acos(sqrt(1 - (R/a)**2) / cos(beta)) below the critical beta asin(R/a); above it the duration is zero. Finite solar radius, penumbra, atmosphere and oblateness are omitted. In particular, zero here is not proof of uninterrupted full sunlight: use earth_occultation_fraction() for a finite-Sun geometry check.

See NASA’s spacecraft thermal-environment course, slides 110-119: https://ntrs.nasa.gov/api/citations/20200007746/downloads/20200007746.pdf

Parameters:
Return type:

ndarray

orbitalpv.circular_orbit_period_s(altitude_m)[source]

Return the two-body period of a circular Earth orbit in seconds.

altitude_m is a finite, positive height above the equatorial Earth radius. This is a design estimate, without perturbations or station keeping.

Parameters:

altitude_m (float)

Return type:

float

orbitalpv.circular_orbit_positions_m(altitude_m, inclination_deg, *, raan_deg=0.0, argument_of_periapsis_deg=0.0, samples=721, earth_radius_m=6378137.0)[source]

Generate positions for a circular orbit at a fixed altitude.

Parameters:
Return type:

ndarray

orbitalpv.classify_pv_farms(farms, settlement)[source]

Attach historical GHSL context at each grouped farm’s centroid.

This explicit farm-centroid lookup differs from the original paper’s majority of input-feature centroid flags. It is not an area fraction or a statement about present-day land use. Unknown cells retain None flags. The input GeoJSON is not modified.

Parameters:
Return type:

dict[str, Any]

orbitalpv.cluster_pv_farms(features, *, eps_m=400.0, min_samples=2, keep_singletons=True, profile='semantic', polygon_eps_m=None)[source]

Group mapped PV features and compute nonoverlapping area measures.

semantic clusters feature centroids at eps_m in a local equal-area projection, then merges intersecting geometries (including parent plants and their generators). panel_area_m2 includes only generator polygons; whole-plant land area is separately recorded. Missing panel area is null. This local approximation requires an extent no wider than five degrees in either coordinate; tile broader inventories with overlapping margins.

dunnett2020 uses Eckert IV, outermost polygons, a 10 m polygon buffer to exclude contained/nearby points, DBSCAN at 400 m for remaining points and 800 m for polygon centroids by default. For point-only groups it uses the median input polygon area as the paper’s explicit area proxy. If no polygon is available the proxy remains null. Intersecting output groups are additionally merged to prevent duplicate area, a documented safeguard beyond the historical script. A singleton polygon retains its original holes and concavities; grouped polygons use their convex hull for landscape area. Geometry IDs are never counted as modules.

Outputs are WGS84 GeoJSON. capacity_area_m2 and capacity_area_basis identify the profile’s predictor separately from actual mapped panel_area_m2 and osm_polygon_area_m2. Singletons are retained with is_cluster=False unless explicitly excluded. This is a spatial grouping, not a registry of independently operated projects.

Parameters:
Return type:

dict[str, Any]

orbitalpv.conformal_order_statistic(scores, *, coverage)[source]

Finite-sample split-conformal quantile; returns infinity if insufficient.

The order is ceil((n+1)*coverage), without clipping it to n. Clipping would silently advertise a confidence level unsupported by the calibration size.

Parameters:

coverage (float)

Return type:

float

orbitalpv.effective_irradiance_w_m2(am0_irradiance_w_m2, illumination_fraction, cosine_aoi, *, spectral_factor=1.0, optical_factor=1.0)[source]

Convert space environment/geometry state into cell-effective irradiance.

Parameters:
Return type:

ndarray

orbitalpv.estimate_pv_farm_capacity(farms, model)[source]

Attach calibrated capacities while retaining reasons for withheld values.

A farm needs a positive capacity-area predictor with the same definition as the calibration and an explicit nonurban flag. Different area bases, absent areas, unknown/urban context and out-of-range predictors are kept in the inventory with null estimates. No extrapolation is enabled here.

Parameters:
Return type:

dict[str, Any]

orbitalpv.evaluate_pv_capacity(observed_mw, prediction)[source]

Report held-out error and interval coverage without hiding exclusions.

Caller-supplied observations must be independent of fitting and use the model’s declared capacity basis. Counts include withheld/extrapolated predictions, while metrics use only eligible finite estimates. R² is null for a constant reference; no eligible predictions produces null metrics.

Parameters:
  • observed_mw (ArrayLike)

  • prediction (PVCapacityPrediction)

Return type:

dict[str, Any]

orbitalpv.evaluate_pv_mask(predicted, labels)[source]

Measure binary agreement on labelled, unmasked pixels only.

Labels are -1 unknown, 0 non-PV and 1 PV. Unknown labels and masked predictions do not become true negatives. Undefined precision/recall/F1/ IoU are None. Counts and coverage make missing-reference cases clear. This low-level scorer does not enforce train/test spatial separation; use PVFootprintModel.evaluate for a held-out-site guard.

Parameters:
Return type:

dict[str, Any]

orbitalpv.fetch_birds_eps(satellite, destination, *, campaign_year=None)[source]

Download and normalize real on-orbit BIRDS EPS telemetry.

campaign_year explicitly dates sheet names that omit a year, without overriding fully dated sheets. Numeric clocks retain their elapsed seconds; calendar-anchored timestamps do not establish the true acquisition time. See load_birds_eps_workbook() for metadata and excluded test sheets.

Parameters:
  • satellite (str)

  • destination (str | Path)

  • campaign_year (int | None)

Return type:

DataFrame

orbitalpv.fetch_celestrak_omm(catnr, *, cache_path='data/cache/gp.sqlite3')[source]

Fetch a CelesTrak OMM record, reusing a persistent two-hour cache.

Use CelesTrakConnector.fetch_gp_cached when source timestamps, stale warnings and checksums are needed alongside the orbital elements.

Parameters:
Return type:

dict[str, object]

orbitalpv.fetch_flying_laptop_power(month, destination, *, time_min=None, time_max=None)[source]

Download a Flying Laptop month and normalize its measured array V/I.

Power is computed from each documented voltage/current pair. UTC packet timestamps and four array identities are preserved. Bounds are inclusive at time_min and exclusive at time_max. For offline reuse, call load_flying_laptop_power() on the downloaded archive.

Parameters:
Return type:

DataFrame

orbitalpv.fetch_opssat_segments(destination, *, channels=None, split=None, refresh=False)[source]

Fetch checksum-verified original OPS-SAT telemetry and expert labels.

Values retain their published scale; the source supplies no engineering unit declaration. Segment IDs and the provider’s train/test split remain intact. Photodiode measurements are not panel electrical power.

Parameters:
Return type:

DataFrame

orbitalpv.fit_bayesian_linear_calibration(features, target, *, timestamps, purpose, observation_noise_std, prior_std=10.0, evidence='')[source]

Compute an exact Gaussian coefficient posterior with explicit noise/prior.

Prior standard deviation applies to all coefficients, including intercept, in standardized feature coordinates and the target’s units. Choose noise on training data or independent calibration evidence, never evaluation data.

Parameters:
  • purpose (Literal['healthy_reference', 'operating_forecast'])

  • observation_noise_std (float)

  • prior_std (float)

  • evidence (str)

Return type:

BayesianLinearCalibration

orbitalpv.fit_linear_calibration(features, target, *, timestamps, purpose, evidence='', ridge=0.0)[source]

Fit a deterministic reference or forecast, declaring its intended role.

timestamps identify target/label times, including the last forecast horizon. The intercept is unpenalized. Ridge is in standardized-feature coordinates; this is a statistical baseline, not an inferred physical law.

Parameters:
  • purpose (Literal['healthy_reference', 'operating_forecast'])

  • evidence (str)

  • ridge (float)

Return type:

LinearCalibration

orbitalpv.fit_linear_vi_forecaster(data, *, ridge=1.0)[source]

Fit a direct multi-horizon, multivariate-lag regression baseline.

Parameters:
  • data (LaggedVIData)

  • ridge (float)

Return type:

LinearVIForecaster

orbitalpv.fit_pv_capacity_model(area_m2, capacity_mw, *, urban, capacity_basis, area_basis, source, min_area_m2=10000.0, max_capacity_mw=1000.0)[source]

Calibrate the paper’s area-only model form from independent capacities.

Inputs are matched observations: area in m², capacity in MW, and explicit urban flags. The default domain mirrors the source script (>1 ha, nonurban, capacity <1000 MW). Set the capacity ceiling explicitly for a modern calibration; 1000 MW is a historical outlier cutoff, not a physical limit. Exclusions are counted. At least six retained observations and three distinct areas are required. A sample is not an independent test: evaluate on held-out sites/countries separately.

capacity_basis must be ‘AC’, ‘DC’, or ‘reported’; area_basis must declare generator panel area, an OSM polygon proxy, or a median polygon imputation. Never mix total site land with module/array surface area in a single calibration. The nonempty source describes external capacity evidence; this function cannot verify that provenance automatically.

Parameters:
Return type:

PVCapacityModel

orbitalpv.geocentric_sun_positions_m(times)[source]

Geocentric GCRS Sun positions using Astropy’s supported solar ephemeris path.

Parameters:

times (Sequence[datetime] | Sequence[str])

Return type:

ndarray

orbitalpv.get_space_cell_technology(name)[source]

Resolve a built-in technology by slug or common alias.

Parameters:

name (str)

Return type:

SpaceCellTechnology

orbitalpv.ground_track_deg_from_eci(positions_m, elapsed_seconds, *, earth_rotation_rate_rad_s=7.2921159e-05)[source]

Convert simple ECI positions to a spherical Earth-fixed ground track.

The transform assumes a uniformly rotating spherical Earth and a zero Greenwich angle at elapsed time zero. Use Astropy/ITRS or SPICE for mission-grade frame transformations.

Parameters:
Return type:

tuple[ndarray, ndarray]

orbitalpv.keplerian_orbit_positions_m(semi_major_axis_m, eccentricity, inclination_deg, *, raan_deg=0.0, argument_of_periapsis_deg=0.0, true_anomaly_rad=None, samples=721)[source]

Generate Keplerian ellipse positions in a simple ECI frame.

This convenience helper is intended for deterministic examples and design visualization. Operational propagation should use OMM/TLE/SGP4 or SPICE.

Parameters:
Return type:

ndarray

orbitalpv.list_space_cell_technologies()[source]

Return the built-in space-cell technology templates.

Return type:

tuple[SpaceCellTechnology, …]

orbitalpv.load_birds_eps_workbook(path, *, normalized=True, campaign_year=None)[source]

Load a downloaded BIRDS EPS workbook into the canonical panel schema.

Parameters:
  • path (str or pathlib.Path) – Downloaded upstream XLSX workbook.

  • normalized (bool, default True) – Return panel-level flight telemetry. The known undated TSURU sheets Test1 w batt and Test2 wo batt are excluded from this mode. False returns raw rows from every nonempty sheet, including tests.

  • campaign_year (int, optional) – Explicit year for campaign sheet dates that omit it. For example, the TSURU 2021 flight campaigns require campaign_year=2021. A year already stated in a sheet name is always preserved. No current-year assumption is made; an omitted year raises an actionable error.

Return type:

DataFrame

Notes

Calibrated numeric Time Stamp values are elapsed seconds. The returned timestamp anchors these to midnight on campaign_date for ordering; this is not a known absolute UTC acquisition time. The original clock is retained in elapsed_seconds and the convention in timestamp_basis. campaign_date_basis records whether a year was supplied by the caller. Rows without a valid elapsed clock or voltage/current pair are omitted.

orbitalpv.load_bupt1_telemetry(path, *, source='common', source_timezone=None, time_min=None, time_max=None, verify_source=True, chunksize=100000)[source]

Stream a local pinned archive, filtering inclusive/exclusive source times.

Bounds must match the timestamp basis: naive for an unspecified source timezone, or timezone-aware if source_timezone is supplied. The full archive is large; supply a time window. No ZIP member is extracted to disk. Set verify_source=False only for independently provided files, which are then labelled unverified rather than claimed as the pinned archive.

Parameters:
Return type:

DataFrame

orbitalpv.load_flying_laptop_power(path, *, time_min=None, time_max=None)[source]

Read calibrated solar-array V, I and computed power from a local archive.

time_min is inclusive and time_max exclusive; naive bounds are UTC. Timestamps are the source’s Unix epoch milliseconds in UTC, identifying packet generation. The source documents up to 400 ms of additional sensor acquisition delay. Missing/invalid readings remain missing and are omitted per voltage/current pair; signed sensor values are not clipped.

Four panel identifiers are preserved: right, left, center and test. Here test is the spacecraft’s experimental array channel, not a separate ground-test recording. Power is computed as V times I; no independently transmitted power measurement is implied.

The reader streams only matching packet 4900 members, never extracting archive paths to disk. A downloaded provenance sidecar, when present, is verified against the local archive. Source metadata is returned in attrs.

Parameters:
Return type:

DataFrame

orbitalpv.load_goes_integral_particle_flux(path, *, particle)[source]

Read an original SWPC integral-flux JSON snapshot without network access.

Raw fields are retained. Negative, nonfinite or missing flux values become NaN in flux_cm2_s_sr and are flagged by is_valid_flux. Integral energy channels overlap and must not be added together. Satellite identity is taken from every measurement, since primary proton/electron sources can differ.

Parameters:
Return type:

DataFrame

orbitalpv.load_ground_image(path, *, max_pixels=4000000)[source]

Load a saved native crop after verifying its pixels and provenance.

Read the GeoTIFF and .meta.json written by GroundImage.save_geotiff(). The SHA-256, byte count, source identity, native grid, nodata and calibration must agree. The metadata’s original path is informational, so snapshots can move between computers. Unverified external mask/PAM files are rejected.

max_pixels counts all band samples and is enforced before reading the pixels. Raw values, per-band masks and the complete source STAC item are retained; this function never makes network requests or applies calibration.

Parameters:
Return type:

GroundImage

orbitalpv.load_opssat_segments(path, *, channels=None, split=None)[source]

Read original OPSSAT-AD telemetry without resampling or merging segments.

Every source column is retained. timestamp becomes a UTC datetime; value stays on its original published scale. Missing/nonfinite values are retained and marked by is_valid_value; no fill value or physical unit is invented. value_unit explicitly records that units are absent from the source CSV.

Use the source’s numeric anomaly field for the expert annotation. The textual label column contains "anomaly" even for nominal segments in v2, so it must not be treated as a classification result. train is the fixed benchmark split, not a chronological split.

A local subset may be loaded for offline analysis. The returned attrs contain its checksum and whether it matches the complete pinned release.

Parameters:
Return type:

DataFrame

orbitalpv.load_pv_site(*, bbox, time_min, time_max, cache_dir, name='PV site', cache_prefix='site', max_cloud_cover=20.0, max_items=10, scene_id=None, assets=('visual', 'red', 'scl'), offline=False, refresh=False, timeout_s=60.0, max_pixels=4000000)[source]

Load or retrieve imagery and OSM inputs for a small PV inspection area.

Search Sentinel-2 Collection 1, select the first (lowest scene-cloud-cover) returned item by default, load native crops, and retrieve raw solar-tagged OSM features. A supplied scene_id must occur in the bounded search. Search intersection does not guarantee full raster coverage; the underlying crop reader raises for tile-edge areas rather than mosaicking implicitly.

bbox is WGS84 (west, south, east, north) and must satisfy the OSM connector’s one-square-degree limit. Time bounds are inclusive UTC instants. Scene-wide cloud cover is not a local cloud mask. Inspect quality classes and site.scenes['context']['limit_reached'] when selecting inputs.

The cache contains {prefix}-scenes.json, {prefix}-osm.json and {prefix}-{asset}.tif, each with its provenance sidecar. Existing caches must match the request, SHA-256, selected scene, asset metadata and grid. Only missing files are retrieved; incomplete or inconsistent caches raise. refresh=True explicitly retrieves replacement snapshots and crops. A refresh is not a transaction across all files: if it fails, retry with refresh enabled or use a new cache prefix. Mixed snapshots fail validation.

offline=True requires every source file and sidecar before any loading begins, blocks HTTP fallback, and cannot be combined with refresh=True. max_pixels limits band samples per asset, not the sum across assets. Install orbital-pv[ground] for GeoTIFF support; plotting is separate.

Parameters:
Return type:

PVSite

orbitalpv.load_settlement_raster(path, *, max_pixels=1000000)[source]

Restore and verify a saved GHSL crop entirely offline.

Parameters:
Return type:

SettlementRaster

orbitalpv.make_lagged_vi_data(frame, *, lags=(0, 1, 2), horizons=(1, 2, 4), feature_columns=('voltage_v', 'current_a'), cadence_s, cadence_tolerance_s=0.5)[source]

Build causal lag features and paired targets, rejecting discontinuities.

Caller-supplied feature columns must themselves be available at the origin. Telemetry from multiple panels must be separated before calling this method.

Parameters:
Return type:

LaggedVIData

orbitalpv.measured_energy_budget(frame, *, solar_column='solar_bus_power_w', load_column='bus_power_w', battery_column=None, battery_discharge_sign=1, max_gap_s)[source]

Reconcile solar + battery discharge - load using common valid intervals.

A residual is unexplained measurement/boundary mismatch, not an attributed physical loss. Supply battery sign explicitly when source data use charge- positive current. Missing battery telemetry is not assumed to be zero unless the caller chooses battery_column=None (a solar-versus-load comparison). Multiplexed group rows require a separately justified alignment first.

Parameters:
  • frame (DataFrame)

  • solar_column (str)

  • load_column (str)

  • battery_column (str | None)

  • battery_discharge_sign (int)

  • max_gap_s (float)

Return type:

MeasuredEnergyBudget

orbitalpv.normalize_bupt1_telemetry(raw, *, source='common', source_timezone=None)[source]

Normalize units without interpolating or demultiplexing measurements.

The common archive supplies separate MPPT1/2 and battery1/2 columns. The short-term source cycles through hardware groups; its group-specific power must not be mistaken for simultaneous whole-spacecraft PV power. Duplicate source clocks and signed sensor offsets remain visible. Zero temperature is retained because zero is not documented as a universal missing sentinel.

Parameters:
Return type:

DataFrame

orbitalpv.normalize_solar_activity(payload, product)[source]

Normalize native SWPC snapshots without network access.

Negative/nonfinite flux and Kp outside 0–9 are flagged and masked in canonical columns, while raw source fields remain available for auditing. Empty lists represent no records, never fabricated quiet conditions.

Parameters:
Return type:

DataFrame

orbitalpv.omm_epoch(omm)[source]

Parse GP EPOCH; timezone-free OMM epochs are UTC per the GP contract.

Parameters:

omm (dict[str, object])

Return type:

datetime

orbitalpv.osm_pv_features(overpass, *, require_photovoltaic=True, on_invalid='raise')[source]

Convert original Overpass solar objects to validated WGS84 GeoJSON.

Generator and plant semantics, original tags, OSM identifiers and snapshot time are preserved. Explicit photovoltaic method/type tags are required by default; unclassified solar objects can be retained with require_photovoltaic=False but are marked unconfirmed. Explicit solar thermal objects are always excluded. Nodes are points, ways must be closed, and multipolygon relations are assembled with member roles and holes. Incomplete/self-intersecting geometry raises; on_invalid='skip' records each exclusion in metadata.excluded. No geometry is silently repaired.

Parameters:
Return type:

dict[str, Any]

orbitalpv.persistence_vi_forecast(data)[source]

Repeat the last observed operating voltage/current at each horizon.

Parameters:

data (LaggedVIData)

Return type:

ndarray

orbitalpv.plot_pv_detection(site, prediction, *, reference_labels=None, reference_label='Separate reference labels', reference_credit=None)[source]

Compare a real RGB image, model scores and image-derived PV footprints.

Inference output must match the site’s red-band native grid and scene. Optional -1/0/1 reference labels add separate orange outlines; they are not used to create or clip the prediction. Unknown references remain unknown. Supply a source-specific reference_label and attribution in reference_credit when displaying mapped reference data. The function returns the figure and three axes for customization.

Parameters:
Return type:

tuple[Figure, np.ndarray]

orbitalpv.plot_pv_site(site, *, overlay_osm=False, ax=None)[source]

Show native RGB, optionally with original OSM outlines and locations.

Parameters:
  • site (space_pv_connectors.ground_site.PVSite) – Inputs returned by orbitalpv.load_pv_site(), including visual.

  • overlay_osm (bool, default False) – Transform the raw WGS84 map coordinates into the image CRS. Separate ways, relation members and incomplete geometry runs remain separate. Outlines are source map features, not image-derived panel labels.

  • ax (matplotlib.axes.Axes, optional) – Draw into existing axes and place attribution beneath those axes; otherwise create an attributed figure. Use constrained/tight layout when composing multiple supplied axes. Existing figure credits remain unchanged.

Returns:

Axes available for further annotations. Call plt.show() yourself.

Return type:

matplotlib.axes.Axes

Notes

RGB nodata samples are filled with zero only for display. Source arrays, masks and geometry are unchanged. Image and OSM dates are shown separately.

orbitalpv.plot_pv_site_quality(site)[source]

Show calibrated red reflectance and the native SCL quality categories.

red and scl assets are required. Red calibration uses the source’s explicit scale/offset, preserving nodata and negative reflectance. The display range is 0 to 0.5; colorbar extensions flag values outside that range. SCL remains on its native grid with its original integer categories 0 to 11. No resampling, cloud masking or photovoltaic classification is performed.

Returns the figure and two image axes; plt.show() remains with the caller. Both images retain their own native extents and coordinate labels.

Parameters:

site (space_pv_connectors.ground_site.PVSite)

Return type:

tuple[Figure, np.ndarray]

orbitalpv.power_loss_breakdown(frame, stages=(), *, expected_power_column='expected_power_w', actual_power_column='actual_power_w', timestamp_column='timestamp', group_columns=())[source]

Explain expected-minus-actual power using ordered cumulative predictions.

For stages P1, ..., Pn and a declared expected baseline P0, the signed contributions are P0-P1, P1-P2, ..., P(n-1)-Pn. The unexplained remainder is Pn-actual. Thus all contributions sum to expected-actual at every valid sample, including gains.

Use an ideal reference baseline for a design loss budget, or a healthy operating model for underperformance analysis. Effects already included in the expected baseline must not be subtracted again. Attribution is order-dependent and conditional on the supplied evidence; this function does not diagnose causes from the residual or normalize supplied losses.

Inputs must be already time-aligned in one DataFrame. Timestamps are converted to UTC (naive timestamps are assumed UTC), then sorted within each group. Duplicate group/timestamp pairs, missing identifiers, infinite powers and negative expected/stage predictions are rejected. Signed actual power is retained, including small negative telemetry sensor offsets. NaN in any required power excludes the entire row from the loss ledger; expected, final-modeled and actual powers remain in samples for inspection. Rows are not dropped, so energy accounting cannot interpolate across missing values.

Parameters:
  • frame (pandas.DataFrame) – Timestamps, expected/actual powers and optional cumulative stage powers.

  • stages (sequence of LossStage) – Ordered stages from the chosen baseline to the final modeled power. With no stages, the whole gap remains unexplained.

  • expected_power_column (str) – Input power column names, in W, at the same declared electrical boundary.

  • actual_power_column (str) – Input power column names, in W, at the same declared electrical boundary.

  • timestamp_column (str) – Input timestamp column. Do not combine unrelated campaign-relative times.

  • group_columns (sequence of str) – Independent series identifiers, e.g. ("panel_id",). Energy is never integrated across groups.

Return type:

PowerLossBreakdown

orbitalpv.prepare_pv_training_sample(site, *, site_id=None, background_is_negative=False, negative_geometries=None, boundary_buffer_m=20.0)[source]

Create explicit weak labels from mapped photovoltaic generator polygons.

Plant perimeters and point-only locations are not panel labels. This adapter rejects sites without usable generator polygons; for reviewed labels or other source products use rasterize_pv_labels directly. Missing map features do not establish absence of PV. Opting into background_is_negative records that assumption in the label source. Explicit negative geometries use WGS84 longitude/latitude coordinates.

Parameters:
Return type:

PVTrainingSample

orbitalpv.propagate_ground_track(omm, times, *, max_element_age_days=14, sun_positions_m=None)[source]

Propagate OMM with SGP4 and transform to WGS84 geodetic coordinates.

Velocity and its magnitude are geocentric GCRS inertial quantities, not ground speed. Altitude is height above the WGS84 ellipsoid. Illumination reuses the finite-Sun/spherical-Earth occultation model and Astropy GCRS Sun vectors; it is an estimate, not measured PV output. Optional Sun vectors must be GCRS metres at the exact supplied timestamps.

Reject naive/unsorted timestamps, SGP4 errors and element sets farther than max_element_age_days from any requested time (including future epochs). This cutoff is a display policy, not an orbital accuracy guarantee.

Parameters:
Return type:

list[GroundTrackSample]

orbitalpv.pvwatts_dc_space(effective_irradiance, cell_temperature_c, reference)[source]

Use pvlib’s PVWatts DC equation with an explicit space reference irradiance.

This is a calibrated engineering baseline, not a multi-junction radiation model.

Parameters:
Return type:

ndarray

orbitalpv.pvwatts_loss_chain(reference, *, am0_irradiance_w_m2=1361.0, illumination_fraction=1.0, cosine_aoi=1.0, spectral_factor=1.0, optical_factor=1.0, cell_temperature_c=25.0, degradation_factor=1.0, mismatch_factor=1.0, wiring_efficiency=1.0, conversion_efficiency=1.0, power_limit_w=None, availability_factor=1.0, curtailment_factor=1.0)[source]

Return a transparent sequence of modeled PV power stages, in watts.

reference specifies beginning-of-life (BOL) array DC power at its reference irradiance and cell temperature. That calibration already includes inherent cell and coverglass efficiencies: optical_factor represents an additional transmission factor relative to that reference, not another multiplication by the cell efficiency or BOL coverglass loss.

Inputs are finite scalars or nonempty one-dimensional arrays. Scalars and length-one arrays broadcast to the common sample count. Pandas Series must have identical indexes; their shared index is preserved, without sorting or label alignment. An indexed length-one Series cannot be broadcast onto a larger positional array. With no Series inputs, use a RangeIndex.

AM0 irradiance and reference.pdc0_w must be nonnegative; reference irradiance must be positive. All fractional inputs are in [0, 1], except spectral_factor, which must be positive and may exceed one. The temperature multiplier 1 + gamma * (Tcell - Tref) may produce a gain but cannot be negative. Values outside these domains are rejected rather than clipped. Zero irradiance, full eclipse and zero available power are valid. power_limit_w=None disables clipping; a finite nonnegative scalar or per-sample limit caps power after electrical conversion.

The returned columns, in sequence, are reference_power_w, after_irradiance_w, after_eclipse_w, after_pointing_w, after_spectral_w, after_optical_w, after_temperature_w, after_degradation_w, after_mismatch_w, after_wiring_w, after_conversion_w, after_clipping_w, after_availability_w, and modeled_power_w (after curtailment). The temperature stage calls pvwatts_dc_space() with the accumulated effective irradiance.

Through after_wiring_w, power is on the array DC side. Conversion is a generic DC/DC or other chosen electronics boundary; it does not imply a terrestrial AC inverter. The cap, availability and curtailment apply on that output side. Compare measurements at the same electrical boundary. Battery storage, spacecraft loads and converter standby consumption are not modeled. Set post-array factors to one and omit the cap for an array DC-only comparison.

Factors are supplied assumptions or independently established states, not inferred diagnoses. Differences between consecutive stages provide an order-dependent accounting, not unique causal attribution. Irradiance, spectral and temperature changes can create signed gains relative to the reference. This is the existing calibrated PVWatts engineering baseline, not a multi-junction spectral or radiation-damage model.

See also

pvwatts_dc_space

PVWatts DC equation with a space irradiance reference.

References

Parameters:
  • reference (PvwattsReference)

  • am0_irradiance_w_m2 (NumericInput)

  • illumination_fraction (NumericInput)

  • cosine_aoi (NumericInput)

  • spectral_factor (NumericInput)

  • optical_factor (NumericInput)

  • cell_temperature_c (NumericInput)

  • degradation_factor (NumericInput)

  • mismatch_factor (NumericInput)

  • wiring_efficiency (NumericInput)

  • conversion_efficiency (NumericInput)

  • power_limit_w (NumericInput | None)

  • availability_factor (NumericInput)

  • curtailment_factor (NumericInput)

Return type:

DataFrame

orbitalpv.quaternion_wxyz_to_matrix(quaternion_wxyz)[source]

Rotation matrix for a normalized active quaternion in (w, x, y, z) order.

The repository convention is explicit: attitude quaternions used by this function rotate vectors from the spacecraft body frame into the stated inertial/reference frame. Mission connectors must convert source conventions before calling it.

Parameters:

quaternion_wxyz (tuple[float, float, float, float] | ndarray)

Return type:

ndarray

orbitalpv.raan_from_local_solar_time_deg(local_time_hours, *, sun_right_ascension_deg=0.0, ascending=True)[source]

Convert local solar time at an equator crossing to RAAN in degrees.

Hours must be in [0, 24). Set ascending=False for a descending crossing. The returned ascending-node angle is wrapped to [0, 360). Supply the mean Sun’s right ascension for mean local solar time, or the physical Sun’s right ascension for apparent local solar time. These differ by the equation of time and must not be silently interchanged.

This sets the plane at one epoch; it does not propagate nodal precession.

Parameters:
  • local_time_hours (float)

  • sun_right_ascension_deg (float)

  • ascending (bool)

Return type:

float

orbitalpv.radiation_retention_factor(technology, fluence_1mev_e_cm2)[source]

Return empirical remaining power versus 1-MeV-electron equivalent fluence.

Built-in retention values are broad comparative assumptions, not manufacturer qualification curves. Pass a custom SpaceCellTechnology when mission-specific radiation-test data are available.

Parameters:
  • technology (str | SpaceCellTechnology)

  • fluence_1mev_e_cm2 (float)

Return type:

float

orbitalpv.rasterize_pv_labels(features, positive_geometries, *, negative_geometries=None, geometry_crs='EPSG:4326', background_is_negative=False, boundary_buffer_m=0.0)[source]

Rasterize supplied labels as 1=PV, 0=non-PV, -1=unknown.

Inputs are polygon/MultiPolygon GeoJSON geometries or Features. Pixel centres determine membership. Invalid polygons are rejected, not silently repaired. Invalid feature pixels are always unknown. The outside buffer around positive geometries remains unknown; positive interiors are not eroded. Explicit overlapping positive/negative polygons are rejected.

Outside supplied polygons remains unknown by default. Opting into background_is_negative=True treats every other valid pixel as non-PV: this is a weak assumption for incomplete OSM inventories, not ground truth. Record that choice in PVTrainingSample.label_source and any independent evaluation’s label_source.

Parameters:
Return type:

ndarray

orbitalpv.read_ground_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]

Read a WGS84 area from one HTTPS GeoTIFF asset at native resolution.

bbox is (west, south, east, north) in longitude/latitude degrees. The crop covers the transformed bounding rectangle, rounded outward to source pixels; it is not an exact polygon clip. The selected tile must cover the entire crop. Select another tile or mosaic explicitly when an area crosses a tile edge.

max_pixels limits the total band samples (bands * rows * columns) before pixel data are read. COG range reads retrieve the intersecting compressed blocks, which can be larger than the requested pixel window. Different assets retain their native grids (e.g. RGB 10 m, SCL 20 m). No reprojection, resampling, reflectance scaling or cloud mask occurs.

Parameters:
Return type:

GroundImage

orbitalpv.save_pv_prediction(prediction, destination, *, overwrite=False)[source]

Export WGS84 GeoJSON, native-grid scores/mask, and prediction metadata.

pv_prediction.tif contains float32 class scores in band 1 and a 0/1 area-filtered mask in band 2; invalid pixels have nodata -9999 in both. This is a derived model output, not a raw Sentinel-2 asset. Model weights are saved separately with PVFootprintModel.save. Existing outputs require explicit overwrite, and a partial failure can leave earlier completed files in the destination directory.

Parameters:
  • prediction (PVFootprintPrediction)

  • destination (str | Path)

  • overwrite (bool)

Return type:

dict[str, Path]

orbitalpv.seasonal_lag_vi_forecast(data, *, period_steps)[source]

Use a historical seasonal/orbit-lag baseline with explicitly chosen lag.

A sample period is an empirical assumption, not a propagated orbit. Every needed lag (period minus horizon) must be present in data. No future values are accessed when a horizon exceeds the chosen period: it raises.

Parameters:
  • data (LaggedVIData)

  • period_steps (int)

Return type:

ndarray

orbitalpv.simulate_space_cell(technology, *, irradiance_w_m2=1361.0, cell_temperature_c=28.0, fluence_1mev_e_cm2=0.0, points=400)[source]

Simulate an empirical AM0 I-V and P-V curve for a space cell.

Current scales approximately linearly with irradiance and an exposed radiation-retention factor. Voltage includes a logarithmic irradiance term and technology-specific temperature scaling. The I-V curve is shaped to reproduce the technology reference Voc, Vmp, Jsc and Jmp at AM0 conditions.

This model is intended for system studies, comparisons and early mission design. It does not replace junction-resolved spectral/radiation models.

Parameters:
  • technology (str | SpaceCellTechnology)

  • irradiance_w_m2 (float)

  • cell_temperature_c (float)

  • fluence_1mev_e_cm2 (float)

  • points (int)

Return type:

SpaceCellSimulation

orbitalpv.single_diode_points(effective_irradiance_w_m2, cell_temperature_c, params)[source]

pvlib De Soto + single-diode reference path for single-junction cells.

This is deliberately separated from multi-junction space-cell modeling. It is useful for silicon/single-junction experiments, model validation, and as a familiar pvlib baseline, but it should not be presented as a native III-V multi-junction model.

Parameters:
Return type:

dict[str, ndarray]

orbitalpv.summarize_power_losses(breakdown, *, max_gap_s)[source]

Integrate a power ledger on common, observed intervals only.

max_gap_s is a required positive, finite maximum interval length in seconds. An interval contributes only when both endpoint rows are valid for all required powers and their separation is at most this threshold. Missing rows remain boundaries; no missing energy is filled or extrapolated. Each group uses its own recorded first-to-last time span for coverage. Coverage does not include any unrecorded time before or after that span.

Power is assumed to vary linearly between accepted endpoints, giving trapezoidal energy integrals. Positive losses and gains split this line exactly where it crosses zero. Event discontinuities and packet timing uncertainty still require suitable sampling; the cutoff is not a claim that the intervening power is known. Choose it from the measurement cadence and context rather than applying a universal default.

All stages, categories and total powers use the same interval mask, so net loss energy reconciles exactly (up to floating-point rounding). Percentages use expected energy over these same intervals; they are signed and are not normalized to make the loss buckets sum to 100%.

Parameters:
Return type:

PowerLossSummary

orbitalpv.sun_synchronous_inclination_deg(altitude_m)[source]

Estimate circular sun-synchronous inclination from first-order J2.

Match -1.5 * J2 * n * (R/a)**2 * cos(i) to one eastward node revolution per 365.2422-day tropical year. The result is a mean-element design approximation; it omits higher harmonics, drag and short-period effects. It does not imply uninterrupted sunlight.

Raises ValueError when altitude is invalid or J2 alone cannot provide the required precession at that altitude.

Parameters:

altitude_m (float)

Return type:

float

Orbit helpers#

Orbit and geometry helpers for the public OrbitalPV API.

class orbitalpv.orbit.GroundTrackSample(timestamp: 'datetime', longitude_deg: 'float', latitude_deg: 'float', altitude_m: 'float', speed_m_s: 'float', velocity_gcrs_m_s: 'tuple[float, float, float]', illumination_fraction: 'float')[source]
Parameters:
class orbitalpv.orbit.SolarGeometry(sun_vector_m: 'tuple[float, float, float]', sun_distance_m: 'float', sun_unit_vector: 'tuple[float, float, float]', illumination_fraction: 'float', cosine_aoi: 'float | None' = None)[source]
Parameters:
orbitalpv.orbit.circular_eclipse_duration_s(altitude_m, beta_angle_deg)[source]

Estimate eclipse duration per circular orbit with a cylindrical shadow.

beta_angle_deg is the signed angle between the Earth-to-Sun direction and the orbital plane, in [-90, 90]. Returns seconds as an array with the input beta shape (a zero-dimensional array for a scalar).

A spherical Earth and a point Sun at infinite distance are assumed. The eclipse half-angle is acos(sqrt(1 - (R/a)**2) / cos(beta)) below the critical beta asin(R/a); above it the duration is zero. Finite solar radius, penumbra, atmosphere and oblateness are omitted. In particular, zero here is not proof of uninterrupted full sunlight: use earth_occultation_fraction() for a finite-Sun geometry check.

See NASA’s spacecraft thermal-environment course, slides 110-119: https://ntrs.nasa.gov/api/citations/20200007746/downloads/20200007746.pdf

Parameters:
Return type:

ndarray

orbitalpv.orbit.circular_orbit_period_s(altitude_m)[source]

Return the two-body period of a circular Earth orbit in seconds.

altitude_m is a finite, positive height above the equatorial Earth radius. This is a design estimate, without perturbations or station keeping.

Parameters:

altitude_m (float)

Return type:

float

orbitalpv.orbit.circular_orbit_positions_m(altitude_m, inclination_deg, *, raan_deg=0.0, argument_of_periapsis_deg=0.0, samples=721, earth_radius_m=6378137.0)[source]

Generate positions for a circular orbit at a fixed altitude.

Parameters:
Return type:

ndarray

orbitalpv.orbit.geocentric_sun_positions_m(times)[source]

Geocentric GCRS Sun positions using Astropy’s supported solar ephemeris path.

Parameters:

times (Sequence[datetime] | Sequence[str])

Return type:

ndarray

orbitalpv.orbit.ground_track_deg_from_eci(positions_m, elapsed_seconds, *, earth_rotation_rate_rad_s=7.2921159e-05)[source]

Convert simple ECI positions to a spherical Earth-fixed ground track.

The transform assumes a uniformly rotating spherical Earth and a zero Greenwich angle at elapsed time zero. Use Astropy/ITRS or SPICE for mission-grade frame transformations.

Parameters:
Return type:

tuple[ndarray, ndarray]

orbitalpv.orbit.keplerian_orbit_positions_m(semi_major_axis_m, eccentricity, inclination_deg, *, raan_deg=0.0, argument_of_periapsis_deg=0.0, true_anomaly_rad=None, samples=721)[source]

Generate Keplerian ellipse positions in a simple ECI frame.

This convenience helper is intended for deterministic examples and design visualization. Operational propagation should use OMM/TLE/SGP4 or SPICE.

Parameters:
Return type:

ndarray

orbitalpv.orbit.omm_epoch(omm)[source]

Parse GP EPOCH; timezone-free OMM epochs are UTC per the GP contract.

Parameters:

omm (dict[str, object])

Return type:

datetime

orbitalpv.orbit.propagate_ground_track(omm, times, *, max_element_age_days=14, sun_positions_m=None)[source]

Propagate OMM with SGP4 and transform to WGS84 geodetic coordinates.

Velocity and its magnitude are geocentric GCRS inertial quantities, not ground speed. Altitude is height above the WGS84 ellipsoid. Illumination reuses the finite-Sun/spherical-Earth occultation model and Astropy GCRS Sun vectors; it is an estimate, not measured PV output. Optional Sun vectors must be GCRS metres at the exact supplied timestamps.

Reject naive/unsorted timestamps, SGP4 errors and element sets farther than max_element_age_days from any requested time (including future epochs). This cutoff is a display policy, not an orbital accuracy guarantee.

Parameters:
Return type:

list[GroundTrackSample]

orbitalpv.orbit.quaternion_wxyz_to_matrix(quaternion_wxyz)[source]

Rotation matrix for a normalized active quaternion in (w, x, y, z) order.

The repository convention is explicit: attitude quaternions used by this function rotate vectors from the spacecraft body frame into the stated inertial/reference frame. Mission connectors must convert source conventions before calling it.

Parameters:

quaternion_wxyz (tuple[float, float, float, float] | ndarray)

Return type:

ndarray

orbitalpv.orbit.raan_from_local_solar_time_deg(local_time_hours, *, sun_right_ascension_deg=0.0, ascending=True)[source]

Convert local solar time at an equator crossing to RAAN in degrees.

Hours must be in [0, 24). Set ascending=False for a descending crossing. The returned ascending-node angle is wrapped to [0, 360). Supply the mean Sun’s right ascension for mean local solar time, or the physical Sun’s right ascension for apparent local solar time. These differ by the equation of time and must not be silently interchanged.

This sets the plane at one epoch; it does not propagate nodal precession.

Parameters:
  • local_time_hours (float)

  • sun_right_ascension_deg (float)

  • ascending (bool)

Return type:

float

orbitalpv.orbit.sun_synchronous_inclination_deg(altitude_m)[source]

Estimate circular sun-synchronous inclination from first-order J2.

Match -1.5 * J2 * n * (R/a)**2 * cos(i) to one eastward node revolution per 365.2422-day tropical year. The result is a mean-element design approximation; it omits higher harmonics, drag and short-period effects. It does not imply uninterrupted sunlight.

Raises ValueError when altitude is invalid or J2 alone cannot provide the required precession at that altitude.

Parameters:

altitude_m (float)

Return type:

float

PV helpers#

Space-PV reference models exposed through the public package.

class orbitalpv.pv.DeSotoParameters(alpha_sc: 'float', a_ref: 'float', i_l_ref: 'float', i_o_ref: 'float', r_sh_ref: 'float', r_s: 'float', eg_ref: 'float' = 1.121, degdt: 'float' = -0.0002677)[source]
Parameters:
class orbitalpv.pv.PvwattsReference(pdc0_w, gamma_pdc_per_c, reference_irradiance_w_m2=1361.0, reference_temperature_c=25.0)[source]

Calibrated BOL DC reference for a spacecraft panel/array.

pdc0_w is defined at reference_irradiance_w_m2 and reference_temperature_c. For space PV, this is intentionally a calibration contract instead of assuming a terrestrial STC reference is physically meaningful for every cell technology.

Parameters:
  • pdc0_w (float)

  • gamma_pdc_per_c (float)

  • reference_irradiance_w_m2 (float)

  • reference_temperature_c (float)

orbitalpv.pv.effective_irradiance_w_m2(am0_irradiance_w_m2, illumination_fraction, cosine_aoi, *, spectral_factor=1.0, optical_factor=1.0)[source]

Convert space environment/geometry state into cell-effective irradiance.

Parameters:
Return type:

ndarray

orbitalpv.pv.pvwatts_dc_space(effective_irradiance, cell_temperature_c, reference)[source]

Use pvlib’s PVWatts DC equation with an explicit space reference irradiance.

This is a calibrated engineering baseline, not a multi-junction radiation model.

Parameters:
Return type:

ndarray

orbitalpv.pv.pvwatts_loss_chain(reference, *, am0_irradiance_w_m2=1361.0, illumination_fraction=1.0, cosine_aoi=1.0, spectral_factor=1.0, optical_factor=1.0, cell_temperature_c=25.0, degradation_factor=1.0, mismatch_factor=1.0, wiring_efficiency=1.0, conversion_efficiency=1.0, power_limit_w=None, availability_factor=1.0, curtailment_factor=1.0)[source]

Return a transparent sequence of modeled PV power stages, in watts.

reference specifies beginning-of-life (BOL) array DC power at its reference irradiance and cell temperature. That calibration already includes inherent cell and coverglass efficiencies: optical_factor represents an additional transmission factor relative to that reference, not another multiplication by the cell efficiency or BOL coverglass loss.

Inputs are finite scalars or nonempty one-dimensional arrays. Scalars and length-one arrays broadcast to the common sample count. Pandas Series must have identical indexes; their shared index is preserved, without sorting or label alignment. An indexed length-one Series cannot be broadcast onto a larger positional array. With no Series inputs, use a RangeIndex.

AM0 irradiance and reference.pdc0_w must be nonnegative; reference irradiance must be positive. All fractional inputs are in [0, 1], except spectral_factor, which must be positive and may exceed one. The temperature multiplier 1 + gamma * (Tcell - Tref) may produce a gain but cannot be negative. Values outside these domains are rejected rather than clipped. Zero irradiance, full eclipse and zero available power are valid. power_limit_w=None disables clipping; a finite nonnegative scalar or per-sample limit caps power after electrical conversion.

The returned columns, in sequence, are reference_power_w, after_irradiance_w, after_eclipse_w, after_pointing_w, after_spectral_w, after_optical_w, after_temperature_w, after_degradation_w, after_mismatch_w, after_wiring_w, after_conversion_w, after_clipping_w, after_availability_w, and modeled_power_w (after curtailment). The temperature stage calls pvwatts_dc_space() with the accumulated effective irradiance.

Through after_wiring_w, power is on the array DC side. Conversion is a generic DC/DC or other chosen electronics boundary; it does not imply a terrestrial AC inverter. The cap, availability and curtailment apply on that output side. Compare measurements at the same electrical boundary. Battery storage, spacecraft loads and converter standby consumption are not modeled. Set post-array factors to one and omit the cap for an array DC-only comparison.

Factors are supplied assumptions or independently established states, not inferred diagnoses. Differences between consecutive stages provide an order-dependent accounting, not unique causal attribution. Irradiance, spectral and temperature changes can create signed gains relative to the reference. This is the existing calibrated PVWatts engineering baseline, not a multi-junction spectral or radiation-damage model.

See also

pvwatts_dc_space

PVWatts DC equation with a space irradiance reference.

References

Parameters:
  • reference (PvwattsReference)

  • am0_irradiance_w_m2 (NumericInput)

  • illumination_fraction (NumericInput)

  • cosine_aoi (NumericInput)

  • spectral_factor (NumericInput)

  • optical_factor (NumericInput)

  • cell_temperature_c (NumericInput)

  • degradation_factor (NumericInput)

  • mismatch_factor (NumericInput)

  • wiring_efficiency (NumericInput)

  • conversion_efficiency (NumericInput)

  • power_limit_w (NumericInput | None)

  • availability_factor (NumericInput)

  • curtailment_factor (NumericInput)

Return type:

DataFrame

orbitalpv.pv.single_diode_points(effective_irradiance_w_m2, cell_temperature_c, params)[source]

pvlib De Soto + single-diode reference path for single-junction cells.

This is deliberately separated from multi-junction space-cell modeling. It is useful for silicon/single-junction experiments, model validation, and as a familiar pvlib baseline, but it should not be presented as a native III-V multi-junction model.

Parameters:
Return type:

dict[str, ndarray]

Space cell simulator#

Empirical AM0 space-solar-cell technology simulator.

The built-in technology templates are educational/reference parameterizations anchored to published NASA space-PV performance ranges and representative datasheet-style AM0 points. They are not qualification models for a specific manufacturer part.

For multijunction devices, OrbitalPV uses an empirical I-V shape rather than a terrestrial single-diode model because junction-specific spectral response, current matching, tunnel junctions, radiation damage and temperature behavior must ultimately be modelled separately for mission-grade work.

class orbitalpv.cells.SpaceCellSimulation(technology, irradiance_w_m2, cell_temperature_c, fluence_1mev_e_cm2, radiation_factor, voltage_v, current_density_ma_cm2, power_density_w_m2, voc_v, isc_ma_cm2, vmp_v, imp_ma_cm2, pmp_w_m2, efficiency)[source]

Simulated I-V/P-V result for one cell technology and operating point.

Parameters:
class orbitalpv.cells.SpaceCellTechnology(slug, name, family, junctions, efficiency_am0, voc_v, vmp_v, jsc_ma_cm2, jmp_ma_cm2, temp_coeff_current_per_c, temp_coeff_voltage_per_c, radiation_retention_at_1e15, reference_temperature_c=28.0, reference_irradiance_w_m2=1361.0, notes='')[source]

Reference parameterization for a space photovoltaic cell technology.

Parameters:
orbitalpv.cells.get_space_cell_technology(name)[source]

Resolve a built-in technology by slug or common alias.

Parameters:

name (str)

Return type:

SpaceCellTechnology

orbitalpv.cells.list_space_cell_technologies()[source]

Return the built-in space-cell technology templates.

Return type:

tuple[SpaceCellTechnology, …]

orbitalpv.cells.radiation_retention_factor(technology, fluence_1mev_e_cm2)[source]

Return empirical remaining power versus 1-MeV-electron equivalent fluence.

Built-in retention values are broad comparative assumptions, not manufacturer qualification curves. Pass a custom SpaceCellTechnology when mission-specific radiation-test data are available.

Parameters:
  • technology (str | SpaceCellTechnology)

  • fluence_1mev_e_cm2 (float)

Return type:

float

orbitalpv.cells.simulate_space_cell(technology, *, irradiance_w_m2=1361.0, cell_temperature_c=28.0, fluence_1mev_e_cm2=0.0, points=400)[source]

Simulate an empirical AM0 I-V and P-V curve for a space cell.

Current scales approximately linearly with irradiance and an exposed radiation-retention factor. Voltage includes a logarithmic irradiance term and technology-specific temperature scaling. The I-V curve is shaped to reproduce the technology reference Voc, Vmp, Jsc and Jmp at AM0 conditions.

This model is intended for system studies, comparisons and early mission design. It does not replace junction-resolved spectral/radiation models.

Parameters:
  • technology (str | SpaceCellTechnology)

  • irradiance_w_m2 (float)

  • cell_temperature_c (float)

  • fluence_1mev_e_cm2 (float)

  • points (int)

Return type:

SpaceCellSimulation

Analytics#

Performance analytics exposed through the public package.

class orbitalpv.analytics.LogPowerTrend(slope_per_year, slope_lower_per_year, slope_upper_per_year, annual_loss_fraction, loss_detected)[source]

Log-power slope and drift-expanded confidence interval, in year⁻¹.

Parameters:
  • slope_per_year (float)

  • slope_lower_per_year (float)

  • slope_upper_per_year (float)

  • annual_loss_fraction (float)

  • loss_detected (bool)

class orbitalpv.analytics.LossStage(name, power_column, category, evidence)[source]

One ordered, cumulative power prediction with a declared evidence basis.

power_column contains the prediction after this stage, not an independent loss estimate. Its contribution is the preceding prediction minus this prediction. evidence should identify the measurement, model, operating flag or explicit scenario assumption supporting the attribution. This label records the caller’s evidence; it does not verify causality.

category must be a key in LOSS_CATEGORIES, except unexplained which is reserved for the final model-minus-actual residual. Names must be unique snake_case identifiers within a breakdown.

Parameters:
  • name (str)

  • power_column (str)

  • category (str)

  • evidence (str)

class orbitalpv.analytics.MonitoringDesign(observations, duration_days, slope_standard_error_per_year, minimum_detectable_annual_loss, confidence, detection_probability, drift_bound_per_year)[source]

Conditional Gaussian detection capability; annual losses are fractions.

Parameters:
  • observations (int)

  • duration_days (float)

  • slope_standard_error_per_year (float)

  • minimum_detectable_annual_loss (float)

  • confidence (float)

  • detection_probability (float)

  • drift_bound_per_year (float)

class orbitalpv.analytics.PowerLossBreakdown(samples, components_w, categories_w, stages, group_columns)[source]

Power ledger returned by power_loss_breakdown().

samples contains sorted timestamps, group identifiers, power predictions, signed total/attributed/unexplained losses and a common valid mask. components_w contains a column per stage plus unexplained. categories_w combines stage contributions into reporting buckets. The three frames share the same positional index. Positive values are losses; negative values are gains. Treat these frames as read-only inputs to summarize_power_losses().

Parameters:
class orbitalpv.analytics.PowerLossSummary(totals, components, categories)[source]

Observed-interval energy totals, components and categories, all in Wh.

totals reports the signed energy gap and common observation coverage per input group. components and categories report signed net_loss_wh, nonnegative loss_wh / gain_wh and the signed percentage of expected energy. Percentages are NaN when expected energy is zero. All energy values are NaN when there are no usable intervals.

Net contributions reconcile with the total gap. Gross positive/negative contributions can cancel between components, so their separate sums need not equal the total positive gap or total surplus.

Parameters:
orbitalpv.analytics.add_robust_baseline(frame, *, reference_samples=500)[source]

Add a telemetry-only upper-envelope normalization.

Case 0 has no trusted Sun/eclipse/attitude state. Normalizing against a high reference quantile is intentionally safer than treating every low-power sample as a fault. Fault screening happens on daily upper-envelope health, not samples.

Parameters:
Return type:

DataFrame

orbitalpv.analytics.design_degradation_monitoring(time_days, covariance, *, confidence=0.95, detection_probability=0.8, drift_bound_per_year=0.0)[source]

Plan detection of a negative constant log-power slope with known noise.

GLS covariance is (X.T @ C^-1 @ X)^-1. Reject zero slope when the two-sided confidence interval’s upper endpoint is negative. For a bounded unknown linear calibration drift ±d, the interval expands by d. Guaranteeing the requested detection probability at the worst opposing drift requires a loss magnitude of (z_confidence + z_probability) * slope_se + 2*d. Annual retained power is exp(slope); loss is 1-exp(slope).

This is conditional on known Gaussian covariance and a constant physical slope. It is not a qualification or a forecast of perovskite lifetime.

Parameters:
  • time_days (ArrayLike)

  • covariance (ArrayLike)

  • confidence (float)

  • detection_probability (float)

  • drift_bound_per_year (float)

Return type:

MonitoringDesign

orbitalpv.analytics.fit_log_power_trend(time_days, normalized_power, covariance, *, confidence=0.95, drift_bound_per_year=0.0)[source]

Fit one normalized device series with externally supplied log covariance.

No residual variance rescaling is performed: covariance must come from calibration/replicates or an explicitly labeled scenario. Do not combine devices, eclipse samples, bus-load-limited power, or unmatched IV sweeps. Confidence bounds include a bounded linear drift but not normalization bias, nonlinear aging, hysteresis, recovery, seasonality or unmodeled change points.

Parameters:
  • time_days (ArrayLike)

  • normalized_power (ArrayLike)

  • covariance (ArrayLike)

  • confidence (float)

  • drift_bound_per_year (float)

Return type:

LogPowerTrend

orbitalpv.analytics.log_power_covariance(time_days, *, independent_sigma, correlated_sigma=0.0, correlation_days=7.0)[source]

Construct log-power covariance: white noise plus an exponential kernel.

Sigmas are standard deviations in natural-log power (dimensionless), not percentage points. They approximate relative errors only for small noise. The kernel is a declared planning assumption, not a fitted instrument model.

Parameters:
  • time_days (ArrayLike)

  • independent_sigma (float)

  • correlated_sigma (float)

  • correlation_days (float)

Return type:

ndarray

orbitalpv.analytics.power_loss_breakdown(frame, stages=(), *, expected_power_column='expected_power_w', actual_power_column='actual_power_w', timestamp_column='timestamp', group_columns=())[source]

Explain expected-minus-actual power using ordered cumulative predictions.

For stages P1, ..., Pn and a declared expected baseline P0, the signed contributions are P0-P1, P1-P2, ..., P(n-1)-Pn. The unexplained remainder is Pn-actual. Thus all contributions sum to expected-actual at every valid sample, including gains.

Use an ideal reference baseline for a design loss budget, or a healthy operating model for underperformance analysis. Effects already included in the expected baseline must not be subtracted again. Attribution is order-dependent and conditional on the supplied evidence; this function does not diagnose causes from the residual or normalize supplied losses.

Inputs must be already time-aligned in one DataFrame. Timestamps are converted to UTC (naive timestamps are assumed UTC), then sorted within each group. Duplicate group/timestamp pairs, missing identifiers, infinite powers and negative expected/stage predictions are rejected. Signed actual power is retained, including small negative telemetry sensor offsets. NaN in any required power excludes the entire row from the loss ledger; expected, final-modeled and actual powers remain in samples for inspection. Rows are not dropped, so energy accounting cannot interpolate across missing values.

Parameters:
  • frame (pandas.DataFrame) – Timestamps, expected/actual powers and optional cumulative stage powers.

  • stages (sequence of LossStage) – Ordered stages from the chosen baseline to the final modeled power. With no stages, the whole gap remains unexplained.

  • expected_power_column (str) – Input power column names, in W, at the same declared electrical boundary.

  • actual_power_column (str) – Input power column names, in W, at the same declared electrical boundary.

  • timestamp_column (str) – Input timestamp column. Do not combine unrelated campaign-relative times.

  • group_columns (sequence of str) – Independent series identifiers, e.g. ("panel_id",). Energy is never integrated across groups.

Return type:

PowerLossBreakdown

orbitalpv.analytics.summarize_power_losses(breakdown, *, max_gap_s)[source]

Integrate a power ledger on common, observed intervals only.

max_gap_s is a required positive, finite maximum interval length in seconds. An interval contributes only when both endpoint rows are valid for all required powers and their separation is at most this threshold. Missing rows remain boundaries; no missing energy is filled or extrapolated. Each group uses its own recorded first-to-last time span for coverage. Coverage does not include any unrecorded time before or after that span.

Power is assumed to vary linearly between accepted endpoints, giving trapezoidal energy integrals. Positive losses and gains split this line exactly where it crosses zero. Event discontinuities and packet timing uncertainty still require suitable sampling; the cutoff is not a claim that the intervening power is known. Choose it from the measurement cadence and context rather than applying a universal default.

All stages, categories and total powers use the same interval mask, so net loss energy reconciles exactly (up to floating-point rounding). Percentages use expected energy over these same intervals; they are signed and are not normalized to make the loss buckets sum to 100%.

Parameters:
Return type:

PowerLossSummary

Data helpers#

Data-loading, connector, and deterministic demonstration helpers.

class orbitalpv.data.ArxivConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

One explicit paper per request; reuse cache and observe arXiv rate limits.

The original Atom bytes are cached with SHA-256, URL and retrieval time. This connector does not extract or promote scientific claims from PDFs. Downloading an accessible paper does not grant redistribution rights.

Parameters:
paper(paper_id, *, cache_path=None, refresh=False)[source]

Fetch pinned metadata, or validate and read its existing local cache.

Parameters:
Return type:

ResearchResponse

download_paper(paper_id, destination, *, max_bytes=20000000)[source]

Download a selected version with a checksum receipt; no bulk crawl.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.data.BirdsEPSConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Connector for the public BIRDS on-orbit EPS dataset.

Parameters:
download(satellite, destination)[source]

Download one satellite workbook from the upstream BIRDS repository.

Parameters:
Return type:

DownloadReceipt

download_frame(satellite, destination, *, normalized=True, campaign_year=None)[source]

Download and load a BIRDS EPS workbook.

campaign_year supplies the year only for campaign sheet names that omit it; see load_birds_eps_workbook() for the time convention.

Parameters:
  • satellite (str)

  • destination (str | Path)

  • normalized (bool)

  • campaign_year (int | None)

Return type:

DataFrame

class orbitalpv.data.DataverseConnector(*, base_url='https://darus.uni-stuttgart.de', timeout_s=30.0)[source]

Public Dataverse search and versioned dataset access; defaults to DaRUS.

Another public installation can be selected with base_url. Dataset and file licenses are provider-specific. Private/restricted data are not fetched.

Parameters:
search(query, *, start=0, page_size=25, cache_path=None, refresh=False)[source]

Search public datasets; start is a zero-based record offset.

Parameters:
Return type:

ResearchResponse

dataset(persistent_id, *, version=':latest-published', cache_path=None, refresh=False)[source]

Fetch published dataset metadata; pin version='1.0' for reproducibility.

Parameters:
Return type:

ResearchResponse

download_file(persistent_id, filename, destination, *, version=':latest-published', max_bytes=100000000)[source]

Download the original public file and verify its dataset checksum.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.data.DiscosConnector(*, token, timeout_s=30.0)[source]

ESA DISCOS v2 metadata; free registration and an explicit token required.

DISCOS IDs and NORAD catalog numbers are different identifiers. This API supplies object/launch metadata, not ephemerides or universal PV ratings.

Parameters:
objects(*, filter_expression=None, page=1, page_size=100, cache_path=None, refresh=False)[source]

Get one page of objects using the provider’s filter syntax.

Parameters:
  • filter_expression (str | None)

  • page (int)

  • page_size (int)

  • cache_path (str | Path | None)

  • refresh (bool)

Return type:

ResearchResponse

object(discos_id, *, cache_path=None, refresh=False)[source]

Retrieve one object by its DISCOS internal ID.

Parameters:
Return type:

ResearchResponse

by_norad(norad_id, *, cache_path=None, refresh=False)[source]

Search the NORAD satno field; preserve an empty or ambiguous result.

Parameters:
Return type:

ResearchResponse

class orbitalpv.data.DonkiConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NASA CCMC DONKI event catalog, accessed directly without a NASA API key.

Uses the September 2026 CCMC endpoint, not the retired kauai host. Events are research context, not spacecraft-specific dose or causation evidence. Follow CCMC’s attribution and publication rules for event studies.

Parameters:
events(event_type, *, start, stop, cache_path=None, refresh=False)[source]

Get an explicit UTC date window (provider endDate is inclusive).

The raw empty response may be null or an empty list. Event links and associated instruments/spacecraft are kept, without assigning them to other missions.

Parameters:
Return type:

ResearchResponse

class orbitalpv.data.FlyingLaptopConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve CC BY 4.0 Flying Laptop monthly archives from DaRUS.

The archive contains many housekeeping packets. The normalizer reads only packet 4900, whose calibrated array currents and voltages have documented units of A and V. Downloads retain a checksum-bearing provenance sidecar.

Parameters:
download_month(month, destination)[source]

Download one YYYY-MM archive after checking its catalog checksum.

Parameters:
Return type:

DownloadReceipt

download_frame(month, destination, *, time_min=None, time_max=None)[source]

Download a month and normalize the requested UTC time interval.

Parameters:
Return type:

DataFrame

class orbitalpv.data.GHSLSettlementConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve JRC GHS-SMOD context while preserving its edition and epoch.

The official R2023A V2.0 global ZIP is downloaded once and reused; the 2015 archive is about 29 MB. Only a bounded native-resolution window is read into memory. The ZIP size is capped before and during downloading, and its member is validated before Rasterio opens it.

Original R2019A downloads are no longer served at the official URL as of October 2026. Use edition='R2019A', source_path=... with a retained native historical GeoTIFF. No fallback to a different edition occurs.

Parameters:
fetch_settlement(*, bbox, cache_path, source_cache_dir=None, source_path=None, edition='R2023A', epoch=2015, refresh=False, offline=False, max_download_bytes=67108864, max_pixels=1000000)[source]

Return a native crop for WGS84 (west, south, east, north).

offline permits an existing validated crop or local source, and prevents HTTP calls. refresh replaces a crop from the same source; archived versioned source files remain cached. A local source_path is hashed and its edition/epoch are caller declarations recorded in provenance; filenames alone cannot verify those declarations.

Parameters:
Return type:

SettlementRaster

class orbitalpv.data.GPCache(path)[source]

Cache provider queries for at least two hours, including across restarts.

SQLite serializes downloads from processes sharing this local file. Any HTTP or malformed-response error pauses the entire provider until an operator calls resume(). Existing snapshots remain available with an explicit warning; the orbit layer separately rejects old element epochs.

Share one cache per deployment, on a local filesystem. Multiple hosts need a single ingestion service, not independent caches behind the same IP.

Parameters:

path (str | Path)

resume(source)[source]

Resume downloads after a human investigates a provider failure.

Parameters:

source (str)

Return type:

None

class orbitalpv.data.GPSnapshot(records: 'list[dict[str, Any]]', source: 'str', retrieved_at: 'datetime', sha256: 'str', cache_stale: 'bool' = False, warning: 'str | None' = None)[source]
Parameters:
class orbitalpv.data.GroundImage(data, crs, transform, bounds, scene_id, asset_key, source_url, asset_metadata, bbox_wgs84, item_metadata, nodata_values, retrieved_at)[source]

A native-resolution rectangular crop, retaining raw pixel semantics.

data has shape (bands, rows, columns); True mask entries mean missing data. transform holds affine (a, b, c, d, e, f) coefficients and bounds is (left, bottom, right, top) in crs. Pixel-aligned bounds can extend slightly beyond the requested bbox_wgs84.

visual is a rendered RGB product, not calibrated reflectance. scl is a categorical scene-classification product, not a power or irradiance measurement. No cloud masking is applied implicitly.

Parameters:
reflectance()[source]

Return raw * scale + offset using explicit STAC band metadata.

Only assets declaring the reflectance role are accepted. Missing data remain masked before calibration; negative reflectance values are retained. The raw data is never modified. For example, Collection 1 commonly declares scale 0.0001 and offset -0.1, so dividing every product by 10000 without its offset would be wrong.

Return type:

MaskedArray

save_geotiff(destination, *, overwrite=False)[source]

Save raw pixels, georeferencing, calibration and provenance.

The .meta.json sidecar includes the complete source STAC item, asset metadata, requested/actual bounds and the output SHA-256. The checksum identifies this derived crop, not the original full tile. A GeoTIFF internal mask is used when all band masks agree. Distinct band masks are retained through a shared nodata value when possible; unsupported mask combinations raise rather than discard information.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.data.HorizonsConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Public NASA/JPL ephemerides for supported targets, including spacecraft.

Returns the original JSON envelope containing the ephemeris text, headers, units and API signature. Vectors use ICRF axes, TDB time, geometric (no light-time) corrections and AU/day units. No spacecraft attitude or PV output is implied. Target coverage is determined by JPL.

Parameters:
vectors(target, *, start, stop, step='1 d', center='500@10', cache_path=None, refresh=False)[source]

Retrieve geometric vectors; default center is the Sun’s center.

Dates are YYYY-MM-DD in TDB, with both endpoints requested. The provider may omit the final instant if the step does not land on it. Negative spacecraft IDs (e.g. '-61' for Juno) avoid ambiguous name matches.

Parameters:
Return type:

ResearchResponse

class orbitalpv.data.LisirdConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve bounded, measured TSIS-1/SORCE irradiance datasets.

The LaTiS jsond response carries parameter order and units. Cache files contain the original JSON bytes plus a .meta.json sidecar binding the response to its dataset, time range and SHA-256. Reusing a different query with the same cache path raises an error instead of returning stale data. Data access is public; retain LASP/instrument-team attribution and consult the product release notes for the version used.

Parameters:
total_solar_irradiance(dataset_id='tsis_tsi_24hr', *, time_min, time_max, cache_path=None)[source]

Return measured daily or six-hourly TSI in W/m².

The interval is [time_min, time_max) in UTC, applied to the nominal averaging-bin timestamp. At-1-AU and actual-Earth-distance irradiances remain separate. Source zero fill values become NaN; missing intervals are not interpolated. valid_measurement requires both irradiances to be finite and positive. provisional_flag is preserved when present and is not interpreted as a missing-value flag.

Parameters:
Return type:

DataFrame

spectral_irradiance(dataset_id='tsis_ssi_24hr', *, time_min, time_max, cache_path=None)[source]

Return measured TSIS-1 SIM spectra as wavelength-resolved rows.

Wavelength is in nm, irradiance in W/m²/nm, and the time interval is end-exclusive. All source quality bits are retained as quality_flag; quality_good conservatively selects zero-flag bins. Flagged bins remain in the frame. Do not integrate across missing or rejected spectral intervals or assume this 200–2400 nm product covers all TSI. At most 31 days may be requested per call to bound response size.

Parameters:
Return type:

DataFrame

class orbitalpv.data.N2YOConnector(*, api_key=None, timeout_s=30)[source]

N2YO REST v1. Keep API keys on the server, outside browser bundles.

Positions are provider predictions, not satellite GPS telemetry. The free service documents 1,000 position calls/hour and at most 300 samples/call. No retries are made here. Bulk tracking should use cached GP + local SGP4. https://www.n2yo.com/api/

Parameters:
  • api_key (str | None)

  • timeout_s (float)

positions(norad_id, *, observer_lat, observer_lon, observer_alt_m=0, seconds=60)[source]

Return the provider’s timestamped position JSON, including provenance.

sataltitude in the provider payload is km; observer altitude is m. Element epoch is not supplied by this endpoint and remains unknown.

Parameters:
Return type:

dict[str, Any]

class orbitalpv.data.NoaaSwpcConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NOAA Space Weather Prediction Center JSON feed connector.

Parameters:
solar_wind_magnetic_field()[source]

Return native real-time solar-wind magnetic-field records (L1).

Preserve provider coordinates, spacecraft identity and quality fields. This is upstream solar-wind context, not a local spacecraft field model.

Return type:

Any

solar_activity(product, *, cache_path=None, refresh=False)[source]

Return UTC X-ray, Kp or alert records with source provenance.

Products are xrays (primary GOES, rolling six hours), kp (estimated planetary Kp), and alerts (provider bulletin text). Original fields are retained. A cache is a frozen snapshot until explicitly refreshed; inspect timestamp/retrieved_at for freshness. X-rays are band-limited irradiance, not total sunlight or PV power.

Parameters:
Return type:

DataFrame

goes_integral_particle_flux(particle, *, role='primary', period='7-day', cache_path=None, refresh=False)[source]

Fetch measured GOES integral proton or electron flux.

period selects a rolling 6-hour, 1-day, 3-day or 7-day observation feed. This is not a historical-date API. role is primary or secondary; the actual GOES number is retained for each record.

A cache stores the original response with a JSON provenance sidecar. Subsequent calls reuse that exact snapshot unless refresh=True. A mismatched request or checksum raises instead of silently using data for another channel. Electron flux can be contaminated during energetic proton events; this feed does not supply a per-record contamination flag.

Parameters:
Return type:

DataFrame

class orbitalpv.data.NtrsConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NASA Technical Reports Server: public metadata and available documents.

No account is needed. A search hit can be metadata-only. Preserve each record’s copyright/distribution fields; public access is not a blanket license to redistribute every paper. Design goals in papers are not flight performance measurements.

Parameters:
search(query, *, offset=0, page_size=25, cache_path=None, refresh=False)[source]

Search one page; offset is the zero-based record offset.

Parameters:
Return type:

ResearchResponse

citation(citation_id, *, cache_path=None, refresh=False)[source]

Get metadata, original download links and access/copyright details.

Parameters:
Return type:

ResearchResponse

download_document(citation_id, filename, destination, *, max_bytes=100000000)[source]

Download an explicitly selected, publicly available original file.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.data.OpenStreetMapEnergyConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Retrieve small-area raw solar/wind features with original OSM structure.

generator:source and plant:source select the paper’s input features without requiring a second power tag. For older tagging, the query also includes power_source on power=generator or power=plant objects. This additional legacy selection is explicit and is not an exact replay of the paper’s 2020 search. solar can include solar thermal: inspect the source’s method/type tags before treating features as photovoltaic arrays.

The result is Overpass JSON, not GeoJSON. Nodes, way-node references, all tags, relation member roles and available geometry are preserved. The query requests full geometry rather than clipping outlines at the bounding box. A way/relation can therefore extend beyond the requested region. Nested relation references remain references and may need additional resolution. No polygon merging, geometry repair, capacity parsing or clustering occurs.

The current snapshot and source timestamp are retained. The optional cache stores original response bytes and a .meta.json sidecar containing the query, retrieval time, license and SHA-256. Public Overpass availability and rate limits apply; global extraction belongs in a regional/planet workflow.

Parameters:
fetch_energy_features(*, bbox, sources=('solar', 'wind'), cache_path=None, refresh=False)[source]

Return the raw source-tagged nodes, ways and relations for a region.

Parameters:
  • bbox (sequence of float) – (west, south, east, north) in WGS84 longitude/latitude degrees. At most one square degree is allowed. Antimeridian-crossing regions must be split into separate boxes. This is a feature-selection box, not an exact polygon-intersection test or an output-geometry clip.

  • sources (sequence of str) – Any nonempty subset of ("solar", "wind"). Input order and duplicate values do not change the query or cache identity.

  • cache_path (str or pathlib.Path, optional) – Original Overpass JSON cache. An existing cache must match both the complete query and its recorded checksum; mismatches raise errors.

  • refresh (bool) – Fetch a new snapshot and replace the cache only after a valid, complete response has been received. Defaults to offline cache reuse.

Returns:

Original decoded Overpass object, including elements and source metadata such as osm3s.timestamp_osm_base when provided. An empty elements list is a valid result; provider errors are never converted into an empty dataset.

Return type:

dict

class orbitalpv.data.OpsSatADConnector(*, timeout_s=120.0)[source]

Download the original telemetry CSV from the fixed OPSSAT-AD v2 release.

Data are CC BY 4.0, DOI 10.5281/zenodo.15108715. The 19 MB CSV contains measured magnetometer and photodiode channels, rather than the separate handcrafted-feature table. No credentials are required.

The source does not include engineering-unit declarations. Values are preserved in their published scale, without interpreting photodiodes as solar-panel current, irradiance, or generated electrical power.

Parameters:

timeout_s (float)

download(destination)[source]

Download, verify, and preserve the source CSV and a provenance sidecar.

Parameters:

destination (str | Path)

Return type:

DownloadReceipt

download_frame(destination, *, channels=None, split=None, refresh=False)[source]

Load selected channels/split, reusing only checksum-verified cached data.

channels is a sequence of source IDs, such as ["CADC0892"]. split is "train", "test", or None for both. Filtering keeps the source segment identifiers and the published benchmark split. A corrupt or different local file raises instead of silently replacing it.

Parameters:
Return type:

DataFrame

class orbitalpv.data.PVSite(name, bbox_wgs84, scenes, item, images, osm)[source]

Source imagery and mapped solar features for one inspection area.

images contains native-grid GroundImage objects keyed by STAC asset name. item is the selected scene from the bounded scenes search, and osm is the original Overpass response. Each image keeps its own resolution, mask and calibration; the map and image dates can differ.

The name is a display label, not a verified inventory record. Solar-tagged OSM features still need method-tag inspection before identifying them as photovoltaic. Neither this object nor its loader infers plant boundaries, panel area, capacity, generation or completeness of OSM mapping.

Parameters:
summary()[source]

Return JSON-serializable dates, search limits and native-grid facts.

Pixel sizes use the units of the asset CRS. OSM counts describe raw objects, not unique plants; SCL counts describe source quality classes, not panel labels. Masked pixels are excluded from SCL counts.

Return type:

dict[str, Any]

class orbitalpv.data.PdsConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

NASA PDS Search API: mission product metadata, labels and data links.

Archive coverage is incomplete. Retain labels to interpret product units and calibration; a search hit is not necessarily a power measurement.

Parameters:
search(query, *, limit=25, sort=None, search_after=None, cache_path=None, refresh=False)[source]

Search using PDS q expressions; cursor pagination requires sort.

Example: '(product_class eq "Product_Bundle")'. Use provider field names and operators, not SQL. The documented keywords parameter is not exposed: it was silently ignored by the live service in the access check.

Parameters:
  • query (str)

  • limit (int)

  • sort (str | None)

  • search_after (str | None)

  • cache_path (str | Path | None)

  • refresh (bool)

Return type:

ResearchResponse

product(identifier, *, cache_path=None, refresh=False)[source]

Resolve a PDS LID or versioned LIDVID to its product metadata.

Parameters:
Return type:

ResearchResponse

class orbitalpv.data.PsaConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

ESA Planetary Science Archive TAP/EPN-TAP read-only ADQL queries.

JSON responses retain column names, units, types and data access links. max_records bounds a response; reaching it may indicate truncation. The service does not provide universal spacecraft EPS telemetry.

Parameters:
query(adql, *, max_records=100, cache_path=None, refresh=False)[source]

Run a SELECT ADQL query; results are bounded, not a complete archive.

Parameters:
Return type:

ResearchResponse

class orbitalpv.data.ResearchResponse(data, receipt, request_url, documentation)[source]

Provider metadata and the receipt for its original response bytes.

request_url includes non-secret query parameters; authentication headers are never serialized. JSON connectors retain provider units, licenses, pagination, versions and uncertainty fields. The arXiv connector documents its Atom-to-metadata normalization and can cache original XML bytes. Neither representation is a validated engineering or PV specification.

Parameters:
class orbitalpv.data.Sentinel2GroundConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Search Sentinel-2 Collection 1 and retrieve ground-image assets.

Search needs only the base installation. Windowed reading needs the optional ground extra (Rasterio). STAC item metadata stays intact, including each asset’s native resolution, calibration and nodata values. The provider’s scene-wide cloud percentage is not an AOI cloud mask.

Parameters:
search(*, bbox, time_min, time_max, max_cloud_cover=20.0, max_items=20, cache_path=None, refresh=False)[source]

Return a bounded STAC FeatureCollection, clearest scenes first.

bbox is west/south/east/north in WGS84 degrees. Time bounds are inclusive UTC instants, as in STAC; a date alone means midnight. max_items caps unique items, not pages. context.limit_reached flags a filled cap: this result must not be assumed exhaustive.

POST/GET pagination is followed with its declared body/merge semantics. Cached snapshots preserve full item metadata and a SHA-256 sidecar binding the file to this query. A changed query or damaged snapshot raises an error; refresh=True explicitly replaces the snapshot.

Parameters:
Return type:

dict[str, Any]

static read_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]

Read a native-resolution COG window; see read_ground_image().

Parameters:
Return type:

GroundImage

download_asset(item, asset, destination, *, max_bytes=1000000000, overwrite=False)[source]

Stream a complete asset to disk with a checksum/provenance sidecar.

Full Sentinel-2 bands can be hundreds of MB. Prefer read_image for farm-sized areas. The size ceiling is enforced while streaming, and a failed request never replaces an existing destination.

Parameters:
Return type:

DownloadReceipt

class orbitalpv.data.SettlementRaster(data, crs, transform, bounds, bbox_wgs84, epoch, edition, provenance)[source]

A native 1 km categorical GHSL crop and its source provenance.

data is a two-dimensional masked integer array. These classes describe settlement context at epoch; they do not describe current PV land use or validate an individual rooftop, ground-mounted plant or water boundary. The original grid is retained, unlike the paper’s Eckert IV reprojection.

Parameters:
sample_points(lon_lat)[source]

Sample WGS84 points without interpolation; unknown flags are None.

Supplying farm centroids implements a clearly defined centroid lookup. It does not calculate the fraction of an entire farm covered by water or urban cells. Outside-crop, masked and unknown-code results remain explicit rather than being counted as rural/non-water observations.

Parameters:

lon_lat (Sequence[Sequence[float]])

Return type:

list[dict[str, Any]]

save(destination, *, overwrite=False)[source]

Write raw classes and internal nodata mask with a SHA-256 sidecar.

Parameters:
Return type:

None

class orbitalpv.data.ZenodoConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]

Discover published research datasets and download open files anonymously.

Restricted files remain restricted. Each record supplies its own license; no deposit, publication or authenticated write endpoints are used.

Parameters:
search(query, *, page=1, page_size=25, cache_path=None, refresh=False)[source]

Search one page using Zenodo query syntax (anonymous maximum: 25).

Parameters:
Return type:

ResearchResponse

record(record_id, *, cache_path=None, refresh=False)[source]

Read a specific record/version, including DOI, license and file checksums.

Parameters:
Return type:

ResearchResponse

download_file(record_id, filename, destination, *, max_bytes=100000000)[source]

Select a public file by exact name and verify its provider checksum.

Parameters:
Return type:

DownloadReceipt

orbitalpv.data.fetch_birds_eps(satellite, destination, *, campaign_year=None)[source]

Download and normalize real on-orbit BIRDS EPS telemetry.

campaign_year explicitly dates sheet names that omit a year, without overriding fully dated sheets. Numeric clocks retain their elapsed seconds; calendar-anchored timestamps do not establish the true acquisition time. See load_birds_eps_workbook() for metadata and excluded test sheets.

Parameters:
  • satellite (str)

  • destination (str | Path)

  • campaign_year (int | None)

Return type:

DataFrame

orbitalpv.data.fetch_celestrak_omm(catnr, *, cache_path='data/cache/gp.sqlite3')[source]

Fetch a CelesTrak OMM record, reusing a persistent two-hour cache.

Use CelesTrakConnector.fetch_gp_cached when source timestamps, stale warnings and checksums are needed alongside the orbital elements.

Parameters:
Return type:

dict[str, object]

orbitalpv.data.fetch_flying_laptop_power(month, destination, *, time_min=None, time_max=None)[source]

Download a Flying Laptop month and normalize its measured array V/I.

Power is computed from each documented voltage/current pair. UTC packet timestamps and four array identities are preserved. Bounds are inclusive at time_min and exclusive at time_max. For offline reuse, call load_flying_laptop_power() on the downloaded archive.

Parameters:
Return type:

DataFrame

orbitalpv.data.fetch_opssat_segments(destination, *, channels=None, split=None, refresh=False)[source]

Fetch checksum-verified original OPS-SAT telemetry and expert labels.

Values retain their published scale; the source supplies no engineering unit declaration. Segment IDs and the provider’s train/test split remain intact. Photodiode measurements are not panel electrical power.

Parameters:
Return type:

DataFrame

orbitalpv.data.load_birds_eps_workbook(path, *, normalized=True, campaign_year=None)[source]

Load a downloaded BIRDS EPS workbook into the canonical panel schema.

Parameters:
  • path (str or pathlib.Path) – Downloaded upstream XLSX workbook.

  • normalized (bool, default True) – Return panel-level flight telemetry. The known undated TSURU sheets Test1 w batt and Test2 wo batt are excluded from this mode. False returns raw rows from every nonempty sheet, including tests.

  • campaign_year (int, optional) – Explicit year for campaign sheet dates that omit it. For example, the TSURU 2021 flight campaigns require campaign_year=2021. A year already stated in a sheet name is always preserved. No current-year assumption is made; an omitted year raises an actionable error.

Return type:

DataFrame

Notes

Calibrated numeric Time Stamp values are elapsed seconds. The returned timestamp anchors these to midnight on campaign_date for ordering; this is not a known absolute UTC acquisition time. The original clock is retained in elapsed_seconds and the convention in timestamp_basis. campaign_date_basis records whether a year was supplied by the caller. Rows without a valid elapsed clock or voltage/current pair are omitted.

orbitalpv.data.load_flying_laptop_power(path, *, time_min=None, time_max=None)[source]

Read calibrated solar-array V, I and computed power from a local archive.

time_min is inclusive and time_max exclusive; naive bounds are UTC. Timestamps are the source’s Unix epoch milliseconds in UTC, identifying packet generation. The source documents up to 400 ms of additional sensor acquisition delay. Missing/invalid readings remain missing and are omitted per voltage/current pair; signed sensor values are not clipped.

Four panel identifiers are preserved: right, left, center and test. Here test is the spacecraft’s experimental array channel, not a separate ground-test recording. Power is computed as V times I; no independently transmitted power measurement is implied.

The reader streams only matching packet 4900 members, never extracting archive paths to disk. A downloaded provenance sidecar, when present, is verified against the local archive. Source metadata is returned in attrs.

Parameters:
Return type:

DataFrame

orbitalpv.data.load_goes_integral_particle_flux(path, *, particle)[source]

Read an original SWPC integral-flux JSON snapshot without network access.

Raw fields are retained. Negative, nonfinite or missing flux values become NaN in flux_cm2_s_sr and are flagged by is_valid_flux. Integral energy channels overlap and must not be added together. Satellite identity is taken from every measurement, since primary proton/electron sources can differ.

Parameters:
Return type:

DataFrame

orbitalpv.data.load_ground_image(path, *, max_pixels=4000000)[source]

Load a saved native crop after verifying its pixels and provenance.

Read the GeoTIFF and .meta.json written by GroundImage.save_geotiff(). The SHA-256, byte count, source identity, native grid, nodata and calibration must agree. The metadata’s original path is informational, so snapshots can move between computers. Unverified external mask/PAM files are rejected.

max_pixels counts all band samples and is enforced before reading the pixels. Raw values, per-band masks and the complete source STAC item are retained; this function never makes network requests or applies calibration.

Parameters:
Return type:

GroundImage

orbitalpv.data.load_opssat_segments(path, *, channels=None, split=None)[source]

Read original OPSSAT-AD telemetry without resampling or merging segments.

Every source column is retained. timestamp becomes a UTC datetime; value stays on its original published scale. Missing/nonfinite values are retained and marked by is_valid_value; no fill value or physical unit is invented. value_unit explicitly records that units are absent from the source CSV.

Use the source’s numeric anomaly field for the expert annotation. The textual label column contains "anomaly" even for nominal segments in v2, so it must not be treated as a classification result. train is the fixed benchmark split, not a chronological split.

A local subset may be loaded for offline analysis. The returned attrs contain its checksum and whether it matches the complete pinned release.

Parameters:
Return type:

DataFrame

orbitalpv.data.load_pv_site(*, bbox, time_min, time_max, cache_dir, name='PV site', cache_prefix='site', max_cloud_cover=20.0, max_items=10, scene_id=None, assets=('visual', 'red', 'scl'), offline=False, refresh=False, timeout_s=60.0, max_pixels=4000000)[source]

Load or retrieve imagery and OSM inputs for a small PV inspection area.

Search Sentinel-2 Collection 1, select the first (lowest scene-cloud-cover) returned item by default, load native crops, and retrieve raw solar-tagged OSM features. A supplied scene_id must occur in the bounded search. Search intersection does not guarantee full raster coverage; the underlying crop reader raises for tile-edge areas rather than mosaicking implicitly.

bbox is WGS84 (west, south, east, north) and must satisfy the OSM connector’s one-square-degree limit. Time bounds are inclusive UTC instants. Scene-wide cloud cover is not a local cloud mask. Inspect quality classes and site.scenes['context']['limit_reached'] when selecting inputs.

The cache contains {prefix}-scenes.json, {prefix}-osm.json and {prefix}-{asset}.tif, each with its provenance sidecar. Existing caches must match the request, SHA-256, selected scene, asset metadata and grid. Only missing files are retrieved; incomplete or inconsistent caches raise. refresh=True explicitly retrieves replacement snapshots and crops. A refresh is not a transaction across all files: if it fails, retry with refresh enabled or use a new cache prefix. Mixed snapshots fail validation.

offline=True requires every source file and sidecar before any loading begins, blocks HTTP fallback, and cannot be combined with refresh=True. max_pixels limits band samples per asset, not the sum across assets. Install orbital-pv[ground] for GeoTIFF support; plotting is separate.

Parameters:
Return type:

PVSite

orbitalpv.data.load_settlement_raster(path, *, max_pixels=1000000)[source]

Restore and verify a saved GHSL crop entirely offline.

Parameters:
Return type:

SettlementRaster

orbitalpv.data.normalize_solar_activity(payload, product)[source]

Normalize native SWPC snapshots without network access.

Negative/nonfinite flux and Kp outside 0–9 are flagged and masked in canonical columns, while raw source fields remain available for auditing. Empty lists represent no records, never fabricated quiet conditions.

Parameters:
Return type:

DataFrame

orbitalpv.data.read_ground_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]

Read a WGS84 area from one HTTPS GeoTIFF asset at native resolution.

bbox is (west, south, east, north) in longitude/latitude degrees. The crop covers the transformed bounding rectangle, rounded outward to source pixels; it is not an exact polygon clip. The selected tile must cover the entire crop. Select another tile or mosaic explicitly when an area crosses a tile edge.

max_pixels limits the total band samples (bands * rows * columns) before pixel data are read. COG range reads retrieve the intersecting compressed blocks, which can be larger than the requested pixel window. Different assets retain their native grids (e.g. RGB 10 m, SCL 20 m). No reprojection, resampling, reflectance scaling or cloud mask occurs.

Parameters:
Return type:

GroundImage

PV mapping utilities#

Plot native satellite inputs and original mapped solar features.

The utilities add presentation to orbitalpv.load_pv_site(): they do not segment panels, assemble OSM multipolygons, resample images or infer capacity. Matplotlib and Rasterio are imported only when a plot is requested.

orbitalpv.mapping.plot_pv_detection(site, prediction, *, reference_labels=None, reference_label='Separate reference labels', reference_credit=None)[source]

Compare a real RGB image, model scores and image-derived PV footprints.

Inference output must match the site’s red-band native grid and scene. Optional -1/0/1 reference labels add separate orange outlines; they are not used to create or clip the prediction. Unknown references remain unknown. Supply a source-specific reference_label and attribution in reference_credit when displaying mapped reference data. The function returns the figure and three axes for customization.

Parameters:
Return type:

tuple[Figure, np.ndarray]

orbitalpv.mapping.plot_pv_site(site, *, overlay_osm=False, ax=None)[source]

Show native RGB, optionally with original OSM outlines and locations.

Parameters:
  • site (space_pv_connectors.ground_site.PVSite) – Inputs returned by orbitalpv.load_pv_site(), including visual.

  • overlay_osm (bool, default False) – Transform the raw WGS84 map coordinates into the image CRS. Separate ways, relation members and incomplete geometry runs remain separate. Outlines are source map features, not image-derived panel labels.

  • ax (matplotlib.axes.Axes, optional) – Draw into existing axes and place attribution beneath those axes; otherwise create an attributed figure. Use constrained/tight layout when composing multiple supplied axes. Existing figure credits remain unchanged.

Returns:

Axes available for further annotations. Call plt.show() yourself.

Return type:

matplotlib.axes.Axes

Notes

RGB nodata samples are filled with zero only for display. Source arrays, masks and geometry are unchanged. Image and OSM dates are shown separately.

orbitalpv.mapping.plot_pv_site_quality(site)[source]

Show calibrated red reflectance and the native SCL quality categories.

red and scl assets are required. Red calibration uses the source’s explicit scale/offset, preserving nodata and negative reflectance. The display range is 0 to 0.5; colorbar extensions flag values outside that range. SCL remains on its native grid with its original integer categories 0 to 11. No resampling, cloud masking or photovoltaic classification is performed.

Returns the figure and two image axes; plt.show() remains with the caller. Both images retain their own native extents and coordinate labels.

Parameters:

site (space_pv_connectors.ground_site.PVSite)

Return type:

tuple[Figure, np.ndarray]

Image-derived PV footprints#

Supervised, image-only PV footprint inference on explicit spectral inputs.

This is a trainable random-forest baseline, not a pretrained global detector or an implementation of Dunnett et al.’s OSM inventory method. Labels must be provided by the caller. In particular, absence from OSM is not a negative label unless that assumption is explicitly chosen and recorded by the user.

Reflectance bands are aligned to the red band’s grid. This derived feature stack is separate from the untouched native GroundImage objects. Model scores are forest class scores, not calibrated detection probabilities.

class orbitalpv.pv_detection.PVFeatures(data, valid_mask, feature_names, crs, transform, bounds, bbox_wgs84, scene_id, pixel_area_m2, provenance)[source]

Derived spectral predictors and validity on one projected image grid.

data has shape (rows, columns, features). valid_mask=True means all predictors and the requested SCL quality filters are usable. Grid areas are projected areas, not an individual-module measurement.

Parameters:
orbitalpv.pv_detection.build_pv_features(images, *, excluded_scl=(0, 1, 2, 3, 6, 8, 9, 10, 11), max_pixels=4000000)[source]

Calibrate six bands and align them to the native red grid.

Requires blue, green, red, nir, swir16, swir22 and scl from the same scene and requested area. Reflectance uses each source’s explicit scale/offset, including negative valid values. Any different spectral grid is resampled bilinearly; SCL always uses nearest neighbour. No source array or metadata is modified. Upsampled SWIR still contains only its original 20 m spatial information.

The default excludes nodata, defective pixels, topographic/cloud shadow, water, cloud/cirrus and snow. This also excludes floating-PV water pixels; callers studying such systems must explicitly choose quality classes. The NDVI/NDBI/MNDWI denominator must have absolute value above 1e-6.

Parameters:
Return type:

PVFeatures

orbitalpv.pv_detection.rasterize_pv_labels(features, positive_geometries, *, negative_geometries=None, geometry_crs='EPSG:4326', background_is_negative=False, boundary_buffer_m=0.0)[source]

Rasterize supplied labels as 1=PV, 0=non-PV, -1=unknown.

Inputs are polygon/MultiPolygon GeoJSON geometries or Features. Pixel centres determine membership. Invalid polygons are rejected, not silently repaired. Invalid feature pixels are always unknown. The outside buffer around positive geometries remains unknown; positive interiors are not eroded. Explicit overlapping positive/negative polygons are rejected.

Outside supplied polygons remains unknown by default. Opting into background_is_negative=True treats every other valid pixel as non-PV: this is a weak assumption for incomplete OSM inventories, not ground truth. Record that choice in PVTrainingSample.label_source and any independent evaluation’s label_source.

Parameters:
Return type:

ndarray

class orbitalpv.pv_detection.PVTrainingSample(features, labels, site_id, label_source)[source]

One labelled scene, with a stable site ID and explicit label source.

Parameters:
  • features (PVFeatures)

  • labels (ndarray)

  • site_id (str)

  • label_source (str)

class orbitalpv.pv_detection.PVFootprintPrediction(probabilities, mask, geojson, metadata)[source]

Image-derived scores, filtered mask and WGS84 footprint polygons.

probabilities are uncalibrated forest scores before area filtering. mask retains only thresholded connected components meeting the area limit. Both arrays mask invalid pixels rather than coding them non-PV. GeoJSON contains grid-derived footprint area, not module surface area.

Parameters:
property area_m2: float

Sum of retained projected-grid footprint areas.

class orbitalpv.pv_detection.PVFootprintModel(feature_names, trees, metadata)[source]

An explicitly trained spectral random forest with safe JSON persistence.

Fitting uses scikit-learn. Prediction reads only learned numeric decision trees and the supplied spectral stack; it never queries or consults OSM. JSON persistence stores numeric arrays instead of executable pickle data. Training provenance is retained so spatially overlapping evaluation can be rejected. Held-out-site metrics assess a supplied reference, not automatic worldwide validity of the model.

Parameters:
classmethod fit(samples, *, random_state=0, max_samples_per_class=5000, n_estimators=100, min_samples_leaf=3, max_depth=20)[source]

Fit a deterministic forest from caller-labelled scenes.

At most max_samples_per_class valid pixels of each class are sampled without replacement from each scene. Random seed, counts, site IDs, bounding boxes, scenes and label sources are recorded. Class weighting balances the retained training labels. This function performs no random-pixel train/test split: such a split cannot test transfer to an unseen farm.

Parameters:
  • samples (Sequence[PVTrainingSample])

  • random_state (int)

  • max_samples_per_class (int)

  • n_estimators (int)

  • min_samples_leaf (int)

  • max_depth (int)

Return type:

PVFootprintModel

property model_id: str

SHA-256 of the model’s canonical numeric JSON representation.

save(path, *, overwrite=False)[source]

Save non-executable JSON, refusing to overwrite by default.

Parameters:
Return type:

Path

classmethod load(path)[source]

Read and validate numeric JSON; never execute serialized Python.

Parameters:

path (str | Path)

Return type:

PVFootprintModel

predict(features, *, threshold=0.5, min_area_m2=1000.0)[source]

Infer PV scores and four-connected footprint polygons from imagery.

No OSM input is accepted. Area filtering removes entire components, retaining holes and the red grid’s pixel edges. GeoJSON is WGS84; areas are measured on the projected input grid. This is approximate array footprint area, not panel surface area or installed capacity.

Parameters:
  • features (PVFeatures)

  • threshold (float)

  • min_area_m2 (float)

Return type:

PVFootprintPrediction

evaluate(features, labels, *, site_id, label_source, threshold=0.5, min_area_m2=1000.0)[source]

Evaluate an unseen site against caller-labelled valid pixels.

Rejects a training site ID or geographic overlap, including a later image of the same farm under a different ID. Returns raw-threshold and area-filtered metrics separately. OSM labels yield agreement with that map snapshot; they do not establish ground-truth accuracy.

Parameters:
Return type:

dict[str, Any]

orbitalpv.pv_detection.evaluate_pv_mask(predicted, labels)[source]

Measure binary agreement on labelled, unmasked pixels only.

Labels are -1 unknown, 0 non-PV and 1 PV. Unknown labels and masked predictions do not become true negatives. Undefined precision/recall/F1/ IoU are None. Counts and coverage make missing-reference cases clear. This low-level scorer does not enforce train/test spatial separation; use PVFootprintModel.evaluate for a held-out-site guard.

Parameters:
Return type:

dict[str, Any]

Farm inventories and capacity calibration#

PV farm geometry and independently calibrated area-to-capacity methods.

Dunnett et al. (2020), DOI 10.1038/s41597-020-0469-8, and the authors’ Figshare v2 scripts (DOI 10.6084/m9.figshare.11310269.v2) motivate the historical profile. The semantic profile distinguishes generator outlines from plant land boundaries. Neither profile detects PV in image pixels.

The historical profile implements the published point/polygon neighbourhoods and area proxies, with explicit geometry validation and overlap deduplication. It does not claim to recreate the authors’ historical source snapshots. Optional geospatial libraries are loaded only when these functions are used.

orbitalpv.pv_inventory.osm_pv_features(overpass, *, require_photovoltaic=True, on_invalid='raise')[source]

Convert original Overpass solar objects to validated WGS84 GeoJSON.

Generator and plant semantics, original tags, OSM identifiers and snapshot time are preserved. Explicit photovoltaic method/type tags are required by default; unclassified solar objects can be retained with require_photovoltaic=False but are marked unconfirmed. Explicit solar thermal objects are always excluded. Nodes are points, ways must be closed, and multipolygon relations are assembled with member roles and holes. Incomplete/self-intersecting geometry raises; on_invalid='skip' records each exclusion in metadata.excluded. No geometry is silently repaired.

Parameters:
Return type:

dict[str, Any]

orbitalpv.pv_inventory.cluster_pv_farms(features, *, eps_m=400.0, min_samples=2, keep_singletons=True, profile='semantic', polygon_eps_m=None)[source]

Group mapped PV features and compute nonoverlapping area measures.

semantic clusters feature centroids at eps_m in a local equal-area projection, then merges intersecting geometries (including parent plants and their generators). panel_area_m2 includes only generator polygons; whole-plant land area is separately recorded. Missing panel area is null. This local approximation requires an extent no wider than five degrees in either coordinate; tile broader inventories with overlapping margins.

dunnett2020 uses Eckert IV, outermost polygons, a 10 m polygon buffer to exclude contained/nearby points, DBSCAN at 400 m for remaining points and 800 m for polygon centroids by default. For point-only groups it uses the median input polygon area as the paper’s explicit area proxy. If no polygon is available the proxy remains null. Intersecting output groups are additionally merged to prevent duplicate area, a documented safeguard beyond the historical script. A singleton polygon retains its original holes and concavities; grouped polygons use their convex hull for landscape area. Geometry IDs are never counted as modules.

Outputs are WGS84 GeoJSON. capacity_area_m2 and capacity_area_basis identify the profile’s predictor separately from actual mapped panel_area_m2 and osm_polygon_area_m2. Singletons are retained with is_cluster=False unless explicitly excluded. This is a spatial grouping, not a registry of independently operated projects.

Parameters:
Return type:

dict[str, Any]

class orbitalpv.pv_inventory.PVCapacityPrediction(mean_mw, lower_mw, upper_mw, eligible, extrapolated, reasons, confidence, capacity_basis, area_basis)[source]

Conditional MW estimates and approximate Gaussian prediction intervals.

Ineligible or disallowed extrapolated estimates are NaN. Intervals include residual variance and fitted-coefficient uncertainty using a local linearization; they do not include mapping error, uncertain area/labels, Box-Cox parameter uncertainty, or geographic/technology domain shift. Their nominal coverage is not a guarantee on a new country or sensor.

Parameters:
class orbitalpv.pv_inventory.PVCapacityModel(boxcox_lambda, area_scale, intercept, slope, coefficient_covariance, residual_std_mw, training_area_range_m2, training_capacity_range_mw, n_training, n_excluded, min_area_m2, capacity_basis, area_basis, source, fit_rmse_mw, fit_mae_mw)[source]

A newly calibrated Gaussian-log-link area model, with source provenance.

The model form follows the published R script: transform positive area in km² with Box-Cox, divide by sample standard deviation, then fit E[capacity_MW] = exp(intercept + slope * transformed_area / scale). Preprocessing is fitted only on the supplied calibration observations. Lambda maximizes the Box-Cox normal likelihood over [-3, 3], with caret’s 0.2 tolerance around zero and one. Continuous optimization and nonlinear least squares can differ numerically from R’s grid/IRLS implementation. This is a recalibration, not the original authors’ trained model.

Parameters:
predict(area_m2, *, urban, area_basis, allow_extrapolation=False, confidence=0.95)[source]

Predict for matching area semantics, flagging unsupported observations.

Only explicitly nonurban observations above min_area_m2 qualify. Extrapolation outside the calibration area range is withheld by default and remains flagged when explicitly allowed. The caller must use the same area definition and AC/DC/reported capacity basis as the calibration data. Urban status can come from a declared GHSL edition.

Parameters:
Return type:

PVCapacityPrediction

orbitalpv.pv_inventory.fit_pv_capacity_model(area_m2, capacity_mw, *, urban, capacity_basis, area_basis, source, min_area_m2=10000.0, max_capacity_mw=1000.0)[source]

Calibrate the paper’s area-only model form from independent capacities.

Inputs are matched observations: area in m², capacity in MW, and explicit urban flags. The default domain mirrors the source script (>1 ha, nonurban, capacity <1000 MW). Set the capacity ceiling explicitly for a modern calibration; 1000 MW is a historical outlier cutoff, not a physical limit. Exclusions are counted. At least six retained observations and three distinct areas are required. A sample is not an independent test: evaluate on held-out sites/countries separately.

capacity_basis must be ‘AC’, ‘DC’, or ‘reported’; area_basis must declare generator panel area, an OSM polygon proxy, or a median polygon imputation. Never mix total site land with module/array surface area in a single calibration. The nonempty source describes external capacity evidence; this function cannot verify that provenance automatically.

Parameters:
Return type:

PVCapacityModel

orbitalpv.pv_inventory.evaluate_pv_capacity(observed_mw, prediction)[source]

Report held-out error and interval coverage without hiding exclusions.

Caller-supplied observations must be independent of fitting and use the model’s declared capacity basis. Counts include withheld/extrapolated predictions, while metrics use only eligible finite estimates. R² is null for a constant reference; no eligible predictions produces null metrics.

Parameters:
  • observed_mw (ArrayLike)

  • prediction (PVCapacityPrediction)

Return type:

dict[str, Any]

Ground-analysis workflows#

Short, provenance-aware workflows for terrestrial PV image analysis.

orbitalpv.ground_analysis.prepare_pv_training_sample(site, *, site_id=None, background_is_negative=False, negative_geometries=None, boundary_buffer_m=20.0)[source]

Create explicit weak labels from mapped photovoltaic generator polygons.

Plant perimeters and point-only locations are not panel labels. This adapter rejects sites without usable generator polygons; for reviewed labels or other source products use rasterize_pv_labels directly. Missing map features do not establish absence of PV. Opting into background_is_negative records that assumption in the label source. Explicit negative geometries use WGS84 longitude/latitude coordinates.

Parameters:
Return type:

PVTrainingSample

orbitalpv.ground_analysis.classify_pv_farms(farms, settlement)[source]

Attach historical GHSL context at each grouped farm’s centroid.

This explicit farm-centroid lookup differs from the original paper’s majority of input-feature centroid flags. It is not an area fraction or a statement about present-day land use. Unknown cells retain None flags. The input GeoJSON is not modified.

Parameters:
Return type:

dict[str, Any]

orbitalpv.ground_analysis.estimate_pv_farm_capacity(farms, model)[source]

Attach calibrated capacities while retaining reasons for withheld values.

A farm needs a positive capacity-area predictor with the same definition as the calibration and an explicit nonurban flag. Different area bases, absent areas, unknown/urban context and out-of-range predictors are kept in the inventory with null estimates. No extrapolation is enabled here.

Parameters:
Return type:

dict[str, Any]

orbitalpv.ground_analysis.save_pv_prediction(prediction, destination, *, overwrite=False)[source]

Export WGS84 GeoJSON, native-grid scores/mask, and prediction metadata.

pv_prediction.tif contains float32 class scores in band 1 and a 0/1 area-filtered mask in band 2; invalid pixels have nodata -9999 in both. This is a derived model output, not a raw Sentinel-2 asset. Model weights are saved separately with PVFootprintModel.save. Existing outputs require explicit overwrite, and a partial failure can leave earlier completed files in the destination directory.

Parameters:
  • prediction (PVFootprintPrediction)

  • destination (str | Path)

  • overwrite (bool)

Return type:

dict[str, Path]