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.
- paper(paper_id, *, cache_path=None, refresh=False)[source]
Fetch pinned metadata, or validate and read its existing local cache.
- Parameters:
- Return type:
- class orbitalpv.BayesianLinearCalibration(model, coefficient_covariance, observation_noise_std, prior_std)[source]
Normal likelihood + zero-mean normal coefficient prior, known noise.
- Parameters:
- 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.
- class orbitalpv.BirdsEPSConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]
Connector for the public BIRDS on-orbit EPS dataset.
- download(satellite, destination)[source]
Download one satellite workbook from the upstream BIRDS repository.
- Parameters:
- Return type:
- download_frame(satellite, destination, *, normalized=True, campaign_year=None)[source]
Download and load a BIRDS EPS workbook.
campaign_yearsupplies the year only for campaign sheet names that omit it; seeload_birds_eps_workbook()for the time convention.
- 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.- search(query, *, start=0, page_size=25, cache_path=None, refresh=False)[source]
Search public datasets; start is a zero-based record offset.
- dataset(persistent_id, *, version=':latest-published', cache_path=None, refresh=False)[source]
Fetch published dataset metadata; pin
version='1.0'for reproducibility.
- download_file(persistent_id, filename, destination, *, version=':latest-published', max_bytes=100000000)[source]
Download the original public file and verify its dataset checksum.
- 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]
- 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.
- 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.
- object(discos_id, *, cache_path=None, refresh=False)[source]
Retrieve one object by its DISCOS internal ID.
- 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.
- 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.
- 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.
- download_month(month, destination)[source]
Download one YYYY-MM archive after checking its catalog checksum.
- Parameters:
- Return type:
- 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.- 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).offlinepermits an existing validated crop or local source, and prevents HTTP calls.refreshreplaces a crop from the same source; archived versioned source files remain cached. A localsource_pathis hashed and its edition/epoch are caller declarations recorded in provenance; filenames alone cannot verify those declarations.
- 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.
datahas shape(bands, rows, columns); True mask entries mean missing data.transformholds affine(a, b, c, d, e, f)coefficients andboundsis(left, bottom, right, top)incrs. Pixel-aligned bounds can extend slightly beyond the requestedbbox_wgs84.visualis a rendered RGB product, not calibrated reflectance.sclis a categorical scene-classification product, not a power or irradiance measurement. No cloud masking is applied implicitly.- Parameters:
- reflectance()[source]
Return
raw * scale + offsetusing explicit STAC band metadata.Only assets declaring the
reflectancerole are accepted. Missing data remain masked before calibration; negative reflectance values are retained. The rawdatais 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:
- save_geotiff(destination, *, overwrite=False)[source]
Save raw pixels, georeferencing, calibration and provenance.
The
.meta.jsonsidecar 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:
- 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]
- 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.
- 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.
- 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.
- 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.
- class orbitalpv.LinearVIForecaster(model, horizons, feature_names)[source]
Multi-output ridge baseline trained only on preceding V/I labels.
- 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
jsondresponse carries parameter order and units. Cache files contain the original JSON bytes plus a.meta.jsonsidecar 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.- 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_measurementrequires both irradiances to be finite and positive.provisional_flagis preserved when present and is not interpreted as a missing-value flag.
- 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_goodconservatively 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.
- class orbitalpv.LossStage(name, power_column, category, evidence)[source]
One ordered, cumulative power prediction with a declared evidence basis.
power_columncontains the prediction after this stage, not an independent loss estimate. Its contribution is the preceding prediction minus this prediction.evidenceshould 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.categorymust be a key inLOSS_CATEGORIES, exceptunexplainedwhich is reserved for the final model-minus-actual residual. Names must be unique snake_case identifiers within a breakdown.
- class orbitalpv.MeasuredEnergyBudget(intervals, summary)[source]
Energy integrated over common valid observation intervals only.
- 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/
- positions(norad_id, *, observer_lat, observer_lon, observer_alt_m=0, seconds=60)[source]
Return the provider’s timestamped position JSON, including provenance.
sataltitudein the provider payload is km; observer altitude is m. Element epoch is not supplied by this endpoint and remains unknown.
- class orbitalpv.NoaaSwpcConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]
NOAA Space Weather Prediction Center JSON feed connector.
- 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:
- 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), andalerts(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.
- goes_integral_particle_flux(particle, *, role='primary', period='7-day', cache_path=None, refresh=False)[source]
Fetch measured GOES integral proton or electron flux.
periodselects a rolling6-hour,1-day,3-dayor7-dayobservation feed. This is not a historical-date API.roleis 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.
- 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.
- search(query, *, offset=0, page_size=25, cache_path=None, refresh=False)[source]
Search one page;
offsetis the zero-based record offset.
- citation(citation_id, *, cache_path=None, refresh=False)[source]
Get metadata, original download links and access/copyright details.
- 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:sourceandplant:sourceselect the paper’s input features without requiring a secondpowertag. For older tagging, the query also includespower_sourceonpower=generatororpower=plantobjects. This additional legacy selection is explicit and is not an exact replay of the paper’s 2020 search.solarcan 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.jsonsidecar containing the query, retrieval time, license and SHA-256. Public Overpass availability and rate limits apply; global extraction belongs in a regional/planet workflow.- 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
elementsand source metadata such asosm3s.timestamp_osm_basewhen provided. An empty elements list is a valid result; provider errors are never converted into an empty dataset.- Return type:
- 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:
- Return type:
- download_frame(destination, *, channels=None, split=None, refresh=False)[source]
Load selected channels/split, reusing only checksum-verified cached data.
channelsis a sequence of source IDs, such as["CADC0892"].splitis"train","test", orNonefor both. Filtering keeps the source segment identifiers and the published benchmark split. A corrupt or different local file raises instead of silently replacing it.
- 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:
boxcox_lambda (float)
area_scale (float)
intercept (float)
slope (float)
coefficient_covariance (tuple[tuple[float, float], tuple[float, float]])
residual_std_mw (float)
n_training (int)
n_excluded (int)
min_area_m2 (float)
capacity_basis (str)
area_basis (str)
source (str)
fit_rmse_mw (float)
fit_mae_mw (float)
- 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_m2qualify. 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.
- 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.
- 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.
datahas shape(rows, columns, features).valid_mask=Truemeans 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_classvalid 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.
- 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.
- classmethod load(path)[source]
Read and validate numeric JSON; never execute serialized Python.
- 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.
- 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.
- class orbitalpv.PVFootprintPrediction(probabilities, mask, geojson, metadata)[source]
Image-derived scores, filtered mask and WGS84 footprint polygons.
probabilitiesare uncalibrated forest scores before area filtering.maskretains 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:
probabilities (MaskedArray)
mask (MaskedArray)
- 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.
imagescontains native-gridGroundImageobjects keyed by STAC asset name.itemis the selected scene from the boundedscenessearch, andosmis 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.
- class orbitalpv.PVTrainingSample(features, labels, site_id, label_source)[source]
One labelled scene, with a stable site ID and explicit label source.
- 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.
- search(query, *, limit=25, sort=None, search_after=None, cache_path=None, refresh=False)[source]
Search using PDS
qexpressions; 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.
- class orbitalpv.PowerLossBreakdown(samples, components_w, categories_w, stages, group_columns)[source]
Power ledger returned by
power_loss_breakdown().samplescontains sorted timestamps, group identifiers, power predictions, signed total/attributed/unexplained losses and a commonvalidmask.components_wcontains a column per stage plusunexplained.categories_wcombines 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 tosummarize_power_losses().
- class orbitalpv.PowerLossSummary(totals, components, categories)[source]
Observed-interval energy totals, components and categories, all in Wh.
totalsreports the signed energy gap and common observation coverage per input group.componentsandcategoriesreport signednet_loss_wh, nonnegativeloss_wh/gain_whand 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.
- 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_recordsbounds a response; reaching it may indicate truncation. The service does not provide universal spacecraft EPS telemetry.
- 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.
- class orbitalpv.ResearchResponse(data, receipt, request_url, documentation)[source]
Provider metadata and the receipt for its original response bytes.
request_urlincludes 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:
data (Any)
receipt (DownloadReceipt)
request_url (str)
documentation (str)
- 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.
- 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
groundextra (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.- 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.
bboxis west/south/east/north in WGS84 degrees. Time bounds are inclusive UTC instants, as in STAC; a date alone means midnight.max_itemscaps unique items, not pages.context.limit_reachedflags 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=Trueexplicitly replaces the snapshot.
- static read_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]
Read a native-resolution COG window; see
read_ground_image().
- 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_imagefor farm-sized areas. The size ceiling is enforced while streaming, and a failed request never replaces an existing destination.
- class orbitalpv.SettlementRaster(data, crs, transform, bounds, bbox_wgs84, epoch, edition, provenance)[source]
A native 1 km categorical GHSL crop and its source provenance.
datais a two-dimensional masked integer array. These classes describe settlement context atepoch; 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.
- 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]
- 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:
technology (SpaceCellTechnology)
irradiance_w_m2 (float)
cell_temperature_c (float)
fluence_1mev_e_cm2 (float)
radiation_factor (float)
voltage_v (ndarray)
current_density_ma_cm2 (ndarray)
power_density_w_m2 (ndarray)
voc_v (float)
isc_ma_cm2 (float)
vmp_v (float)
imp_ma_cm2 (float)
pmp_w_m2 (float)
efficiency (float)
- 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:
slug (str)
name (str)
family (str)
junctions (int)
efficiency_am0 (float)
voc_v (float)
vmp_v (float)
jsc_ma_cm2 (float)
jmp_ma_cm2 (float)
temp_coeff_current_per_c (float)
temp_coeff_voltage_per_c (float)
radiation_retention_at_1e15 (float)
reference_temperature_c (float)
reference_irradiance_w_m2 (float)
notes (str)
- 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:
- 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.
- search(query, *, page=1, page_size=25, cache_path=None, refresh=False)[source]
Search one page using Zenodo query syntax (anonymous maximum: 25).
- record(record_id, *, cache_path=None, refresh=False)[source]
Read a specific record/version, including DOI, license and file checksums.
- 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.
- 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,swir22andsclfrom 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.
- 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.
scalesis 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.
- 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_degis 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 betaasin(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: useearth_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
- orbitalpv.circular_orbit_period_s(altitude_m)[source]
Return the two-body period of a circular Earth orbit in seconds.
altitude_mis a finite, positive height above the equatorial Earth radius. This is a design estimate, without perturbations or station keeping.
- 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.
- 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.
- 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.
semanticclusters feature centroids ateps_min a local equal-area projection, then merges intersecting geometries (including parent plants and their generators).panel_area_m2includes 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.dunnett2020uses 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_m2andcapacity_area_basisidentify the profile’s predictor separately from actual mappedpanel_area_m2andosm_polygon_area_m2. Singletons are retained withis_cluster=Falseunless explicitly excluded. This is a spatial grouping, not a registry of independently operated projects.
- 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.
- 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.
- 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.
- 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.
- 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; usePVFootprintModel.evaluatefor a held-out-site guard.
- orbitalpv.fetch_birds_eps(satellite, destination, *, campaign_year=None)[source]
Download and normalize real on-orbit BIRDS EPS telemetry.
campaign_yearexplicitly 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. Seeload_birds_eps_workbook()for metadata and excluded test sheets.
- 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_cachedwhen source timestamps, stale warnings and checksums are needed alongside the orbital elements.
- 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_minand exclusive attime_max. For offline reuse, callload_flying_laptop_power()on the downloaded archive.
- 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.
- 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.
- orbitalpv.fit_linear_calibration(features, target, *, timestamps, purpose, evidence='', ridge=0.0)[source]
Fit a deterministic reference or forecast, declaring its intended role.
timestampsidentify 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.
- 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_basismust be ‘AC’, ‘DC’, or ‘reported’;area_basismust 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 nonemptysourcedescribes external capacity evidence; this function cannot verify that provenance automatically.
- orbitalpv.geocentric_sun_positions_m(times)[source]
Geocentric GCRS Sun positions using Astropy’s supported solar ephemeris path.
- 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.
- 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.
- 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 battandTest2 wo battare excluded from this mode.Falsereturns 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:
Notes
Calibrated numeric
Time Stampvalues are elapsed seconds. The returnedtimestampanchors these to midnight oncampaign_datefor ordering; this is not a known absolute UTC acquisition time. The original clock is retained inelapsed_secondsand the convention intimestamp_basis.campaign_date_basisrecords 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_timezoneis supplied. The full archive is large; supply a time window. No ZIP member is extracted to disk. Setverify_source=Falseonly for independently provided files, which are then labelled unverified rather than claimed as the pinned archive.
- 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_minis inclusive andtime_maxexclusive; 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,centerandtest. Heretestis 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.
- 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_srand are flagged byis_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.
- 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.jsonwritten byGroundImage.save_geotiff(). The SHA-256, byte count, source identity, native grid, nodata and calibration must agree. The metadata’s originalpathis informational, so snapshots can move between computers. Unverified external mask/PAM files are rejected.max_pixelscounts 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:
- 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.
timestampbecomes a UTC datetime;valuestays on its original published scale. Missing/nonfinite values are retained and marked byis_valid_value; no fill value or physical unit is invented.value_unitexplicitly records that units are absent from the source CSV.Use the source’s numeric
anomalyfield for the expert annotation. The textuallabelcolumn contains"anomaly"even for nominal segments in v2, so it must not be treated as a classification result.trainis the fixed benchmark split, not a chronological split.A local subset may be loaded for offline analysis. The returned
attrscontain its checksum and whether it matches the complete pinned release.
- 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_idmust 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.bboxis 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 andsite.scenes['context']['limit_reached']when selecting inputs.The cache contains
{prefix}-scenes.json,{prefix}-osm.jsonand{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=Trueexplicitly 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=Truerequires every source file and sidecar before any loading begins, blocks HTTP fallback, and cannot be combined withrefresh=True.max_pixelslimits band samples per asset, not the sum across assets. Installorbital-pv[ground]for GeoTIFF support; plotting is separate.
- orbitalpv.load_settlement_raster(path, *, max_pixels=1000000)[source]
Restore and verify a saved GHSL crop entirely offline.
- Parameters:
- Return type:
- 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.
- 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.
- 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.
- 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.
- orbitalpv.omm_epoch(omm)[source]
Parse GP EPOCH; timezone-free OMM epochs are UTC per the GP contract.
- 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=Falsebut 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 inmetadata.excluded. No geometry is silently repaired.
- orbitalpv.persistence_vi_forecast(data)[source]
Repeat the last observed operating voltage/current at each horizon.
- Parameters:
data (LaggedVIData)
- Return type:
- 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_labeland attribution inreference_creditwhen displaying mapped reference data. The function returns the figure and three axes for customization.
- 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(), includingvisual.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:
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.
redandsclassets 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:
- 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, ..., Pnand a declared expected baselineP0, the signed contributions areP0-P1, P1-P2, ..., P(n-1)-Pn. The unexplained remainder isPn-actual. Thus all contributions sum toexpected-actualat 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
samplesfor 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:
- 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_labelsdirectly. Missing map features do not establish absence of PV. Opting intobackground_is_negativerecords that assumption in the label source. Explicit negative geometries use WGS84 longitude/latitude coordinates.
- 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_daysfrom any requested time (including future epochs). This cutoff is a display policy, not an orbital accuracy guarantee.
- 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.
- 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.
referencespecifies beginning-of-life (BOL) array DC power at its reference irradiance and cell temperature. That calibration already includes inherent cell and coverglass efficiencies:optical_factorrepresents 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_wmust be nonnegative; reference irradiance must be positive. All fractional inputs are in [0, 1], exceptspectral_factor, which must be positive and may exceed one. The temperature multiplier1 + 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=Nonedisables 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, andmodeled_power_w(after curtailment). The temperature stage callspvwatts_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_spacePVWatts DC equation with a space irradiance reference.
References
pvlib PVWatts DC model: https://pvlib-python.readthedocs.io/en/stable/reference/generated/pvlib.pvsystem.pvwatts_dc.html
NASA Small Spacecraft Technology, Power: https://www.nasa.gov/smallsat-institute/sst-soa/power-subsystems/
- 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:
- 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.
- 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). Setascending=Falsefor 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.
- 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.
- 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=Truetreats every other valid pixel as non-PV: this is a weak assumption for incomplete OSM inventories, not ground truth. Record that choice inPVTrainingSample.label_sourceand any independent evaluation’slabel_source.
- orbitalpv.read_ground_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]
Read a WGS84 area from one HTTPS GeoTIFF asset at native resolution.
bboxis(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_pixelslimits 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.
- orbitalpv.save_pv_prediction(prediction, destination, *, overwrite=False)[source]
Export WGS84 GeoJSON, native-grid scores/mask, and prediction metadata.
pv_prediction.tifcontains 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 withPVFootprintModel.save. Existing outputs require explicit overwrite, and a partial failure can leave earlier completed files in the destination directory.
- 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.
- 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.
- 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.
- orbitalpv.summarize_power_losses(breakdown, *, max_gap_s)[source]
Integrate a power ledger on common, observed intervals only.
max_gap_sis 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:
breakdown (PowerLossBreakdown)
max_gap_s (float)
- Return type:
- 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
ValueErrorwhen altitude is invalid or J2 alone cannot provide the required precession at that altitude.
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]
- 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]
- orbitalpv.orbit.circular_eclipse_duration_s(altitude_m, beta_angle_deg)[source]
Estimate eclipse duration per circular orbit with a cylindrical shadow.
beta_angle_degis 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 betaasin(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: useearth_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
- orbitalpv.orbit.circular_orbit_period_s(altitude_m)[source]
Return the two-body period of a circular Earth orbit in seconds.
altitude_mis a finite, positive height above the equatorial Earth radius. This is a design estimate, without perturbations or station keeping.
- 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.
- orbitalpv.orbit.geocentric_sun_positions_m(times)[source]
Geocentric GCRS Sun positions using Astropy’s supported solar ephemeris path.
- 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.
- 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.
- orbitalpv.orbit.omm_epoch(omm)[source]
Parse GP EPOCH; timezone-free OMM epochs are UTC per the GP contract.
- 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_daysfrom any requested time (including future epochs). This cutoff is a display policy, not an orbital accuracy guarantee.
- 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.
- 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). Setascending=Falsefor 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.
- 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
ValueErrorwhen altitude is invalid or J2 alone cannot provide the required precession at that altitude.
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]
- 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.
- 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.
- 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.
- 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.
referencespecifies beginning-of-life (BOL) array DC power at its reference irradiance and cell temperature. That calibration already includes inherent cell and coverglass efficiencies:optical_factorrepresents 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_wmust be nonnegative; reference irradiance must be positive. All fractional inputs are in [0, 1], exceptspectral_factor, which must be positive and may exceed one. The temperature multiplier1 + 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=Nonedisables 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, andmodeled_power_w(after curtailment). The temperature stage callspvwatts_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_spacePVWatts DC equation with a space irradiance reference.
References
pvlib PVWatts DC model: https://pvlib-python.readthedocs.io/en/stable/reference/generated/pvlib.pvsystem.pvwatts_dc.html
NASA Small Spacecraft Technology, Power: https://www.nasa.gov/smallsat-institute/sst-soa/power-subsystems/
- 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:
- 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.
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:
technology (SpaceCellTechnology)
irradiance_w_m2 (float)
cell_temperature_c (float)
fluence_1mev_e_cm2 (float)
radiation_factor (float)
voltage_v (ndarray)
current_density_ma_cm2 (ndarray)
power_density_w_m2 (ndarray)
voc_v (float)
isc_ma_cm2 (float)
vmp_v (float)
imp_ma_cm2 (float)
pmp_w_m2 (float)
efficiency (float)
- 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:
slug (str)
name (str)
family (str)
junctions (int)
efficiency_am0 (float)
voc_v (float)
vmp_v (float)
jsc_ma_cm2 (float)
jmp_ma_cm2 (float)
temp_coeff_current_per_c (float)
temp_coeff_voltage_per_c (float)
radiation_retention_at_1e15 (float)
reference_temperature_c (float)
reference_irradiance_w_m2 (float)
notes (str)
- 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.
- 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.
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⁻¹.
- class orbitalpv.analytics.LossStage(name, power_column, category, evidence)[source]
One ordered, cumulative power prediction with a declared evidence basis.
power_columncontains the prediction after this stage, not an independent loss estimate. Its contribution is the preceding prediction minus this prediction.evidenceshould 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.categorymust be a key inLOSS_CATEGORIES, exceptunexplainedwhich is reserved for the final model-minus-actual residual. Names must be unique snake_case identifiers within a breakdown.
- 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.
- class orbitalpv.analytics.PowerLossBreakdown(samples, components_w, categories_w, stages, group_columns)[source]
Power ledger returned by
power_loss_breakdown().samplescontains sorted timestamps, group identifiers, power predictions, signed total/attributed/unexplained losses and a commonvalidmask.components_wcontains a column per stage plusunexplained.categories_wcombines 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 tosummarize_power_losses().
- class orbitalpv.analytics.PowerLossSummary(totals, components, categories)[source]
Observed-interval energy totals, components and categories, all in Wh.
totalsreports the signed energy gap and common observation coverage per input group.componentsandcategoriesreport signednet_loss_wh, nonnegativeloss_wh/gain_whand 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.
- 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.
- 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:
- Return type:
- 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:
- Return type:
- 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.
- 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, ..., Pnand a declared expected baselineP0, the signed contributions areP0-P1, P1-P2, ..., P(n-1)-Pn. The unexplained remainder isPn-actual. Thus all contributions sum toexpected-actualat 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
samplesfor 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:
- orbitalpv.analytics.summarize_power_losses(breakdown, *, max_gap_s)[source]
Integrate a power ledger on common, observed intervals only.
max_gap_sis 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:
breakdown (PowerLossBreakdown)
max_gap_s (float)
- Return type:
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.
- paper(paper_id, *, cache_path=None, refresh=False)[source]
Fetch pinned metadata, or validate and read its existing local cache.
- Parameters:
- Return type:
- 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.
- download(satellite, destination)[source]
Download one satellite workbook from the upstream BIRDS repository.
- Parameters:
- Return type:
- download_frame(satellite, destination, *, normalized=True, campaign_year=None)[source]
Download and load a BIRDS EPS workbook.
campaign_yearsupplies the year only for campaign sheet names that omit it; seeload_birds_eps_workbook()for the time convention.
- 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.- search(query, *, start=0, page_size=25, cache_path=None, refresh=False)[source]
Search public datasets; start is a zero-based record offset.
- dataset(persistent_id, *, version=':latest-published', cache_path=None, refresh=False)[source]
Fetch published dataset metadata; pin
version='1.0'for reproducibility.
- download_file(persistent_id, filename, destination, *, version=':latest-published', max_bytes=100000000)[source]
Download the original public file and verify its dataset checksum.
- 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.
- 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.
- object(discos_id, *, cache_path=None, refresh=False)[source]
Retrieve one object by its DISCOS internal ID.
- 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.
- 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.
- 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.
- download_month(month, destination)[source]
Download one YYYY-MM archive after checking its catalog checksum.
- Parameters:
- Return type:
- 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.- 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).offlinepermits an existing validated crop or local source, and prevents HTTP calls.refreshreplaces a crop from the same source; archived versioned source files remain cached. A localsource_pathis hashed and its edition/epoch are caller declarations recorded in provenance; filenames alone cannot verify those declarations.
- 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)
- 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]
- 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.
datahas shape(bands, rows, columns); True mask entries mean missing data.transformholds affine(a, b, c, d, e, f)coefficients andboundsis(left, bottom, right, top)incrs. Pixel-aligned bounds can extend slightly beyond the requestedbbox_wgs84.visualis a rendered RGB product, not calibrated reflectance.sclis a categorical scene-classification product, not a power or irradiance measurement. No cloud masking is applied implicitly.- Parameters:
- reflectance()[source]
Return
raw * scale + offsetusing explicit STAC band metadata.Only assets declaring the
reflectancerole are accepted. Missing data remain masked before calibration; negative reflectance values are retained. The rawdatais 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:
- save_geotiff(destination, *, overwrite=False)[source]
Save raw pixels, georeferencing, calibration and provenance.
The
.meta.jsonsidecar 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:
- 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.
- 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.
- 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
jsondresponse carries parameter order and units. Cache files contain the original JSON bytes plus a.meta.jsonsidecar 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.- 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_measurementrequires both irradiances to be finite and positive.provisional_flagis preserved when present and is not interpreted as a missing-value flag.
- 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_goodconservatively 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.
- 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/
- positions(norad_id, *, observer_lat, observer_lon, observer_alt_m=0, seconds=60)[source]
Return the provider’s timestamped position JSON, including provenance.
sataltitudein the provider payload is km; observer altitude is m. Element epoch is not supplied by this endpoint and remains unknown.
- class orbitalpv.data.NoaaSwpcConnector(*, timeout_s=30.0, user_agent='space-pv-analytics/0.2')[source]
NOAA Space Weather Prediction Center JSON feed connector.
- 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:
- 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), andalerts(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.
- goes_integral_particle_flux(particle, *, role='primary', period='7-day', cache_path=None, refresh=False)[source]
Fetch measured GOES integral proton or electron flux.
periodselects a rolling6-hour,1-day,3-dayor7-dayobservation feed. This is not a historical-date API.roleis 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.
- 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.
- search(query, *, offset=0, page_size=25, cache_path=None, refresh=False)[source]
Search one page;
offsetis the zero-based record offset.
- citation(citation_id, *, cache_path=None, refresh=False)[source]
Get metadata, original download links and access/copyright details.
- 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:sourceandplant:sourceselect the paper’s input features without requiring a secondpowertag. For older tagging, the query also includespower_sourceonpower=generatororpower=plantobjects. This additional legacy selection is explicit and is not an exact replay of the paper’s 2020 search.solarcan 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.jsonsidecar containing the query, retrieval time, license and SHA-256. Public Overpass availability and rate limits apply; global extraction belongs in a regional/planet workflow.- 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
elementsand source metadata such asosm3s.timestamp_osm_basewhen provided. An empty elements list is a valid result; provider errors are never converted into an empty dataset.- Return type:
- 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:
- Return type:
- download_frame(destination, *, channels=None, split=None, refresh=False)[source]
Load selected channels/split, reusing only checksum-verified cached data.
channelsis a sequence of source IDs, such as["CADC0892"].splitis"train","test", orNonefor both. Filtering keeps the source segment identifiers and the published benchmark split. A corrupt or different local file raises instead of silently replacing it.
- class orbitalpv.data.PVSite(name, bbox_wgs84, scenes, item, images, osm)[source]
Source imagery and mapped solar features for one inspection area.
imagescontains native-gridGroundImageobjects keyed by STAC asset name.itemis the selected scene from the boundedscenessearch, andosmis 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.
- 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.
- search(query, *, limit=25, sort=None, search_after=None, cache_path=None, refresh=False)[source]
Search using PDS
qexpressions; 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.
- 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_recordsbounds a response; reaching it may indicate truncation. The service does not provide universal spacecraft EPS telemetry.
- class orbitalpv.data.ResearchResponse(data, receipt, request_url, documentation)[source]
Provider metadata and the receipt for its original response bytes.
request_urlincludes 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:
data (Any)
receipt (DownloadReceipt)
request_url (str)
documentation (str)
- 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
groundextra (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.- 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.
bboxis west/south/east/north in WGS84 degrees. Time bounds are inclusive UTC instants, as in STAC; a date alone means midnight.max_itemscaps unique items, not pages.context.limit_reachedflags 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=Trueexplicitly replaces the snapshot.
- static read_image(item, *, bbox, asset='visual', max_pixels=4000000)[source]
Read a native-resolution COG window; see
read_ground_image().
- 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_imagefor farm-sized areas. The size ceiling is enforced while streaming, and a failed request never replaces an existing destination.
- 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.
datais a two-dimensional masked integer array. These classes describe settlement context atepoch; 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.
- 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.
- search(query, *, page=1, page_size=25, cache_path=None, refresh=False)[source]
Search one page using Zenodo query syntax (anonymous maximum: 25).
- record(record_id, *, cache_path=None, refresh=False)[source]
Read a specific record/version, including DOI, license and file checksums.
- orbitalpv.data.fetch_birds_eps(satellite, destination, *, campaign_year=None)[source]
Download and normalize real on-orbit BIRDS EPS telemetry.
campaign_yearexplicitly 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. Seeload_birds_eps_workbook()for metadata and excluded test sheets.
- 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_cachedwhen source timestamps, stale warnings and checksums are needed alongside the orbital elements.
- 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_minand exclusive attime_max. For offline reuse, callload_flying_laptop_power()on the downloaded archive.
- 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.
- 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 battandTest2 wo battare excluded from this mode.Falsereturns 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:
Notes
Calibrated numeric
Time Stampvalues are elapsed seconds. The returnedtimestampanchors these to midnight oncampaign_datefor ordering; this is not a known absolute UTC acquisition time. The original clock is retained inelapsed_secondsand the convention intimestamp_basis.campaign_date_basisrecords 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_minis inclusive andtime_maxexclusive; 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,centerandtest. Heretestis 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.
- 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_srand are flagged byis_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.
- 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.jsonwritten byGroundImage.save_geotiff(). The SHA-256, byte count, source identity, native grid, nodata and calibration must agree. The metadata’s originalpathis informational, so snapshots can move between computers. Unverified external mask/PAM files are rejected.max_pixelscounts 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:
- 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.
timestampbecomes a UTC datetime;valuestays on its original published scale. Missing/nonfinite values are retained and marked byis_valid_value; no fill value or physical unit is invented.value_unitexplicitly records that units are absent from the source CSV.Use the source’s numeric
anomalyfield for the expert annotation. The textuallabelcolumn contains"anomaly"even for nominal segments in v2, so it must not be treated as a classification result.trainis the fixed benchmark split, not a chronological split.A local subset may be loaded for offline analysis. The returned
attrscontain its checksum and whether it matches the complete pinned release.
- 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_idmust 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.bboxis 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 andsite.scenes['context']['limit_reached']when selecting inputs.The cache contains
{prefix}-scenes.json,{prefix}-osm.jsonand{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=Trueexplicitly 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=Truerequires every source file and sidecar before any loading begins, blocks HTTP fallback, and cannot be combined withrefresh=True.max_pixelslimits band samples per asset, not the sum across assets. Installorbital-pv[ground]for GeoTIFF support; plotting is separate.
- orbitalpv.data.load_settlement_raster(path, *, max_pixels=1000000)[source]
Restore and verify a saved GHSL crop entirely offline.
- Parameters:
- Return type:
- 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.
- 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.
bboxis(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_pixelslimits 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.
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_labeland attribution inreference_creditwhen displaying mapped reference data. The function returns the figure and three axes for customization.
- 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(), includingvisual.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:
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.
redandsclassets 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:
- 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.
datahas shape(rows, columns, features).valid_mask=Truemeans 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,swir22andsclfrom 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.
- 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=Truetreats every other valid pixel as non-PV: this is a weak assumption for incomplete OSM inventories, not ground truth. Record that choice inPVTrainingSample.label_sourceand any independent evaluation’slabel_source.
- class orbitalpv.pv_detection.PVTrainingSample(features, labels, site_id, label_source)[source]
One labelled scene, with a stable site ID and explicit label source.
- class orbitalpv.pv_detection.PVFootprintPrediction(probabilities, mask, geojson, metadata)[source]
Image-derived scores, filtered mask and WGS84 footprint polygons.
probabilitiesare uncalibrated forest scores before area filtering.maskretains 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:
probabilities (MaskedArray)
mask (MaskedArray)
- 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_classvalid 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.
- 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.
- classmethod load(path)[source]
Read and validate numeric JSON; never execute serialized Python.
- 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.
- 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.
- 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; usePVFootprintModel.evaluatefor a held-out-site guard.
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=Falsebut 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 inmetadata.excluded. No geometry is silently repaired.
- 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.
semanticclusters feature centroids ateps_min a local equal-area projection, then merges intersecting geometries (including parent plants and their generators).panel_area_m2includes 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.dunnett2020uses 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_m2andcapacity_area_basisidentify the profile’s predictor separately from actual mappedpanel_area_m2andosm_polygon_area_m2. Singletons are retained withis_cluster=Falseunless explicitly excluded. This is a spatial grouping, not a registry of independently operated projects.
- 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.
- 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:
boxcox_lambda (float)
area_scale (float)
intercept (float)
slope (float)
coefficient_covariance (tuple[tuple[float, float], tuple[float, float]])
residual_std_mw (float)
n_training (int)
n_excluded (int)
min_area_m2 (float)
capacity_basis (str)
area_basis (str)
source (str)
fit_rmse_mw (float)
fit_mae_mw (float)
- 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_m2qualify. 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.
- 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_basismust be ‘AC’, ‘DC’, or ‘reported’;area_basismust 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 nonemptysourcedescribes external capacity evidence; this function cannot verify that provenance automatically.
- 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.
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_labelsdirectly. Missing map features do not establish absence of PV. Opting intobackground_is_negativerecords that assumption in the label source. Explicit negative geometries use WGS84 longitude/latitude coordinates.
- 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.
- 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.
- orbitalpv.ground_analysis.save_pv_prediction(prediction, destination, *, overwrite=False)[source]
Export WGS84 GeoJSON, native-grid scores/mask, and prediction metadata.
pv_prediction.tifcontains 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 withPVFootprintModel.save. Existing outputs require explicit overwrite, and a partial failure can leave earlier completed files in the destination directory.