From e566ae151296c93b7d27a90cf26b0491dc0679c7 Mon Sep 17 00:00:00 2001 From: Paul Grogan Date: Tue, 24 Nov 2026 23:05:53 -0700 Subject: [PATCH 1/3] Size the ground samples of observations Coverage and coincidence requests take optional sample_size options. The size of each observation's sample is the larger of its pixel and pixel spacing, along and across track (tatc.analysis.compute_sample_sizes), for pointed instruments and conical instruments with a beam width and scan sample spacing. Coverage results give each point's median and smallest sample size and counts of its observations, gridded to cells and summarized (SampleSizeSummary). An optional max_sample_size drops coarser observations before coverage (or coincidence) is computed; requests with it are rejected if an analyzed instrument has no pixels. Chunk tasks may give several tagged results (untag flattens them); cells are gridded by a shared helper (analysis.gridding), which sufficiency now uses. The instrument form adds pixel counts, overlap, and scan period of pointed instruments, and beam width and sample spacing of conical ones; the GUI adds the options, display modes, table columns, a summary section, and rows of the comparison of saved runs. --- README.md | 4 +- docs/api.rst | 11 + src/static/analysis.js | 83 +++++++- src/static/index.html | 20 ++ src/static/library.js | 10 +- src/static/schemas.js | 14 +- src/static/summary.js | 44 ++++ src/tatc_app/analysis/gridding.py | 70 +++++++ src/tatc_app/analysis/sample_sizes.py | 174 ++++++++++++++++ src/tatc_app/analysis/sufficiency.py | 33 +-- src/tatc_app/analysis/summary.py | 78 +++++++ src/tatc_app/analysis/tasks.py | 12 +- src/tatc_app/coincidence/router.py | 5 + src/tatc_app/coincidence/schemas.py | 4 +- src/tatc_app/coincidence/tasks.py | 14 ++ src/tatc_app/coverage/router.py | 7 + src/tatc_app/coverage/schemas.py | 63 +++++- src/tatc_app/coverage/tasks.py | 116 ++++++++++- tests/test_sample_sizes.py | 280 ++++++++++++++++++++++++++ 19 files changed, 985 insertions(+), 57 deletions(-) create mode 100644 src/tatc_app/analysis/gridding.py create mode 100644 src/tatc_app/analysis/sample_sizes.py create mode 100644 tests/test_sample_sizes.py diff --git a/README.md b/README.md index 93965db..eb93f8f 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,9 @@ tasks and visualized with animated results (CZML) in the GUI: * Coverage and revisit (`/analyze/coverage`): observations of a grid of points and cells, optionally with their sampling sufficiency: the error of estimating the mean of a field over the period from each point's samples (for a field with a decorrelation time), and - how the samples spread in time and local time of day. + how the samples spread in time and local time of day; and the ground sample size of + each observation (for instruments with pixels), optionally counting only observations + at most a maximum size. * Coincident observations (`/analyze/coincidence`): periods when several satellites (or satellites and constellations) observe a point of the grid at once, within a time difference, as for cross-calibration matchups, with the statistics of coverage of those diff --git a/docs/api.rst b/docs/api.rst index 1dba187..52e1d7a 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -64,6 +64,17 @@ they spread in time and local time of day. .. autopydantic_model:: tatc_app.analysis.summary.SufficiencySummary +A coverage (or coincidence) analysis may also size the ground samples of +observations (``sample_size`` of its request): the larger of each +observation's pixel and pixel spacing, along and across track, for +instruments with pixels. Coverage results summarize the sizes of each point's +observations; a maximum sample size drops coarser observations before +coverage (or coincidence) is computed. + +.. autopydantic_model:: tatc_app.coverage.schemas.SampleSizeOptions + +.. autopydantic_model:: tatc_app.analysis.summary.SampleSizeSummary + Coincident Observations ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/static/analysis.js b/src/static/analysis.js index 33b998c..faf9918 100644 --- a/src/static/analysis.js +++ b/src/static/analysis.js @@ -198,8 +198,8 @@ function rangeOfValues(property, scale) { // The display modes of coverage-like results (see `COVERAGE_TERMS`), with // the names of their events (such as "observations"): of their counts, the -// time since and between them, and their sampling sufficiency (only of -// results that assess it). +// time since and between them, their sampling sufficiency, and their ground +// sample sizes (only of results that assess them). function coverageDisplayModes(terms, event) { return [ { @@ -245,6 +245,16 @@ function coverageDisplayModes(terms, event) { value: "local-time", label: "Local time-of-day coverage (final)", unit: "%", sufficiency: true, property: "local_time_coverage", scale: 100, range: function() { return [0, 100]; } + }, + { + value: "sample-size", label: "Median ground sample size (final)", unit: "km", + sampleSize: true, reverse: true, property: "sample_size_median", scale: 1 / 1000, + range: rangeOfValues("sample_size_median", 1 / 1000) + }, + { + value: "best-sample-size", label: "Smallest ground sample size (final)", unit: "km", + sampleSize: true, reverse: true, property: "sample_size_min", scale: 1 / 1000, + range: rangeOfValues("sample_size_min", 1 / 1000) } ]; } @@ -274,13 +284,16 @@ const DISPLAY_MODES = { }; // Lists the display modes of results of a type: those of sampling -// sufficiency only if the results assess it. Keeps the selected mode if it -// is listed. +// sufficiency and of ground sample sizes only if the results assess them. +// Keeps the selected mode if it is listed. function updateDisplayModes(type, result) { const select = $("#" + type + "-mode"); const selected = select.val(); - const assessed = Boolean(result && result.summary && result.summary.sufficiency); - const modes = _.filter(DISPLAY_MODES[type], function(mode) { return !mode.sufficiency || assessed; }); + const summary = (result && result.summary) || {}; + const modes = _.filter(DISPLAY_MODES[type], function(mode) { + return (!mode.sufficiency || Boolean(summary.sufficiency)) && + (!mode.sampleSize || Boolean(summary.sample_size)); + }); fillSelect(select, modes); if (_.some(modes, { value: selected })) { select.val(selected); @@ -377,6 +390,30 @@ function setSufficiencyInputs(sufficiency) { } } +// Gets the options of ground sample sizes of a coverage (or coincidence) +// analysis: null if not sized, or (showing an error) undefined if invalid. +function getSampleSizeSpec() { + if (!$("#sample-size-enabled").is(":checked")) { + return null; + } + const text = String($("#sample-size-max").val()).trim(); + const km = text === "" ? null : Number(text); + if (km !== null && !(km > 0)) { + $("#analysis-error").text("The maximum sample size must be positive (or blank).").show(); + return undefined; + } + return { max_sample_size: km === null ? null : km * 1000 }; +} + +// Sets the inputs of ground sample sizes from the options of a request (none +// to turn them off). +function setSampleSizeInputs(sampleSize) { + $("#sample-size-enabled").prop("checked", Boolean(sampleSize)); + $("#sample-size-options").toggle(Boolean(sampleSize)); + const max = sampleSize && sampleSize.max_sample_size; + $("#sample-size-max").val(max ? Number((max / 1000).toFixed(6)) : ""); +} + // Gets the options of a coincidence analysis, or (showing an error) // undefined if invalid. function getCoincidenceSpec() { @@ -410,24 +447,28 @@ function setCoincidenceInputs(request) { function getAnalysisPayload(type, base) { if (type == "coverage") { const sufficiency = getSufficiencySpec(); - if (sufficiency === undefined) { + const sampleSize = getSampleSizeSpec(); + if (sufficiency === undefined || sampleSize === undefined) { return null; } return _.assign(base, { points: getPointsSpec(), cells: getCellsSpec(), - sufficiency: sufficiency + sufficiency: sufficiency, + sample_size: sampleSize }); } else if (type == "coincidence") { const sufficiency = getSufficiencySpec(); + const sampleSize = getSampleSizeSpec(); const coincidence = getCoincidenceSpec(); - if (sufficiency === undefined || coincidence === undefined) { + if (sufficiency === undefined || sampleSize === undefined || coincidence === undefined) { return null; } return _.assign(base, coincidence, { points: getPointsSpec(), cells: getCellsSpec(), - sufficiency: sufficiency + sufficiency: sufficiency, + sample_size: sampleSize }); } else if (type == "swaths") { // swaths animate over the analysis period @@ -572,7 +613,9 @@ function showAnalysisData() { const terms = COVERAGE_TERMS[type]; const coincidence = type == "coincidence"; const sufficiency = result.summary && result.summary.sufficiency; + const sampleSize = result.summary && result.summary.sample_size; const percent = function(share) { return share === null || share === undefined ? null : 100 * share; }; + const km = function(meters) { return meters === null || meters === undefined ? null : meters / 1000; }; let columns = pointColumns.concat([ { title: coincidence ? "Mean coincidence duration (s)" : "Mean access (s)", key: "access_s", format: number2 }, { title: terms.revisitAxis + " (h)", key: "revisit_h", format: number2 } @@ -590,6 +633,18 @@ function showAnalysisData() { ] ); } + if (sampleSize) { + columns = columns.concat( + [ + { title: "Median sample size (km)", key: "sample_size_median_km", format: number2 }, + { title: "Smallest sample size (km)", key: "sample_size_min_km", format: number2 }, + { title: "Observations sized", key: "observations_sized" } + ], + sampleSize.max_sample_size + ? [{ title: "Observations at most " + formatValue(sampleSize.max_sample_size / 1000) + " km", key: "observations_meeting" }] + : [] + ); + } showResultsTable({ title: coincidence ? "Coincidence Statistics" : "Coverage Statistics", columns: columns, @@ -602,6 +657,11 @@ function showAnalysisData() { revisit_p90_h: hours(p.revisit_p90), max_gap_h: hours(p.max_gap), local_time_pct: percent(p.local_time_coverage) + } : {}, sampleSize ? { + sample_size_median_km: km(p.sample_size_median), + sample_size_min_km: km(p.sample_size_min), + observations_sized: p.observations_sized, + observations_meeting: p.observations_meeting } : {}); }), filename: type + "-points", @@ -793,6 +853,9 @@ $(document).ready(function() { } limitAnimation(); }); + $("#sample-size-enabled").change(function() { + $("#sample-size-options").toggle($(this).is(":checked")); + }); $("#sufficiency-enabled").change(function() { $("#sufficiency-options").toggle($(this).is(":checked")); }); diff --git a/src/static/index.html b/src/static/index.html index 2ab5012..55d3018 100644 --- a/src/static/index.html +++ b/src/static/index.html @@ -265,6 +265,26 @@
Orbit Preview
+ +
+
+
+ + +
+
+ +
+
diff --git a/src/static/library.js b/src/static/library.js index aa8775e..860cbc9 100644 --- a/src/static/library.js +++ b/src/static/library.js @@ -164,7 +164,7 @@ let comparedRuns = []; // [{id, slot}] // The headline metric of runs of each analysis with a summary, and the rows // of their comparison: {label, value(summary), kind} (a share, duration, -// number, or count), and whether a row is `optional` (shown only if a run +// number, length in meters, or count), and whether a row is `optional` (shown only if a run // has a value). // The metrics of runs of coverage-like analyses (see `COVERAGE_TERMS`). function coverageRunMetrics(terms) { @@ -185,6 +185,9 @@ function coverageRunMetrics(terms) { { label: "Median effective samples", optional: true, value: function(s) { return s.sufficiency && s.sufficiency.effective_samples && s.sufficiency.effective_samples.median; }, kind: "number" }, { label: "90th percentile longest gap", optional: true, value: function(s) { return s.sufficiency && s.sufficiency.max_gap && s.sufficiency.max_gap.p90; }, kind: "duration" }, { label: "Local time-of-day coverage", optional: true, value: function(s) { return s.sufficiency && s.sufficiency.local_time_coverage; }, kind: "share" }, + // ground sample sizes (of runs that size them) + { label: "Median ground sample size", optional: true, value: function(s) { return s.sample_size && s.sample_size.median && s.sample_size.median.median; }, kind: "length" }, + { label: "Max. sample size required", optional: true, value: function(s) { return s.sample_size && s.sample_size.max_sample_size; }, kind: "length" }, { label: "Analysis period", value: function(s) { return _.last(s.coverage.times); }, kind: "duration" }, { label: "Points", value: function(s) { return s.points; }, kind: "count" } ] @@ -221,6 +224,9 @@ function formatMetric(value, kind, unit) { if (kind == "number") { return formatValue(value); } + if (kind == "length") { + return formatValue(value / 1000) + " km"; + } return Number(value).toLocaleString(); } @@ -372,9 +378,11 @@ function setAnalysisInputs(type, request) { } if (type == "coverage") { setSufficiencyInputs(request.sufficiency); + setSampleSizeInputs(request.sample_size); } else if (type == "coincidence") { setCoincidenceInputs(request); setSufficiencyInputs(request.sufficiency); + setSampleSizeInputs(request.sample_size); } else if (type == "swaths") { $("#swaths-step").val(request.step); if (request.segment) { diff --git a/src/static/schemas.js b/src/static/schemas.js index b166b8a..6cda21d 100644 --- a/src/static/schemas.js +++ b/src/static/schemas.js @@ -215,7 +215,14 @@ const INSTRUMENT_SPECS = { _.assign({ key: "roll_angle", label: "Roll", type: "number", min: -180, max: 180, default: 0, group: "pointing" }, ANGLE), _.assign({ key: "pitch_angle", label: "Pitch", type: "number", min: -180, max: 180, default: 0, group: "pointing" }, ANGLE), { key: "is_rectangular", label: "Rectangular", type: "checkbox", default: false }, - _.assign({ key: "field_of_regard", label: "Field of regard", type: "number", min: 0, max: 360, optional: true, help: "Blank for the default" }, ANGLE) + _.assign({ key: "field_of_regard", label: "Field of regard", type: "number", min: 0, max: 360, optional: true, help: "Blank for the default" }, ANGLE), + // pixels, which size the ground samples (blank for one pixel across + // the field of view) + { key: "cross_track_pixels", label: "Cross-track pixels", type: "integer", min: 1, optional: true, group: "pixels", help: "Pixels across the cross-track field of view, which size ground samples (blank for 1)" }, + { key: "along_track_pixels", label: "Along-track pixels", type: "integer", min: 1, optional: true, group: "pixels", help: "Pixels across the along-track field of view (blank for 1)" }, + { key: "cross_track_oversampling", label: "Cross-track overlap", type: "number", unit: "%", scale: 0.01, max: 99, step: "any", optional: true, group: "oversampling", help: "Share of a pixel overlapping its neighbor across track (negative for a gap; blank for 0)" }, + { key: "along_track_oversampling", label: "Along-track overlap", type: "number", unit: "%", scale: 0.01, max: 99, step: "any", optional: true, group: "oversampling", help: "Share of a pixel overlapping its neighbor along track (negative for a gap; blank for 0)" }, + { key: "scan_period", label: "Scan period", type: "number", unit: "s", min: 0, step: "any", optional: true, help: "Seconds between scans of a scanning instrument, which space its samples along track (blank if not modeled)" } ].concat(COMMON_INSTRUMENT_FIELDS) }, conical: { @@ -225,7 +232,10 @@ const INSTRUMENT_SPECS = { _.assign({ key: "along_track_field_of_view", label: "Along-track FOV", type: "number", min: 0, max: 180, default: 1 }, ANGLE), _.assign({ key: "scan_center_azimuth", label: "Scan center", type: "number", min: -180, max: 180, default: 0, group: "scan" }, ANGLE), _.assign({ key: "scan_half_width", label: "Scan half-width", type: "number", min: 0, max: 180, default: 180, group: "scan" }, ANGLE), - _.assign({ key: "field_of_regard", label: "Field of regard", type: "number", min: 0, max: 360, optional: true, help: "Blank for the default" }, ANGLE) + _.assign({ key: "field_of_regard", label: "Field of regard", type: "number", min: 0, max: 360, optional: true, help: "Blank for the default" }, ANGLE), + // samples, which size the ground samples (if both are given) + _.assign({ key: "beam_width", label: "Beam width", type: "number", min: 0, max: 90, optional: true, group: "samples", help: "Angular width of the beam (such as its half-power width), which sizes ground samples (blank if not modeled)" }, ANGLE), + _.assign({ key: "scan_sample_spacing", label: "Sample spacing", type: "number", min: 0, max: 180, optional: true, group: "samples", help: "Scan azimuth between neighboring samples along the scanned arc (blank if not modeled)" }, ANGLE) ].concat(COMMON_INSTRUMENT_FIELDS) } }; diff --git a/src/static/summary.js b/src/static/summary.js index 3be94a6..15fdb5d 100644 --- a/src/static/summary.js +++ b/src/static/summary.js @@ -509,9 +509,53 @@ function renderCoverageSummary(container, summary, terms) { if (summary.sufficiency) { renderSufficiencySummary(root, summary.sufficiency); } + if (summary.sample_size) { + renderSampleSizeSummary(root, summary.sample_size); + } root.append($("

").addClass("small text-muted mb-0").text(weightingNote(summary))); } +// Formats a length (meters) in kilometers. +function formatKilometers(meters) { + return formatValue(meters / 1000) + " km"; +} + +// Renders the summary of ground sample sizes (`sample_size` of a coverage +// summary) in a container. +function renderSampleSizeSummary(container, sizes) { + container.append($("

").addClass("summary-section-title").text("Ground sample size")); + container.append($("
").addClass("summary-section-note").text( + "The size on the ground of each observation's sample: the larger of its pixel and pixel spacing, along and across track. " + + "Only instruments with pixels (pointed, or conical with a beam width and sample spacing) have sizes." + )); + const tiles = $("
").addClass("summary-tiles").appendTo(container); + if (sizes.median) { + tiles.append(statTile("Median sample size", formatKilometers(sizes.median.median), + "of points' median · 90th percentile " + formatKilometers(sizes.median.p90))); + } else { + tiles.append(statTile("Median sample size", "–", "no observation is sized")); + } + if (sizes.best) { + tiles.append(statTile("Smallest sample size", formatKilometers(sizes.best.median), + "median of points' smallest")); + } + tiles.append(statTile("Observations sized", + formatShare(sizes.observations > 0 ? sizes.sized / sizes.observations : 0), + sizes.sized.toLocaleString() + " of " + sizes.observations.toLocaleString())); + if (sizes.max_sample_size) { + tiles.append(statTile("At most " + formatKilometers(sizes.max_sample_size), + formatShare(sizes.observations > 0 ? sizes.meeting / sizes.observations : 0), + "of observations, which count toward coverage")); + } + if (sizes.median_histogram) { + $("
").addClass("summary-charts").appendTo(container).append( + histogramChart(sizes.median_histogram, "Median ground sample size", + "Points with a sized observation", "Median sample size", + { unit: { label: "km", seconds: 1000 } }) + ); + } +} + // Formats a relative error (a share of the field's standard deviation). function formatRelativeError(value) { return formatValue(100 * value) + "% of σ"; diff --git a/src/tatc_app/analysis/gridding.py b/src/tatc_app/analysis/gridding.py new file mode 100644 index 0000000..43646bb --- /dev/null +++ b/src/tatc_app/analysis/gridding.py @@ -0,0 +1,70 @@ +""" +Gridding of statistics of points to the cells that contain them. + +@author: Paul T. Grogan +""" + +from typing import Dict, List, Optional + +import geopandas as gpd +import numpy as np +import pandas as pd + +# reductions of the values of the points of a cell +REDUCTIONS = ("mean", "rms", "min", "max") + + +def grid_columns( + points: pd.DataFrame, + cells: gpd.GeoDataFrame, + cell_targets: Dict[str, List[int]], + reductions: Dict[str, str], + masks: Optional[Dict[str, np.ndarray]] = None, +) -> gpd.GeoDataFrame: + """ + Grids columns of points to cells: reduces the finite values of the + points in each cell (`NaN`, or `NaT` for durations, for a cell without + any) by the mean, root-mean-square (`rms`), minimum, or maximum. + + Args: + points (pandas.DataFrame): The points, with the columns. + cells (geopandas.GeoDataFrame): The cells (with a `cell_id` column). + cell_targets (Dict[str, List[int]]): The indices of the points in + each cell, by `cell_id` (see `tasks.get_cell_targets`). + reductions (Dict[str, str]): The reduction of each column. + masks (Optional[Dict[str, numpy.ndarray]]): The points whose values + of a column count (by column; all, if not given). + + Returns: + geopandas.GeoDataFrame: the cells, with the gridded columns. + """ + result = cells.copy() + members = [cell_targets.get(str(cell_id), []) for cell_id in cells["cell_id"]] + for column, reduction in reductions.items(): + if reduction not in REDUCTIONS: + raise ValueError(f"Unknown reduction: {reduction}") + timedeltas = pd.api.types.is_timedelta64_dtype(points[column]) + values = ( + points[column].dt.total_seconds() if timedeltas else points[column] + ).to_numpy(dtype=float) + if masks is not None and column in masks: + values = np.where(masks[column], values, np.nan) + gridded = np.array([_reduce(values[m], reduction) for m in members]) + result[column] = pd.to_timedelta(gridded, unit="s") if timedeltas else gridded + return result + + +def _reduce(values: np.ndarray, reduction: str) -> float: + """ + Reduces the finite values of the points of a cell (`NaN` if none). + """ + values = values[np.isfinite(values)] + if len(values) == 0: + return np.nan + if reduction == "rms": + return float(np.sqrt(np.mean(values**2))) + if reduction == "min": + return float(values.min()) + if reduction == "max": + return float(values.max()) + return float(values.mean()) diff --git a/src/tatc_app/analysis/sample_sizes.py b/src/tatc_app/analysis/sample_sizes.py new file mode 100644 index 0000000..c90fb6e --- /dev/null +++ b/src/tatc_app/analysis/sample_sizes.py @@ -0,0 +1,174 @@ +""" +Ground sample sizes of the observations of points: the extent on the ground +of the observing instrument's pixel at each point, and the spacing between +pixels (see `tatc.analysis.compute_sample_sizes`), as one size per +observation (the larger of the pixel and its spacing, along and across +track: the finest detail it resolves in both directions), summarized for +each point, and a requirement that drops coarser observations. + +Sizes are defined for pointed instruments, and for conical instruments with a +beam width and a scan sample spacing; observations by other instruments have +no size (`NaN`). + +@author: Paul T. Grogan +""" + +from typing import Dict, List, Optional + +import geopandas as gpd +import numpy as np +import pandas as pd +from tatc.analysis import compute_sample_sizes +from tatc.schemas import ConicalInstrument, PointedInstrument, Satellite + +from .gridding import grid_columns + +# columns of the sizes of samples and their spacing (meters) +SIZE_COLUMNS = ["sample_along", "sample_cross", "spacing_along", "spacing_cross"] + +# columns of the sample sizes of each point (see `summarize_point_sizes`) +POINT_COLUMNS = [ + "target_hash", + "sample_size_median", + "sample_size_min", + "observations", + "observations_sized", + "observations_meeting", +] + + +def is_sized(instrument) -> bool: + """ + Tests whether the samples of an instrument have sizes: a pointed + instrument, or a conical instrument with a beam width and a scan sample + spacing. + """ + if isinstance(instrument, PointedInstrument): + return True + return ( + isinstance(instrument, ConicalInstrument) + and instrument.beam_width is not None + and instrument.scan_sample_spacing is not None + ) + + +def size_observations( + observations: gpd.GeoDataFrame, satellites: List[Satellite] +) -> gpd.GeoDataFrame: + """ + Sizes the samples of observations of points by satellites. + + Args: + observations (geopandas.GeoDataFrame): The observations (by + `satellite` and `instrument`, see + `tatc.analysis.collect_observations`). + satellites (List[tatc.schemas.Satellite]): The satellites. + + Returns: + geopandas.GeoDataFrame: the observations, with the `sample_size` of + each (meters, `NaN` if not defined). + """ + result = observations.copy() + if observations.empty: + result["sample_size"] = pd.Series([], dtype=float) + return result + sized = compute_sample_sizes(observations, satellites) + # the larger of the pixel and spacing in both directions (NaN if any is) + result["sample_size"] = sized[SIZE_COLUMNS].to_numpy(dtype=float).max(axis=1) + return result + + +def meets_requirement( + observations: pd.DataFrame, max_sample_size: Optional[float] +) -> np.ndarray: + """ + Tests which sized observations meet a maximum sample size (all, without + one; none without a size, otherwise). + """ + sizes = observations["sample_size"].to_numpy(dtype=float) + if max_sample_size is None: + return np.ones(len(sizes), dtype=bool) + return np.nan_to_num(sizes, nan=np.inf) <= max_sample_size + + +def summarize_point_sizes( + sized: pd.DataFrame, max_sample_size: Optional[float] = None +) -> pd.DataFrame: + """ + Summarizes the sample sizes of the observations of each observed point: + the median and smallest size (meters) of its sized observations, and the + numbers of its observations, sized observations, and observations that + meet the maximum sample size (if any; else, the sized ones). + + Args: + sized (pandas.DataFrame): The sized observations (see + `size_observations`). + max_sample_size (Optional[float]): The maximum sample size (meters). + + Returns: + pandas.DataFrame: a row per observed point (`POINT_COLUMNS`). + """ + if sized.empty: + return pd.DataFrame({column: [] for column in POINT_COLUMNS}) + sizes = sized["sample_size"].astype(float) + meeting = meets_requirement(sized, max_sample_size) & sizes.notna().to_numpy() + grouped = pd.DataFrame( + { + "target_hash": sized["target_hash"].to_numpy(), + "size": sizes.to_numpy(), + "sized": sizes.notna().to_numpy(), + "meeting": meeting, + } + ).groupby("target_hash", sort=False) + return pd.DataFrame( + { + "sample_size_median": grouped["size"].median(), + "sample_size_min": grouped["size"].min(), + "observations": grouped.size(), + "observations_sized": grouped["sized"].sum(), + "observations_meeting": grouped["meeting"].sum(), + } + ).reset_index()[POINT_COLUMNS] + + +def add_point_sizes(points: pd.DataFrame, sizes: pd.DataFrame) -> pd.DataFrame: + """ + Adds the sample sizes of points (see `summarize_point_sizes`) to their + statistics, by `target_hash`, in their order: points without + observations have no sizes and none of the counts. + """ + lookup = sizes.drop_duplicates("target_hash").set_index("target_hash") + result = points.copy() + for column in POINT_COLUMNS[1:]: + values = points["target_hash"].map(lookup[column]) + if column.startswith("observations"): + values = values.fillna(0).astype(int) + result[column] = values.to_numpy() + return result + + +def grid_sample_sizes( + points: pd.DataFrame, + cells: gpd.GeoDataFrame, + cell_targets: Dict[str, List[int]], +) -> gpd.GeoDataFrame: + """ + Grids the sample sizes of points to cells: the mean of the median sample + sizes of the points in each cell, and the smallest sample size of any. + + Args: + points (pandas.DataFrame): The points, with their sample sizes (see + `add_point_sizes`). + cells (geopandas.GeoDataFrame): The cells (with a `cell_id` column). + cell_targets (Dict[str, List[int]]): The indices of the points in + each cell, by `cell_id`. + + Returns: + geopandas.GeoDataFrame: the cells, with their sample sizes. + """ + return grid_columns( + points, + cells, + cell_targets, + {"sample_size_median": "mean", "sample_size_min": "min"}, + ) diff --git a/src/tatc_app/analysis/sufficiency.py b/src/tatc_app/analysis/sufficiency.py index e9c033b..064c019 100644 --- a/src/tatc_app/analysis/sufficiency.py +++ b/src/tatc_app/analysis/sufficiency.py @@ -25,6 +25,8 @@ estimate_sampling_error, ) +from .gridding import grid_columns + # columns of the sampling error, with how each is gridded to cells: # root-mean-square ("rms"), mean, or maximum ("max") ERROR_COLUMNS = {"relative_error": "rms", "effective_samples": "mean"} @@ -173,31 +175,8 @@ def grid_sufficiency( if SAMPLING_ERROR_COLUMN in points.columns: reductions[SAMPLING_ERROR_COLUMN] = "rms" reductions.update(TIME_COLUMNS) - result = cells.copy() - members = [cell_targets.get(str(cell_id), []) for cell_id in cells["cell_id"]] + # (points not observed have no effective samples, rather than zero) observed = np.isfinite(points["relative_error"].to_numpy(dtype=float)) - for column, reduction in reductions.items(): - timedeltas = pd.api.types.is_timedelta64_dtype(points[column]) - values = ( - points[column].dt.total_seconds() if timedeltas else points[column] - ).to_numpy(dtype=float) - if column == "effective_samples": - # (points not observed have none, rather than a count of zero) - values = np.where(observed, values, np.nan) - gridded = np.array([_reduce(values[m], reduction) for m in members]) - result[column] = pd.to_timedelta(gridded, unit="s") if timedeltas else gridded - return result - - -def _reduce(values: np.ndarray, reduction: str) -> float: - """ - Reduces the finite values of the points of a cell (`NaN` if none). - """ - values = values[np.isfinite(values)] - if len(values) == 0: - return np.nan - if reduction == "rms": - return float(np.sqrt(np.mean(values**2))) - if reduction == "max": - return float(values.max()) - return float(values.mean()) + return grid_columns( + points, cells, cell_targets, reductions, {"effective_samples": observed} + ) diff --git a/src/tatc_app/analysis/summary.py b/src/tatc_app/analysis/summary.py index 821cca0..4e8b5e7 100644 --- a/src/tatc_app/analysis/summary.py +++ b/src/tatc_app/analysis/summary.py @@ -161,6 +161,43 @@ class SufficiencySummary(BaseModel): ) +class SampleSizeSummary(BaseModel): + """ + Summary of the ground sample sizes of the observations of the points of a + region (in meters). + """ + + max_sample_size: Optional[float] = Field( + None, description="Required maximum sample size (meters), if any." + ) + observations: int = Field( + ..., description="Number of observations of the points (by each satellite)." + ) + sized: int = Field( + ..., + description="Number of observations with a sample size (by instruments " + "with pixels).", + ) + meeting: Optional[int] = Field( + None, + description="Number of observations at most the maximum sample size " + "(which count toward coverage), if required.", + ) + median: Optional[Distribution] = Field( + None, + description="Distribution of the median sample size (meters) of points " + "with a sized observation.", + ) + median_histogram: Optional[Histogram] = Field( + None, description="Histogram of the median sample size (meters)." + ) + best: Optional[Distribution] = Field( + None, + description="Distribution of the smallest sample size (meters) of " + "points with a sized observation.", + ) + + class CoverageSummary(BaseModel): """ Summary of coverage over the points of a region. @@ -193,6 +230,9 @@ class CoverageSummary(BaseModel): sufficiency: Optional[SufficiencySummary] = Field( None, description="Summary of sampling sufficiency, if assessed." ) + sample_size: Optional[SampleSizeSummary] = Field( + None, description="Summary of ground sample sizes, if sized." + ) class LatencySummary(BaseModel): @@ -497,6 +537,44 @@ def summarize_sufficiency( # pylint: disable=too-many-arguments,too-many-locals ) +def summarize_sample_sizes( + points: pd.DataFrame, + weighting: Weighting, + max_sample_size: Optional[float] = None, +) -> SampleSizeSummary: + """ + Summarizes the ground sample sizes of points. + + Args: + points (pandas.DataFrame): The points, with their sample sizes (see + `sample_sizes.add_point_sizes`) and point `geometry`. + weighting (Weighting): The weighting of points. + max_sample_size (Optional[float]): The required maximum sample size + (meters), if any. + + Returns: + SampleSizeSummary: The summary. + """ + weights = point_weights(points, weighting) + median, median_histogram = summarize_values( + points["sample_size_median"].to_numpy(dtype=float), weights + ) + best, _ = summarize_values(points["sample_size_min"].to_numpy(dtype=float), weights) + return SampleSizeSummary( + max_sample_size=max_sample_size, + observations=int(points["observations"].sum()), + sized=int(points["observations_sized"].sum()), + meeting=( + None + if max_sample_size is None + else int(points["observations_meeting"].sum()) + ), + median=median, + median_histogram=median_histogram, + best=best, + ) + + def summarize_latency( points: pd.DataFrame, contacts: pd.DataFrame, diff --git a/src/tatc_app/analysis/tasks.py b/src/tatc_app/analysis/tasks.py index a75cfc1..367a5bf 100644 --- a/src/tatc_app/analysis/tasks.py +++ b/src/tatc_app/analysis/tasks.py @@ -39,9 +39,15 @@ def tag(kind: str, data) -> dict: def untag(results: list, kind: str) -> list: """ - Gets the results of parallel tasks of a kind. - """ - return [r["data"] for r in results if r["kind"] == kind] + Gets the results of parallel tasks of a kind (a task may give several + tagged results, as a list). + """ + tagged = [ + r + for result in results + for r in (result if isinstance(result, list) else [result]) + ] + return [r["data"] for r in tagged if r["kind"] == kind] def deserialize_members(members: List[str]) -> List[Satellite]: diff --git a/src/tatc_app/coincidence/router.py b/src/tatc_app/coincidence/router.py index 1399e37..8917413 100644 --- a/src/tatc_app/coincidence/router.py +++ b/src/tatc_app/coincidence/router.py @@ -64,6 +64,11 @@ def enqueue_coincidence_analysis( request.max_time_difference.total_seconds(), request.instantaneous, request.get_platform_systems(), + ( + None + if request.sample_size is None + else request.sample_size.max_sample_size + ), ) for points_chunk in chunk(points) ], diff --git a/src/tatc_app/coincidence/schemas.py b/src/tatc_app/coincidence/schemas.py index a77a0ea..3163d58 100644 --- a/src/tatc_app/coincidence/schemas.py +++ b/src/tatc_app/coincidence/schemas.py @@ -29,7 +29,9 @@ class CoincidenceAnalysisRequest(CoverageAnalysisRequest): User request to analyze coincident observations: the periods when at least `min_platforms` platforms observe a point at once (within `max_time_difference`), with the statistics of coverage of those - periods (and, optionally, their sampling sufficiency). + periods (and, optionally, their sampling sufficiency). A maximum sample + size (`sample_size`) drops coarser observations before coincidences are + found; coincidences have no statistics of sample sizes. """ min_platforms: int = Field( diff --git a/src/tatc_app/coincidence/tasks.py b/src/tatc_app/coincidence/tasks.py index 2a2e136..5ebcb6b 100644 --- a/src/tatc_app/coincidence/tasks.py +++ b/src/tatc_app/coincidence/tasks.py @@ -21,6 +21,7 @@ ) from tatc.schemas import Satellite +from ..analysis.sample_sizes import meets_requirement, size_observations from ..analysis.tasks import deserialize_members, tag from ..coverage.tasks import OBSERVATION_COLUMNS from ..utils.serialization import empty_frame, from_geojson, to_geojson @@ -81,6 +82,7 @@ def collect_coincident_observations( # pylint: disable=too-many-arguments max_time_difference: timedelta = timedelta(0), instantaneous: bool = False, systems: Optional[Dict[str, str]] = None, + max_sample_size: Optional[float] = None, ) -> gpd.GeoDataFrame: """ Collects the coincident observations of points by all instruments of @@ -101,6 +103,9 @@ def collect_coincident_observations( # pylint: disable=too-many-arguments systems (Optional[Dict[str, str]]): The platform (system) of each member satellite, by name, or `None` if each member is a platform. + max_sample_size (Optional[float]): The largest ground sample size + (meters) of an observation that counts (see + `analysis.sample_sizes`), or `None` for every observation. Returns: geopandas.GeoDataFrame: The aggregated coincident observations, with @@ -109,6 +114,11 @@ def collect_coincident_observations( # pylint: disable=too-many-arguments observations = collect_observations( points, satellites, start, end, instrument_index=None ) + if max_sample_size is not None: + sized = size_observations(observations, satellites) + observations = sized[meets_requirement(sized, max_sample_size)].drop( + columns="sample_size" + ) if observations.empty: return empty_frame(OBSERVATION_COLUMNS) if systems is not None: @@ -136,6 +146,7 @@ def collect_coincidence_task( # pylint: disable=too-many-arguments max_time_difference: float = 0, instantaneous: bool = False, systems: Optional[dict] = None, + max_sample_size: Optional[float] = None, ) -> dict: """ Task to collect the coincident observations of a chunk of points. @@ -152,6 +163,8 @@ def collect_coincidence_task( # pylint: disable=too-many-arguments instantaneous (bool): True to compare the observations' epochs. systems (Optional[dict]): The platform of each member satellite, by name, or `None` if each member is a platform. + max_sample_size (Optional[float]): The largest ground sample size + (meters) of an observation that counts, or `None`. Returns: dict: Tagged (`obs`) GeoJSON serialized aggregated coincident @@ -166,5 +179,6 @@ def collect_coincidence_task( # pylint: disable=too-many-arguments timedelta(seconds=max_time_difference), instantaneous, systems, + max_sample_size, ) return tag("obs", to_geojson(results)) diff --git a/src/tatc_app/coverage/router.py b/src/tatc_app/coverage/router.py index d9be1b2..217c5a2 100644 --- a/src/tatc_app/coverage/router.py +++ b/src/tatc_app/coverage/router.py @@ -49,6 +49,11 @@ def enqueue_coverage_analysis( serialized = serialize_members(members) points = resolve_points(request.points) cells = resolve_cells(request.cells) + sample_size = ( + None + if request.sample_size is None + else request.sample_size.model_dump(mode="json") + ) return enqueue_analysis( request, members, @@ -58,6 +63,7 @@ def enqueue_coverage_analysis( serialized, request.start.isoformat(), request.end.isoformat(), + sample_size=sample_size, ) for points_chunk in chunk(points) ], @@ -73,6 +79,7 @@ def enqueue_coverage_analysis( if request.sufficiency is None else request.sufficiency.model_dump(mode="json") ), + sample_size=sample_size, ), slot, ) diff --git a/src/tatc_app/coverage/schemas.py b/src/tatc_app/coverage/schemas.py index fc446a6..f3cf083 100644 --- a/src/tatc_app/coverage/schemas.py +++ b/src/tatc_app/coverage/schemas.py @@ -8,8 +8,9 @@ from typing import Dict, List, Optional from geojson_pydantic import FeatureCollection -from pydantic import Field, field_validator +from pydantic import Field, field_validator, model_validator +from ..analysis.sample_sizes import is_sized from ..analysis.schemas import AnimatedResult, PointsCellsAnalysisRequest from ..analysis.summary import CoverageSummary from ..analysis.timeline import Timeline @@ -63,6 +64,26 @@ def validate_decorrelation_time(cls, value: timedelta) -> timedelta: return value +class SampleSizeOptions(CamelModel): + """ + Options to size the ground samples of observations (see + `analysis.sample_sizes`): their statistics for each point (in coverage + results), and an optional requirement that drops coarser observations + before coverage (or coincidence) is computed. + """ + + max_sample_size: Optional[float] = Field( + None, + gt=0, + description="Largest sample size (meters) of an observation that counts " + "(`null` to count every observation): observations with a larger " + "pixel or pixel spacing, along or across track, are dropped. Requires " + "every analyzed instrument to be pointed, or conical with a beam width " + "and a scan sample spacing.", + examples=[1000], + ) + + class CoverageAnalysisRequest(PointsCellsAnalysisRequest): """ User request to perform coverage analysis. @@ -73,6 +94,37 @@ class CoverageAnalysisRequest(PointsCellsAnalysisRequest): description="Options to also assess sampling sufficiency (`null` to " "skip it).", ) + sample_size: Optional[SampleSizeOptions] = Field( + None, + description="Options to size the ground samples of observations (`null` " + "to skip it).", + ) + + @model_validator(mode="after") + def validate_sample_size(self) -> "CoverageAnalysisRequest": + """ + Validates every analyzed instrument has sized samples if a maximum + sample size is required (otherwise none of its observations would + count). + """ + if self.sample_size is None or self.sample_size.max_sample_size is None: + return self + unsized = sorted( + { + f"{member.name} ({instrument.name})" + for member in self.get_members() + for instrument in member.instruments + if not is_sized(instrument) + } + ) + if unsized: + listed = ", ".join(unsized[:5]) + (", ..." if len(unsized) > 5 else "") + raise ValueError( + "A maximum sample size requires instruments with pixels: pointed, " + "or conical with a beam width and a scan sample spacing. Without " + f"them: {listed}." + ) + return self class CoverageAnalysisResult(AnimatedResult): @@ -87,7 +139,11 @@ class CoverageAnalysisResult(AnimatedResult): "sufficiency, also the `relative_error` (and `sampling_error`, given " "the field's standard deviation), `effective_samples`, `revisit_p50` " "and `revisit_p90` (seconds between consecutive samples), `max_gap` " - "(seconds), and `local_time_coverage`.", + "(seconds), and `local_time_coverage`. With sample sizes, also the " + "`sample_size_median` and `sample_size_min` (meters) of its " + "observations, and the numbers of its `observations`, " + "`observations_sized`, and `observations_meeting` the maximum sample " + "size (before coarser observations are dropped).", ) cells: FeatureCollection = Field( ..., @@ -96,7 +152,8 @@ class CoverageAnalysisResult(AnimatedResult): "sufficiency, also the root-mean-square `relative_error` (and " "`sampling_error`) and mean `effective_samples` of its observed " "points, and the mean `local_time_coverage` and longest `max_gap` of " - "all its points.", + "all its points. With sample sizes, also the mean `sample_size_median` " + "and smallest `sample_size_min` of its points.", ) timeline: Timeline = Field( ..., description="Observations of points (in the order of `points`)." diff --git a/src/tatc_app/coverage/tasks.py b/src/tatc_app/coverage/tasks.py index 26b808b..dd20c73 100644 --- a/src/tatc_app/coverage/tasks.py +++ b/src/tatc_app/coverage/tasks.py @@ -6,9 +6,10 @@ import json from datetime import datetime -from typing import List, Optional +from typing import List, Optional, Tuple, Union import geopandas as gpd +import pandas as pd from tatc.analysis import ( aggregate_observations, collect_observations, @@ -17,8 +18,21 @@ ) from tatc.schemas import Satellite +from ..analysis.sample_sizes import ( + POINT_COLUMNS, + add_point_sizes, + grid_sample_sizes, + meets_requirement, + size_observations, + summarize_point_sizes, +) from ..analysis.sufficiency import compute_sufficiency, grid_sufficiency -from ..analysis.summary import Weighting, summarize_coverage, summarize_sufficiency +from ..analysis.summary import ( + Weighting, + summarize_coverage, + summarize_sample_sizes, + summarize_sufficiency, +) from ..analysis.tasks import ( combine_animation, deserialize_members, @@ -29,7 +43,7 @@ from ..analysis.timeline import build_timeline from ..utils.serialization import concat, empty_frame, from_geojson, to_geojson from ..worker import app -from .schemas import CoverageAnalysisResult, SufficiencyOptions +from .schemas import CoverageAnalysisResult, SampleSizeOptions, SufficiencyOptions OBSERVATION_COLUMNS = [ "target_hash", @@ -63,16 +77,59 @@ def collect_aggregated_observations( Returns: geopandas.GeoDataFrame: The aggregated observations. """ + return collect_sized_observations(points, satellites, start, end)[0] + + +def collect_sized_observations( + points: gpd.GeoDataFrame, + satellites: List[Satellite], + start: datetime, + end: datetime, + sample_size: Optional[SampleSizeOptions] = None, +) -> Tuple[gpd.GeoDataFrame, Optional[pd.DataFrame]]: + """ + Collects and aggregates observations of points by all instruments of + satellites, sizing their ground samples (if requested): the observations + coarser than a maximum sample size (if any) are dropped before they are + aggregated. + + Args: + points (geopandas.GeoDataFrame): The points. + satellites (List[tatc.schemas.Satellite]): The satellites. + start (datetime.datetime): The start of the analysis period. + end (datetime.datetime): The end of the analysis period. + sample_size (Optional[SampleSizeOptions]): Options to size the + samples, or `None`. + + Returns: + Tuple[geopandas.GeoDataFrame, Optional[pandas.DataFrame]]: The + aggregated observations, and the sample sizes of the observed + points (see `sample_sizes.summarize_point_sizes`; of all their + observations, before any are dropped), if sized. + """ observations = collect_observations( points, satellites, start, end, instrument_index=None ) + sizes = None + if sample_size is not None: + sized = size_observations(observations, satellites) + sizes = summarize_point_sizes(sized, sample_size.max_sample_size) + observations = sized[ + meets_requirement(sized, sample_size.max_sample_size) + ].drop(columns="sample_size") if observations.empty: - return empty_frame(OBSERVATION_COLUMNS) - return aggregate_observations(observations)[OBSERVATION_COLUMNS] + return empty_frame(OBSERVATION_COLUMNS), sizes + return aggregate_observations(observations)[OBSERVATION_COLUMNS], sizes @app.task -def collect_coverage_task(points: str, satellites: list, start: str, end: str) -> dict: +def collect_coverage_task( + points: str, + satellites: list, + start: str, + end: str, + sample_size: Optional[dict] = None, +) -> Union[dict, list]: """ Task to collect and aggregate observations of a chunk of points. @@ -81,17 +138,28 @@ def collect_coverage_task(points: str, satellites: list, start: str, end: str) - satellites (list): List of JSON serialized :class:`tatc.schemas.Satellite` objects. start (str): ISO 8601 serialized start time. end (str): ISO 8601 serialized end time. + sample_size (Optional[dict]): JSON serialized `SampleSizeOptions`, or + `None` not to size samples. Returns: - dict: Tagged (`obs`) GeoJSON serialized aggregated observations. + Union[dict, list]: Tagged (`obs`) GeoJSON serialized aggregated + observations, and, if sized, tagged (`size`) JSON serialized + sample sizes of the observed points. """ - results = collect_aggregated_observations( + options = ( + None if sample_size is None else SampleSizeOptions.model_validate(sample_size) + ) + observations, sizes = collect_sized_observations( from_geojson(points), deserialize_members(satellites), datetime.fromisoformat(start), datetime.fromisoformat(end), + options, ) - return tag("obs", to_geojson(results)) + result = tag("obs", to_geojson(observations)) + if sizes is None: + return result + return [result, tag("size", sizes.to_json(orient="records"))] def compute_coverage( # pylint: disable=too-many-arguments @@ -103,6 +171,8 @@ def compute_coverage( # pylint: disable=too-many-arguments end: Optional[datetime] = None, weighting: Weighting = Weighting.uniform, sufficiency: Optional[SufficiencyOptions] = None, + sample_size: Optional[SampleSizeOptions] = None, + sizes: Optional[pd.DataFrame] = None, ) -> dict: """ Reduces aggregated observations to coverage statistics of points and @@ -120,6 +190,10 @@ def compute_coverage( # pylint: disable=too-many-arguments weighting (Weighting): The weighting of points in the summary. sufficiency (Optional[SufficiencyOptions]): Options to also assess the sampling sufficiency of points and cells, or `None`. + sample_size (Optional[SampleSizeOptions]): Options of the ground + sample sizes of points and cells, or `None` (without sizes). + sizes (Optional[pandas.DataFrame]): The sample sizes of the observed + points (see `sample_sizes.summarize_point_sizes`), if sized. Returns: dict: The `points`, `cells`, `timeline`, `cell_targets`, and @@ -159,6 +233,16 @@ def compute_coverage( # pylint: disable=too-many-arguments sufficiency.standard_deviation, sufficiency.target_relative_error, ) + if sample_size is not None: + reduced = add_point_sizes( + reduced, + sizes if sizes is not None else pd.DataFrame(columns=POINT_COLUMNS), + ) + gridded = grid_sample_sizes(reduced, gridded, cell_targets) + if summary is not None: + summary.sample_size = summarize_sample_sizes( + reduced, weighting, sample_size.max_sample_size + ) return { "points": json.loads(to_geojson(reduced)), "cells": json.loads(to_geojson(gridded)), @@ -178,6 +262,7 @@ def combine_coverage_task( end: Optional[str] = None, weighting: str = Weighting.uniform.value, sufficiency: Optional[dict] = None, + sample_size: Optional[dict] = None, ) -> str: """ Task to combine the observations of chunks of points into coverage @@ -195,11 +280,18 @@ def combine_coverage_task( `Weighting`). sufficiency (Optional[dict]): JSON serialized `SufficiencyOptions`, or `None` to skip sampling sufficiency. + sample_size (Optional[dict]): JSON serialized `SampleSizeOptions` of + the sample sizes the parallel tasks give (tagged `size`), or + `None` without sizes. Returns: str: JSON serialized `CoverageAnalysisResult`. """ animation = combine_animation(results, start, colors) + sizes = pd.DataFrame( + [row for data in untag(results, "size") for row in json.loads(data)], + columns=POINT_COLUMNS, + ) observations = concat( from_geojson( data, @@ -223,6 +315,12 @@ def combine_coverage_task( if sufficiency is None else SufficiencyOptions.model_validate(sufficiency) ), + ( + None + if sample_size is None + else SampleSizeOptions.model_validate(sample_size) + ), + sizes, ), tracks=animation.tracks, colors=animation.colors, diff --git a/tests/test_sample_sizes.py b/tests/test_sample_sizes.py new file mode 100644 index 0000000..beff4ed --- /dev/null +++ b/tests/test_sample_sizes.py @@ -0,0 +1,280 @@ +from datetime import datetime, timedelta, timezone + +import geopandas as gpd +import numpy as np +import pandas as pd +from shapely.geometry import Point as GeoPoint +from shapely.geometry import box +from tatc.analysis import ( + aggregate_observations, + collect_observations, + compute_sample_sizes, + reduce_observations, +) +from tatc.generation import generate_points_uniform_spacing +from tatc.schemas import ( + ConicalInstrument, + Instrument, + PointedInstrument, + Satellite, + SunSynchronousOrbit, +) + +from tatc_app.analysis.sample_sizes import ( + POINT_COLUMNS, + add_point_sizes, + grid_sample_sizes, + is_sized, + meets_requirement, + size_observations, + summarize_point_sizes, +) +from tatc_app.analysis.summary import Weighting, summarize_sample_sizes +from tatc_app.coincidence.schemas import ( + CoincidenceAnalysisRequest, + CoincidenceAnalysisResult, +) +from tatc_app.coverage.schemas import ( + CoverageAnalysisRequest, + CoverageAnalysisResult, + SampleSizeOptions, +) +from tatc_app.generation.schemas import CellGenerator, PointGenerator +from tatc_app.utils.serialization import from_geojson + +from .base import TatcTestCase + +START = datetime(2022, 6, 1, tzinfo=timezone.utc) +END = datetime(2022, 6, 2, tzinfo=timezone.utc) +ORBIT = SunSynchronousOrbit( + altitude=705e3, equator_crossing_time="13:30", equator_crossing_ascending=True +) +# a 100-degree swath of 1000 pixels: about 1 km at nadir, growing off nadir +POINTED = PointedInstrument( + name="P", + cross_track_field_of_view=100, + along_track_field_of_view=0.1, + cross_track_pixels=1000, +) + + +def satellite(name="A", instruments=None) -> Satellite: + return Satellite(name=name, orbit=ORBIT, instruments=instruments or [POINTED]) + + +class SampleSizeFunctionsTestCase(TatcTestCase): + def setUp(self): + super().setUp() + self.points = generate_points_uniform_spacing(1000e3) + + def test_is_sized(self): + self.assertTrue(is_sized(POINTED)) + self.assertFalse(is_sized(Instrument(name="S"))) + conical = ConicalInstrument( + name="C", cone_angle=45, along_track_field_of_view=1 + ) + self.assertFalse(is_sized(conical)) + self.assertTrue( + is_sized( + conical.model_copy(update={"beam_width": 1, "scan_sample_spacing": 1}) + ) + ) + + def test_size_observations(self): + sat = satellite( + instruments=[POINTED, Instrument(name="S", field_of_regard=100)] + ) + observations = collect_observations( + self.points, [sat], START, END, instrument_index=None + ) + sized = size_observations(observations, [sat]) + self.assertEqual(len(sized), len(observations)) + pointed = sized[sized.instrument == "P"] + simple = sized[sized.instrument == "S"] + self.assertTrue(pointed.sample_size.notna().all()) + self.assertTrue(simple.sample_size.isna().all()) + # the larger of the pixel and its spacing, along and across track + expected = compute_sample_sizes(observations, [sat])[ + ["sample_along", "sample_cross", "spacing_along", "spacing_cross"] + ].max(axis=1, skipna=False) + np.testing.assert_allclose(sized.sample_size, expected, equal_nan=True) + # about 1 km at nadir, larger off nadir + self.assertGreater(pointed.sample_size.min(), 500) + self.assertLess(pointed.sample_size.min(), 2000) + self.assertGreater(pointed.sample_size.max(), 2 * pointed.sample_size.min()) + # nothing to size + self.assertTrue(size_observations(observations.iloc[0:0], [sat]).empty) + + def test_requirement_and_point_sizes(self): + sized = pd.DataFrame( + { + "target_hash": ["a", "a", "a", "b", "b"], + "sample_size": [1000.0, 3000.0, np.nan, 500.0, 2500.0], + } + ) + np.testing.assert_array_equal( + meets_requirement(sized, 2000), [True, False, False, True, False] + ) + self.assertTrue(meets_requirement(sized, None).all()) + sizes = summarize_point_sizes(sized, 2000).set_index("target_hash") + self.assertEqual(sizes.loc["a", "sample_size_median"], 2000) + self.assertEqual(sizes.loc["a", "sample_size_min"], 1000) + self.assertEqual( + list(sizes.loc["a", ["observations", "observations_sized"]]), [3, 2] + ) + self.assertEqual(sizes.loc["a", "observations_meeting"], 1) + # without a requirement, the sized observations meet it + sizes = summarize_point_sizes(sized).set_index("target_hash") + self.assertEqual(sizes.loc["b", "observations_meeting"], 2) + self.assertEqual( + list(summarize_point_sizes(sized.iloc[0:0]).columns), POINT_COLUMNS + ) + + def test_add_grid_and_summarize(self): + points = gpd.GeoDataFrame( + {"target_hash": ["a", "b", "c"]}, + geometry=[GeoPoint(0, 0), GeoPoint(1, 0), GeoPoint(0, 60)], + crs="EPSG:4326", + ) + sizes = pd.DataFrame( + { + "target_hash": ["b", "a"], + "sample_size_median": [2000.0, 1000.0], + "sample_size_min": [1500.0, 800.0], + "observations": [4, 2], + "observations_sized": [4, 2], + "observations_meeting": [1, 2], + } + ) + added = add_point_sizes(points, sizes) + # in the order of the points, and none for the point not observed + self.assertEqual(list(added.sample_size_median[:2]), [1000, 2000]) + self.assertTrue(np.isnan(added.sample_size_median[2])) + self.assertEqual(list(added.observations), [2, 4, 0]) + cells = gpd.GeoDataFrame( + {"cell_id": ["x", "y"]}, + geometry=[box(-1, -1, 2, 1), box(-1, 59, 1, 61)], + crs="EPSG:4326", + ) + gridded = grid_sample_sizes(added, cells, {"x": [0, 1], "y": [2]}) + self.assertEqual(gridded.sample_size_median[0], 1500) + self.assertEqual(gridded.sample_size_min[0], 800) + self.assertTrue(np.isnan(gridded.sample_size_median[1])) + summary = summarize_sample_sizes(added, Weighting.uniform, 1200) + self.assertEqual(summary.max_sample_size, 1200) + self.assertEqual( + (summary.observations, summary.sized, summary.meeting), (6, 6, 3) + ) + self.assertEqual(summary.median.count, 2) + self.assertEqual(summary.median.mean, 1500) + self.assertEqual(summary.best.max, 1500) + self.assertIsNone(summarize_sample_sizes(added, Weighting.uniform).meeting) + + +class SampleSizeEndpointsTestCase(TatcTestCase): + def request(self, satellites=None, **kwargs) -> CoverageAnalysisRequest: + return CoverageAnalysisRequest( + satellites=satellites or [satellite()], + start=START, + end=END, + points=PointGenerator(method="equally_spaced", distance=1000e3), + cells=CellGenerator(method="equally_spaced", distance=5000e3), + **kwargs, + ) + + def analyze(self, request) -> CoverageAnalysisResult: + task = self.run_analysis("/analyze/coverage", request) + return CoverageAnalysisResult.model_validate( + self.get_json(f"/analyze/coverage/{task['task_id']}") + ) + + def test_coverage_sample_sizes(self): + result = self.analyze(self.request(sample_size=SampleSizeOptions())) + points = from_geojson(result.points.model_dump_json()) + observed = points[points.samples > 0] + self.assertTrue(observed.sample_size_median.notna().all()) + self.assertTrue((observed.sample_size_min <= observed.sample_size_median).all()) + self.assertTrue(points[points.samples == 0].sample_size_median.isna().all()) + self.assertIn("sample_size_median", result.cells.features[0].properties) + summary = result.summary.sample_size + self.assertIsNone(summary.max_sample_size) + self.assertEqual(summary.sized, summary.observations) + self.assertGreater(summary.sized, 0) + self.assertIsNone(summary.meeting) + # without the option, no sizes + plain = self.analyze(self.request()) + self.assertIsNone(plain.summary.sample_size) + self.assertNotIn("sample_size_median", plain.points.features[0].properties) + + def test_coverage_max_sample_size(self): + request = self.request(sample_size=SampleSizeOptions(max_sample_size=1500)) + result = self.analyze(request) + # the observations at most 1.5 km, aggregated and reduced + points = generate_points_uniform_spacing(1000e3) + members = request.get_members() + sized = size_observations( + collect_observations(points, members, START, END, instrument_index=None), + members, + ) + kept = sized[sized.sample_size <= 1500].drop(columns="sample_size") + expected = reduce_observations(aggregate_observations(kept), targets=points) + actual = from_geojson(result.points.model_dump_json()) + merged = actual.merge(expected, on="target_hash", suffixes=("", "_expected")) + self.assertEqual(len(merged), len(points)) + self.assertTrue((merged.samples == merged.samples_expected).all()) + summary = result.summary.sample_size + self.assertEqual(summary.meeting, int((sized.sample_size <= 1500).sum())) + self.assertLess(summary.meeting, summary.sized) + self.assertEqual(int(actual.observations_meeting.sum()), summary.meeting) + + def test_coincidence_max_sample_size(self): + satellites = [ + satellite("A"), + satellite("B").model_copy( + update={ + "orbit": ORBIT.model_copy(update={"equator_crossing_time": "13:40"}) + } + ), + ] + base = { + "satellites": satellites, + "start": START, + "end": END, + "points": PointGenerator(method="equally_spaced", distance=1000e3), + "cells": CellGenerator(method="equally_spaced", distance=5000e3), + "max_time_difference": timedelta(hours=1), + } + counts = [] + for sample_size in (None, SampleSizeOptions(max_sample_size=1500)): + request = CoincidenceAnalysisRequest(**base, sample_size=sample_size) + task = self.run_analysis("/analyze/coincidence", request) + result = CoincidenceAnalysisResult.model_validate( + self.get_json(f"/analyze/coincidence/{task['task_id']}") + ) + counts.append(sum(f.properties["samples"] for f in result.points.features)) + # coincidences have no sample size statistics + self.assertIsNone(result.summary.sample_size) + self.assertGreater(counts[0], 0) + self.assertLess(counts[1], counts[0]) + + def test_requirement_needs_pixels(self): + simple = satellite(instruments=[Instrument(name="S", field_of_regard=100)]) + body = self.request(satellites=[simple]).model_dump(mode="json") + # sizes without a requirement are allowed (and undefined) + self.assertEqual( + self.client.post( + "/analyze/coverage", json=body | {"sampleSize": {}} + ).status_code, + 200, + ) + for sample_size in ({"maxSampleSize": 1000}, {"maxSampleSize": 0}): + response = self.client.post( + "/analyze/coverage", json=body | {"sampleSize": sample_size} + ) + self.assertEqual(response.status_code, 422, sample_size) + self.assertIn( + "instruments with pixels", + self.client.post( + "/analyze/coverage", json=body | {"sampleSize": {"maxSampleSize": 1000}} + ).text, + ) From 9983ae313f10fc384f8e6f6110a87cc2f5ec74a2 Mon Sep 17 00:00:00 2001 From: Paul Grogan Date: Tue, 24 Nov 2026 23:23:21 -0700 Subject: [PATCH 2/3] Analyze the swath coverage of a region A region analysis (/analyze/region) samples the footprints of instruments every step over the analysis period, clipped to a region (a polygon, known shape, country, or the globe), in parallel by windows of time with every member satellite (tatc.analysis.collect_footprints). It gives the swath segments over the region, the share of its area observed over time (measured in an equal-area projection of the WGS 84 ellipsoid), and its observations (collect_region_observations) with their revisit and longest gap. With coincidence, each window also pairs its footprints with those up to max_time_difference after them (find_coincident_ground_track), between member satellites or between satellites and constellations, giving the areas observed in common over time and the time between paired footprints. Window boundaries do not change the results (tested against a direct computation). The GUI adds the analysis with its options, CZML of swaths and common areas, a table of observations, a summary, and the comparison of saved runs; saved runs accept region. --- README.md | 3 + docs/api.rst | 19 + src/static/analysis.js | 70 +++- src/static/index.html | 43 +++ src/static/library.js | 26 ++ src/static/summary.js | 48 +++ src/tatc_app/analysis/summary.py | 59 +++ src/tatc_app/cesium/czml.py | 51 +++ src/tatc_app/library/router.py | 5 +- src/tatc_app/library/schemas.py | 1 + src/tatc_app/main.py | 2 + src/tatc_app/region/__init__.py | 0 src/tatc_app/region/router.py | 154 ++++++++ src/tatc_app/region/schemas.py | 225 +++++++++++ src/tatc_app/region/tasks.py | 623 +++++++++++++++++++++++++++++++ src/tatc_app/worker.py | 1 + tests/test_region.py | 208 +++++++++++ 17 files changed, 1536 insertions(+), 2 deletions(-) create mode 100644 src/tatc_app/region/__init__.py create mode 100644 src/tatc_app/region/router.py create mode 100644 src/tatc_app/region/schemas.py create mode 100644 src/tatc_app/region/tasks.py create mode 100644 tests/test_region.py diff --git a/README.md b/README.md index eb93f8f..30c8767 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,9 @@ tasks and visualized with animated results (CZML) in the GUI: difference, as for cross-calibration matchups, with the statistics of coverage of those periods (and optionally their sampling sufficiency). * Ground track swaths (`/analyze/swaths`): instrument swaths that accumulate over time. + * Swath coverage of a region (`/analyze/region`): swaths over a region, the share of its area + observed over time, its observations and revisit, and optionally coincident swaths: the + areas two satellites observe in common within a time difference. * Data latency (`/analyze/latency`): latency to downlink observations at ground stations. * Point access (`/analyze/overflight`): access windows of satellites to target points. diff --git a/docs/api.rst b/docs/api.rst index 52e1d7a..4897c67 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -88,6 +88,25 @@ of a coverage analysis, of coincidences rather than observations. .. autopydantic_model:: tatc_app.coincidence.schemas.CoincidenceAnalysisResult +Swath Coverage of a Region +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A region analysis samples the footprints of instruments every ``step`` over +the analysis period, clipped to the region: the share of its area observed +over time (measured in an equal-area projection of the WGS 84 ellipsoid), its +observations (when any part of it is observed), and, with ``coincidence``, the +areas that two platforms observe in common within ``max_time_difference``. + +.. autopydantic_model:: tatc_app.region.schemas.RegionAnalysisRequest + +.. autopydantic_model:: tatc_app.region.schemas.SwathCoincidenceOptions + +.. autopydantic_model:: tatc_app.region.schemas.RegionAnalysisResult + +.. autopydantic_model:: tatc_app.analysis.summary.RegionSummary + +.. autopydantic_model:: tatc_app.analysis.summary.SwathCoincidenceSummary + Data Latency ^^^^^^^^^^^^ diff --git a/src/static/analysis.js b/src/static/analysis.js index faf9918..7170a1d 100644 --- a/src/static/analysis.js +++ b/src/static/analysis.js @@ -34,6 +34,14 @@ const ANALYSES = { targetLayer: false, endpoint: "/analyze/swaths" }, + region: { + label: "Swath Coverage of a Region", + description: "Swaths of the checked instruments over the region, sampled every step: the share of its area observed over time, " + + "its observations and revisit, and optionally the areas several satellites observe in common within a time difference.", + region: true, + targetLayer: false, + endpoint: "/analyze/region" + }, latency: { label: "Data Latency (Ground Stations)", description: "Latency from the observation of each point to its downlink at a ground station. " + @@ -470,6 +478,33 @@ function getAnalysisPayload(type, base) { sufficiency: sufficiency, sample_size: sampleSize }); + } else if (type == "region") { + const step = Number($("#region-step").val()); + const segment = Number($("#region-segment").val()); + if (!(step > 0) || !(segment > 0)) { + $("#analysis-error").text("The step and segment must be positive.").show(); + return null; + } + let coincidence = null; + if ($("#region-coincidence-enabled").is(":checked")) { + const minutes = Number($("#region-coincidence-difference").val()); + if (!(minutes >= 0)) { + $("#analysis-error").text("The maximum time difference must not be negative.").show(); + return null; + } + coincidence = { + max_time_difference: minutes * 60, + platforms: $("#region-coincidence-platforms").val() + }; + } + // footprints are sampled every step over the analysis period + return _.assign(_.omit(base, "display"), { + region: getRegionMask(), + instrument_index: null, + step: step, + segment: segment * 60, + coincidence: coincidence + }); } else if (type == "swaths") { // swaths animate over the analysis period return _.assign(_.omit(base, "display"), { @@ -697,6 +732,36 @@ function showAnalysisData() { }) }] }); + } else if (type == "region") { + const epoch = new Date(analysisResult.payload.start).getTime(); + const iso = function(seconds) { return new Date(epoch + seconds * 1000).toISOString(); }; + showResultsTable({ + title: "Observations of the Region", + columns: [ + { title: "Satellites", key: "satellite" }, + { title: "Instruments", key: "instrument" }, + { title: "Start (UTC)", key: "start_utc" }, + { title: "End (UTC)", key: "end_utc" }, + { title: "Duration (min)", key: "duration_min", format: number2 } + ], + rows: _.map(result.observations, function(o) { + return { + satellite: o.satellite, + instrument: o.instrument, + start_utc: iso(o.start), + end_utc: iso(o.end), + duration_min: (o.end - o.start) / 60 + }; + }), + filename: "region-observations", + note: "Periods when any part of the region is observed (overlapping observations merged). Click a row to jump the animation to it.", + summary: function(container) { renderRegionSummary(container, result.summary); }, + onRowClick: function(row) { + viewer.clock.currentTime = Cesium.JulianDate.fromIso8601(row.start_utc); + viewer.clock.shouldAnimate = true; + $("#results-dialog").modal("hide"); + } + }); } else if (type == "swaths") { showResultsTable({ title: "Swath Segments", @@ -796,7 +861,7 @@ function changeAnalysisType() { $(".analysis-panel[data-analysis~='" + type + "']").addClass("shown"); $(".region-panel").toggle(ANALYSES[type].region); $("#analysis-description").text(ANALYSES[type].description); - $(".animate-control").toggle(type != "swaths"); + $(".animate-control").toggle(type != "swaths" && type != "region"); adjustDurationForType(type); limitAnimation(); // picking (region vertices or target points) applies to one analysis type @@ -853,6 +918,9 @@ $(document).ready(function() { } limitAnimation(); }); + $("#region-coincidence-enabled").change(function() { + $("#region-coincidence-options").toggle($(this).is(":checked")); + }); $("#sample-size-enabled").change(function() { $("#sample-size-options").toggle($(this).is(":checked")); }); diff --git a/src/static/index.html b/src/static/index.html index 55d3018..2d3668c 100644 --- a/src/static/index.html +++ b/src/static/index.html @@ -329,6 +329,49 @@
Orbit Preview
+ +
+
+ +
+ +
s
+
+
+
+ +
+ +
min
+
+
Swaths over the region accumulate as each segment completes. The animation spans the analysis duration.
+
+
+
+ + +
+
+ +
+
diff --git a/src/static/library.js b/src/static/library.js index 860cbc9..4406580 100644 --- a/src/static/library.js +++ b/src/static/library.js @@ -197,6 +197,20 @@ function coverageRunMetrics(terms) { const RUN_METRICS = { coverage: coverageRunMetrics(COVERAGE_TERMS.coverage), coincidence: coverageRunMetrics(COVERAGE_TERMS.coincidence), + region: { + headline: { label: "Area observed", value: function(s) { return s.covered; }, kind: "share" }, + rows: [ + { label: "Area observed", value: function(s) { return s.covered; }, kind: "share" }, + { label: "Observations of the region", value: function(s) { return s.observations; }, kind: "count" }, + { label: "Mean revisit time", value: function(s) { return s.revisit && s.revisit.mean; }, kind: "duration" }, + { label: "90th percentile revisit time", value: function(s) { return s.revisit && s.revisit.p90; }, kind: "duration" }, + { label: "Longest gap", value: function(s) { return s.max_gap; }, kind: "duration" }, + { label: "Area in common", optional: true, value: function(s) { return s.coincidence && s.coincidence.common; }, kind: "share" }, + { label: "Coincident footprints", optional: true, value: function(s) { return s.coincidence && s.coincidence.pairs; }, kind: "count" }, + { label: "Region area (km²)", value: function(s) { return s.area; }, kind: "number" }, + { label: "Analysis period", value: function(s) { return _.last(s.coverage.times); }, kind: "duration" } + ] + }, latency: { headline: { label: "Region downlinked", value: function(s) { return s.downlinked; }, kind: "share" }, rows: [ @@ -383,6 +397,18 @@ function setAnalysisInputs(type, request) { setCoincidenceInputs(request); setSufficiencyInputs(request.sufficiency); setSampleSizeInputs(request.sample_size); + } else if (type == "region") { + $("#region-step").val(request.step); + if (request.segment) { + $("#region-segment").val(request.segment / 60); + } + const coincidence = request.coincidence; + $("#region-coincidence-enabled").prop("checked", Boolean(coincidence)); + $("#region-coincidence-options").toggle(Boolean(coincidence)); + if (coincidence) { + $("#region-coincidence-difference").val(Number(((coincidence.max_time_difference || 0) / 60).toFixed(6))); + $("#region-coincidence-platforms").val(coincidence.platforms || "members"); + } } else if (type == "swaths") { $("#swaths-step").val(request.step); if (request.segment) { diff --git a/src/static/summary.js b/src/static/summary.js index 15fdb5d..6b57943 100644 --- a/src/static/summary.js +++ b/src/static/summary.js @@ -27,6 +27,17 @@ const COVERAGE_TERMS = { curveColumn: "Observed", samples: "Observations" }, + // (the area curves of the swath coverage of a region) + region: { + curveTitle: "Share of the region's area observed so far", + curveSubtitle: "Within a swath at least once", + curveColumn: "Observed" + }, + regionCommon: { + curveTitle: "Share of the region's area observed in common so far", + curveSubtitle: "Within coincident swaths of two satellites at least once", + curveColumn: "In common" + }, coincidence: { observed: "Region with coincidences", twice: "with at least two", @@ -515,6 +526,43 @@ function renderCoverageSummary(container, summary, terms) { root.append($("

").addClass("small text-muted mb-0").text(weightingNote(summary))); } +// Renders the summary of the swath coverage of a region in a container. +function renderRegionSummary(container, summary) { + const root = $("

").addClass("summary").appendTo($(container).empty()); + const tiles = $("
").addClass("summary-tiles").appendTo(root); + tiles.append(statTile("Area observed", formatShare(summary.covered), + "of " + formatValue(summary.area) + " km²")); + if (summary.revisit) { + const unit = durationUnit(summary.revisit.p90); + tiles.append(statTile("Mean revisit time", formatDuration(summary.revisit.mean, unit), + distributionDetail(summary.revisit, unit))); + } else { + tiles.append(statTile("Mean revisit time", "–", + summary.observations ? "observed once" : "the region is not observed")); + } + tiles.append(statTile("Observations", summary.observations.toLocaleString(), + summary.access ? "mean duration " + formatDuration(summary.access.mean) : "of any part of the region")); + tiles.append(statTile("Longest gap", formatDuration(summary.max_gap), + "without an observation, including the ends of the period")); + const charts = $("
").addClass("summary-charts").appendTo(root); + charts.append(coverageChart(summary.coverage, COVERAGE_TERMS.region)); + const coincidence = summary.coincidence; + if (coincidence) { + root.append($("
").addClass("summary-section-title").text("Coincident swaths")); + const common = $("
").addClass("summary-tiles").appendTo(root); + common.append(statTile("Area in common", formatShare(coincidence.common), + "observed by two satellites within the time difference")); + common.append(statTile("Coincident footprints", coincidence.pairs.toLocaleString(), + coincidence.time_difference + ? "median " + formatDuration(coincidence.time_difference.median) + " apart" + : "pairs of overlapping footprints")); + $("
").addClass("summary-charts").appendTo(root).append( + coverageChart(coincidence.coverage, COVERAGE_TERMS.regionCommon)); + } + root.append($("

").addClass("small text-muted mb-0").text( + "Areas are of the swaths' footprints sampled every step, measured on the WGS 84 ellipsoid.")); +} + // Formats a length (meters) in kilometers. function formatKilometers(meters) { return formatValue(meters / 1000) + " km"; diff --git a/src/tatc_app/analysis/summary.py b/src/tatc_app/analysis/summary.py index 4e8b5e7..245063d 100644 --- a/src/tatc_app/analysis/summary.py +++ b/src/tatc_app/analysis/summary.py @@ -263,6 +263,65 @@ class LatencySummary(BaseModel): ) +class SwathCoincidenceSummary(BaseModel): + """ + Summary of the coincident swaths of a region: the areas that two + platforms observe in common, within a time difference. + """ + + pairs: int = Field(..., description="Number of pairs of coincident footprints.") + common: float = Field( + ..., + description="Share of the region's area observed in common by two " + "platforms (at least once).", + ) + coverage: CoverageCurve = Field( + ..., + description="Share of the region's area observed in common so far, over " + "time (by the later footprint of each pair).", + ) + time_difference: Optional[Distribution] = Field( + None, + description="Distribution of the time (seconds) between the footprints " + "of each pair.", + ) + + +class RegionSummary(BaseModel): + """ + Summary of the swath coverage of a region. + """ + + area: float = Field(..., description="Area of the region (square kilometers).") + covered: float = Field( + ..., description="Share of the region's area observed at least once." + ) + coverage: CoverageCurve = Field( + ..., description="Share of the region's area observed so far, over time." + ) + observations: int = Field( + ..., + description="Number of observations of the region (periods when any " + "part of it is observed, overlapping observations merged).", + ) + access: Optional[Distribution] = Field( + None, description="Distribution of the duration (seconds) of observations." + ) + revisit: Optional[Distribution] = Field( + None, + description="Distribution of the time (seconds) from the end of one " + "observation to the start of the next.", + ) + max_gap: float = Field( + ..., + description="Longest time (seconds) without an observation, including " + "from the start and to the end of the period.", + ) + coincidence: Optional[SwathCoincidenceSummary] = Field( + None, description="Summary of coincident swaths, if found." + ) + + def point_weights(points: pd.DataFrame, weighting: Weighting) -> np.ndarray: """ Gets the weights of points (with a point `geometry`). diff --git a/src/tatc_app/cesium/czml.py b/src/tatc_app/cesium/czml.py index 9300caa..190b720 100644 --- a/src/tatc_app/cesium/czml.py +++ b/src/tatc_app/cesium/czml.py @@ -825,3 +825,54 @@ def swath_packets( } ) return packets + + +# the color of the areas observed in common by coincident swaths +COINCIDENT_COLOR = "#ffd166" + + +def coincident_packets( + pairs: gpd.GeoDataFrame, + end: datetime, + *, + tolerance: float = 0.01, + alpha: int = 200, +) -> List[dict]: + """ + Builds packets for the areas that pairs of satellites observe in common + (coincident swaths), which accumulate over time: each appears at its end + (the later footprint of its pairs) and remains until the end of the + analysis, outlined in one highlight color over the swaths. + + Args: + pairs (geopandas.GeoDataFrame): The common areas, with columns + `satellite_1`, `satellite_2`, `end`, and `geometry`. + end (datetime.datetime): The end of the analysis. + tolerance (float): The tolerance (degrees) to simplify geometries. + alpha (int): The fill opacity (0-255). + + Returns: + List[dict]: The CZML packets. + """ + packets = [] + for i, row in enumerate(pairs.itertuples()): + polygons = polygon_parts( + row.geometry.simplify(tolerance, preserve_topology=True) + ) + for j, (polygon, arc_type) in enumerate(display_polygons(polygons)): + packets.append( + { + "id": f"coincident/{i}/{j}", + "name": f"{row.satellite_1} and {row.satellite_2} in common", + "availability": interval(row.end.to_pydatetime(), end), + "polygon": { + **_polygon_positions(polygon), + "arcType": arc_type, + "material": _solid(COINCIDENT_COLOR, alpha), + "height": 0, + "outline": True, + "outlineColor": {"rgba": [0, 0, 0, 255]}, + }, + } + ) + return packets diff --git a/src/tatc_app/library/router.py b/src/tatc_app/library/router.py index 6b5d56c..3d195f5 100644 --- a/src/tatc_app/library/router.py +++ b/src/tatc_app/library/router.py @@ -13,13 +13,14 @@ from pydantic import ValidationError from .. import limits -from ..analysis.summary import CoverageSummary, LatencySummary +from ..analysis.summary import CoverageSummary, LatencySummary, RegionSummary from ..auth import User, current_user from ..celery.utils import get_task_result from ..coincidence.schemas import CoincidenceAnalysisRequest from ..coverage.schemas import CoverageAnalysisRequest from ..latency.schemas import LatencyAnalysisRequest from ..overflight.schemas import OverflightAnalysisRequest +from ..region.schemas import RegionAnalysisRequest from ..tracking.schemas import SwathAnalysisRequest from .database import library from .schemas import ( @@ -45,6 +46,7 @@ AnalysisType.swaths: SwathAnalysisRequest, AnalysisType.latency: LatencyAnalysisRequest, AnalysisType.access: OverflightAnalysisRequest, + AnalysisType.region: RegionAnalysisRequest, } # the summary schema of each type of analysis with a summary @@ -52,6 +54,7 @@ AnalysisType.coverage: CoverageSummary, AnalysisType.coincidence: CoverageSummary, AnalysisType.latency: LatencySummary, + AnalysisType.region: RegionSummary, } diff --git a/src/tatc_app/library/schemas.py b/src/tatc_app/library/schemas.py index c10709b..74c1a48 100644 --- a/src/tatc_app/library/schemas.py +++ b/src/tatc_app/library/schemas.py @@ -30,6 +30,7 @@ class AnalysisType(str, Enum): swaths = "swaths" latency = "latency" access = "access" + region = "region" def check_size(*values: Any) -> None: diff --git a/src/tatc_app/main.py b/src/tatc_app/main.py index 6d7a498..e2fb6a7 100644 --- a/src/tatc_app/main.py +++ b/src/tatc_app/main.py @@ -25,6 +25,7 @@ from tatc_app.latency.router import router as latency_router from tatc_app.library.router import designs_router, runs_router from tatc_app.overflight.router import router as overflight_router +from tatc_app.region.router import router as region_router from tatc_app.system_catalog.router import router as system_catalog_router from tatc_app.tracking.router import router as tracking_router from tatc_app.validation.router import router as validation_router @@ -70,6 +71,7 @@ (coverage_router, "/analyze"), (coincidence_router, "/analyze"), (latency_router, "/analyze"), + (region_router, "/analyze"), (designs_router, "/designs"), (runs_router, "/runs"), ]: diff --git a/src/tatc_app/region/__init__.py b/src/tatc_app/region/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tatc_app/region/router.py b/src/tatc_app/region/router.py new file mode 100644 index 0000000..33a6916 --- /dev/null +++ b/src/tatc_app/region/router.py @@ -0,0 +1,154 @@ +""" +Router specifications for analyses of the swath coverage of a region. + +@author: Paul T. Grogan +""" + +import json +import logging +from typing import List +from uuid import UUID + +from fastapi import APIRouter, Depends +from shapely.geometry import mapping + +from ..analysis.endpoints import ( + enqueue_analysis, + get_analysis_result, + serialize_members, +) +from ..celery.quota import TaskSlot, analysis_slot +from ..celery.schemas import CeleryTask +from ..cesium.czml import animation_packets, coincident_packets, swath_packets +from ..utils.serialization import MSGPACK_RESPONSES, from_geojson +from .schemas import RegionAnalysisRequest, RegionAnalysisResult +from .tasks import WINDOW_STEPS, collect_region_window_task, combine_region_task + +logger = logging.getLogger(__name__) + +router = APIRouter() + + +@router.post("/region", response_model=CeleryTask) +def enqueue_region_analysis( + request: RegionAnalysisRequest, slot: TaskSlot = Depends(analysis_slot) +): + """ + Endpoint to enqueue a task to analyze the swath coverage of a region, in + parallel by windows of time (each with all member satellites, so that + their footprints may coincide). + + Args: + request (RegionAnalysisRequest): User request. + slot (TaskSlot): Slot reserved for the user's analysis. + + Returns: + CeleryTask: Queued task. + """ + members = request.get_members() + serialized = serialize_members(members) + region = json.dumps(mapping(request.get_region())) + times = request.get_display_times() + difference = ( + None if request.coincidence is None else request.coincidence.max_time_difference + ) + tasks = [] + for first in range(0, len(times), WINDOW_STEPS): + own = times[first : first + WINDOW_STEPS] + # the window ends at the next window's first time (or the end) + window_end = ( + times[first + WINDOW_STEPS] + if first + WINDOW_STEPS < len(times) + else request.end + ) + # with the times after it within the maximum time difference + window = ( + own + if difference is None + else times[(times >= own[0]) & (times <= own[-1] + difference)] + ) + tasks.append( + collect_region_window_task.s( + serialized, + region, + [time.isoformat() for time in window], + window_end.isoformat(), + request.start.isoformat(), + request.end.isoformat(), + request.step.total_seconds(), + request.segment.total_seconds(), + request.instrument_index, + None if difference is None else difference.total_seconds(), + request.get_platform_systems(), + ) + ) + return enqueue_analysis( + request, + members, + tasks, + combine_region_task.s( + region, + request.start.isoformat(), + request.end.isoformat(), + request.get_member_colors(), + request.get_member_systems(), + request.coincidence is not None, + ), + slot, + ) + + +def _get_region_result(task_id: UUID) -> RegionAnalysisResult: + return get_analysis_result(RegionAnalysisResult, task_id, "Region analysis", logger) + + +@router.get( + "/region/{task_id}", + response_model=RegionAnalysisResult, + response_model_exclude_none=True, + responses=MSGPACK_RESPONSES, +) +def retrieve_region_analysis(task_id: UUID): + """ + Endpoint to retrieve results of a completed region analysis task. + + Args: + task_id (UUID): Task unique identifier. + + Returns: + RegionAnalysisResult: Region analysis results. + """ + return _get_region_result(task_id) + + +@router.get("/region/{task_id}/czml", response_model=List[dict]) +def retrieve_region_analysis_czml(task_id: UUID): + """ + Endpoint to retrieve results of a completed region analysis task as a + CZML document, animating satellites, their footprints, their swath + segments over the region, and the areas observed in common (if found). + + Args: + task_id (UUID): Task unique identifier. + + Returns: + List[dict]: CZML packets. + """ + result = _get_region_result(task_id) + end = result.tracks.get_end() + swaths = from_geojson( + result.swaths.model_dump_json(), + datetimes=["start", "end"], + columns=["satellite", "instrument", "start", "end", "geometry"], + ) + packets = animation_packets("Region analysis", result) + swath_packets( + swaths, end, result.colors, tracks=result.tracks + ) + if result.coincident is not None: + pairs = from_geojson( + result.coincident.model_dump_json(), + datetimes=["start", "end"], + columns=["satellite_1", "satellite_2", "start", "end", "geometry"], + ) + packets += coincident_packets(pairs, end) + return packets diff --git a/src/tatc_app/region/schemas.py b/src/tatc_app/region/schemas.py new file mode 100644 index 0000000..66eec4b --- /dev/null +++ b/src/tatc_app/region/schemas.py @@ -0,0 +1,225 @@ +""" +Schema specifications for analyses of the swath coverage of a region. + +@author: Paul T. Grogan +""" + +from datetime import timedelta +from enum import Enum +from typing import Dict, List, Optional, Union + +import pandas as pd +from geojson_pydantic import FeatureCollection +from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator +from shapely.geometry import MultiPolygon, Polygon, box + +from ..analysis.schemas import MAX_DISPLAY_STEPS, AnalysisRequest, AnimatedResult +from ..analysis.summary import RegionSummary +from ..coincidence.schemas import CoincidencePlatforms +from ..generation.masks import resolve_mask +from ..generation.schemas import Mask, TimeGenerator +from ..satellites import validate_instrument_index +from ..utils.schemas import CamelModel + +# the region of a request without one: the globe +GLOBE = box(-180, -90, 180, 90) + + +def mask_spec(mask: Optional[Mask]) -> Optional[Union[dict, str]]: + """ + Gets the specification of a mask that `resolve_mask` resolves: a GeoJSON + geometry, a known shape or country code, or `None`. + """ + if mask is None: + return None + if isinstance(mask, BaseModel): + return mask.model_dump(mode="json") + if isinstance(mask, Enum): + return mask.value + return str(mask) + + +class SwathCoincidenceOptions(CamelModel): + """ + Options to find the coincident swaths of a region: the areas that the + footprints of two platforms observe in common, within a time difference. + """ + + max_time_difference: timedelta = Field( + timedelta(0), + description="Maximum time (seconds, or an ISO 8601 duration) between " + "footprints that coincide.", + examples=[600], + ) + platforms: CoincidencePlatforms = Field( + CoincidencePlatforms.members, + description="Distinct platforms: each member satellite (`members`), or " + "each satellite or constellation of the request (`systems`).", + ) + + @field_validator("max_time_difference") + @classmethod + def validate_max_time_difference(cls, value: timedelta) -> timedelta: + """ + Validates the maximum time difference is not negative. + """ + if value < timedelta(0): + raise ValueError("The maximum time difference must not be negative.") + return value + + +class RegionAnalysisRequest(AnalysisRequest): + """ + User request to analyze the swath coverage of a region: the footprints + of instruments sampled every `step` over the analysis period (so + `display` does not apply), clipped to the region, with the share of its + area observed over time, its observations (when any part of it is + observed), and optionally the areas that platforms observe in common. + """ + + region: Optional[Mask] = Field( + None, + description="The region: a polygon, a known shape, or a country code " + "(`null` for the globe).", + ) + instrument_index: Optional[int] = Field( + None, ge=0, description="Instrument index, or `null` for all instruments." + ) + step: timedelta = Field( + timedelta(seconds=60), + gt=timedelta(0), + description="Time step to sample orbit tracks and footprints.", + ) + segment: timedelta = Field( + timedelta(minutes=10), + gt=timedelta(0), + description="Duration of each displayed swath segment.", + ) + coincidence: Optional[SwathCoincidenceOptions] = Field( + None, + description="Options to also find coincident swaths (`null` to skip " "it).", + ) + # the region's geometry + _region: Optional[Union[Polygon, MultiPolygon]] = PrivateAttr(None) + + @model_validator(mode="after") + def validate_region(self) -> "RegionAnalysisRequest": + """ + Validates the region resolves to a polygon with an area. + """ + try: + region = resolve_mask(mask_spec(self.region)) + except (ValueError, KeyError) as exc: + raise ValueError(f"Invalid region: {exc}") from exc + region = GLOBE if region is None else region + if region.is_empty or region.area <= 0: + raise ValueError("Invalid region: it has no area.") + self._region = region + return self + + @model_validator(mode="after") + def validate_options(self) -> "RegionAnalysisRequest": + """ + Validates the instrument index, that `display` is not set (footprints + are sampled every `step`), and that coincident swaths have at least + two platforms. + """ + validate_instrument_index(self.satellites, self.instrument_index) + if self.display is not None: + raise ValueError( + "Invalid display: region analyses sample the whole analysis " + "period every `step`." + ) + if self.coincidence is not None: + systems = self.get_platform_systems() + count = ( + len(self.get_members()) + if systems is None + else len(set(systems.values())) + ) + if count < 2: + raise ValueError( + "Too few platforms: coincident swaths need at least two " + + ( + "member satellites." + if systems is None + else "satellites or constellations." + ) + ) + return self + + def get_region(self) -> Union[Polygon, MultiPolygon]: + """ + Gets the region's geometry (the globe, without a region). + """ + return self._region + + def get_display_times(self) -> pd.DatetimeIndex: + """ + Gets the times at which to sample orbit tracks and footprints. + + Returns: + pandas.DatetimeIndex: The times. + """ + return TimeGenerator(start=self.start, end=self.end, delta=self.step).to_index( + MAX_DISPLAY_STEPS + ) + + def get_platform_systems(self) -> Optional[Dict[str, str]]: + """ + Gets the platform of each member satellite, if coincident swaths are + between systems. + + Returns: + Optional[Dict[str, str]]: The satellite or constellation (its + index in `satellites`, as a string) of each analyzed member, + by name, or `None` if each member is a platform. + """ + if ( + self.coincidence is None + or self.coincidence.platforms != CoincidencePlatforms.systems + ): + return None + systems = self.get_member_systems() + return {member.name: str(systems[member.name]) for member in self.get_members()} + + +class RegionObservation(BaseModel): + """ + An observation of a region: a period when any part of it is observed + (overlapping observations by several satellites merged). + """ + + satellite: str = Field(..., description="Observing satellites, comma-separated.") + instrument: str = Field(..., description="Observing instruments, comma-separated.") + start: float = Field(..., description="Start (seconds since the analysis start).") + end: float = Field(..., description="End (seconds since the analysis start).") + + +class RegionAnalysisResult(AnimatedResult): + """ + Results of an analysis of the swath coverage of a region. + """ + + region: FeatureCollection = Field(..., description="The region.") + swaths: FeatureCollection = Field( + ..., + description="Swath segments clipped to the region, with properties " + "`satellite`, `instrument`, `start`, and `end`.", + ) + coincident: Optional[FeatureCollection] = Field( + None, + description="Areas of the region observed in common by two platforms " + "(dissolved by pair and segment), with properties `satellite_1`, " + "`satellite_2`, `start` (the earlier time), and `end` (the later), if " + "coincident swaths were found.", + ) + observations: List[RegionObservation] = Field( + [], description="Observations of the region, in order of time." + ) + systems: Dict[str, int] = Field( + {}, + description="Index of the requested satellite or constellation of " + "each member satellite, by name.", + ) + summary: RegionSummary = Field(..., description="Summary of the region's coverage.") diff --git a/src/tatc_app/region/tasks.py b/src/tatc_app/region/tasks.py new file mode 100644 index 0000000..3ebe2bf --- /dev/null +++ b/src/tatc_app/region/tasks.py @@ -0,0 +1,623 @@ +""" +Task specifications for analyses of the swath coverage of a region. + +The analysis period is split into windows of times, analyzed in parallel: +each collects the footprints of every member satellite at its times, +clipped to the region (and those of the following `max_time_difference`, +to pair them with coincident footprints), and the observations of the +region. The combining task merges the swath segments of the windows, the +areas observed by the times of a coverage curve, and the observations. + +@author: Paul T. Grogan +""" + +import json +import os +from datetime import datetime, timedelta +from typing import Dict, List, Optional, Union + +import geopandas as gpd +import numpy as np +import pandas as pd +import shapely +from pyproj import Transformer +from shapely.geometry import MultiPolygon, Polygon, mapping, shape +from shapely.ops import transform +from tatc.analysis import ( + aggregate_observations, + collect_footprints, + collect_region_observations, + find_coincident_ground_track, +) + +from ..analysis.summary import ( + COVERAGE_SAMPLES, + CoverageCurve, + RegionSummary, + SwathCoincidenceSummary, + summarize_values, +) +from ..analysis.tasks import combine_animation, deserialize_members, tag, untag +from ..utils.serialization import concat, empty_frame, from_geojson, to_geojson +from ..worker import app +from .schemas import RegionAnalysisResult, RegionObservation + +# number of time steps of each window analyzed in parallel +WINDOW_STEPS = int(os.getenv("TATC_REGION_WINDOW_STEPS", "1440")) + +# an equal-area projection (cylindrical, on the WGS 84 ellipsoid) to measure +# areas of geometries in longitude and latitude, including whole bands of +# latitude and the globe +_TO_EQUAL_AREA = Transformer.from_crs( + "EPSG:4326", + "+proj=cea +lon_0=0 +lat_ts=0 +datum=WGS84 +units=m", + always_xy=True, +) + +SWATH_COLUMNS = ["satellite", "instrument", "segment", "start", "end", "geometry"] +PAIR_COLUMNS = ["satellite_1", "satellite_2", "segment", "start", "end", "geometry"] +PIECE_COLUMNS = ["bin", "geometry"] +OBSERVATION_COLUMNS = [ + "target_hash", + "satellite", + "instrument", + "start", + "epoch", + "end", + "geometry", +] + + +def area_km2(geometry) -> float: + """ + Gets the area (square kilometers) of a geometry in longitude and + latitude (zero if empty or `None`). + """ + if geometry is None or geometry.is_empty: + return 0.0 + return transform(_TO_EQUAL_AREA.transform, geometry).area / 1e6 + + +def curve_seconds(start: datetime, end: datetime) -> np.ndarray: + """ + Gets the times (seconds since the start) of a coverage curve. + """ + return np.linspace(0, (end - start).total_seconds(), COVERAGE_SAMPLES + 1) + + +def _seconds(times: pd.Series, start: datetime) -> np.ndarray: + """ + Converts times to seconds since a start. + """ + return ( + (pd.to_datetime(times, utc=True) - pd.Timestamp(start).tz_convert("UTC")) + .dt.total_seconds() + .to_numpy(dtype=float) + ) + + +def _dissolve_pieces( + frame: gpd.GeoDataFrame, times: pd.Series, start: datetime, end: datetime +) -> gpd.GeoDataFrame: + """ + Dissolves footprints (or overlaps) into one piece for each time of a + coverage curve: the first curve time at or after its time. + """ + if frame.empty: + return empty_frame(PIECE_COLUMNS) + bins = np.searchsorted(curve_seconds(start, end), _seconds(times, start), "left") + pieces = gpd.GeoDataFrame( + {"bin": np.minimum(bins, COVERAGE_SAMPLES)}, + geometry=frame.geometry.to_numpy(), + crs="EPSG:4326", + ) + return pieces.dissolve(by="bin", as_index=False)[PIECE_COLUMNS] + + +def _segment(times: pd.Series, start: datetime, segment: timedelta) -> np.ndarray: + """ + Gets the display segment of times (samples on a boundary belong to the + preceding segment). + """ + elapsed = pd.to_datetime(times, utc=True) - pd.Timestamp(start).tz_convert("UTC") + return ( + ((elapsed - pd.Timedelta(1, "ns")) // pd.Timedelta(segment)) + .clip(lower=0) + .astype(int) + .to_numpy() + ) + + +def analyze_window( # pylint: disable=too-many-arguments,too-many-locals + members: list, + region: Union[Polygon, MultiPolygon], + times: pd.DatetimeIndex, + window_end: datetime, + start: datetime, + end: datetime, + step: timedelta, + segment: timedelta, + instrument_index: Optional[int] = None, + max_time_difference: Optional[timedelta] = None, + systems: Optional[Dict[str, str]] = None, +) -> Dict[str, pd.DataFrame]: + """ + Analyzes a window of times: the footprints of the members at the times + before the window's end (its own times), clipped to the region, as swath + segments and pieces of the area observed by each time of the coverage + curve; the observations of the region in the window; and, with a maximum + time difference, the coincident footprints whose earlier time is the + window's own (paired with footprints up to that difference after it). + + Args: + members (list): The member satellites. + region (Union[Polygon, MultiPolygon]): The region. + times (pandas.DatetimeIndex): The times of the window: its own, and + those of the following maximum time difference. + window_end (datetime.datetime): The end of the window (exclusive, + unless it is the end of the analysis). + start (datetime.datetime): The start of the analysis period. + end (datetime.datetime): The end of the analysis period. + step (datetime.timedelta): The time step (over which footprints sweep). + segment (datetime.timedelta): The duration of each swath segment. + instrument_index (Optional[int]): The instrument index, or `None` for all. + max_time_difference (Optional[datetime.timedelta]): The maximum time + difference of coincident footprints, or `None` not to find them. + systems (Optional[Dict[str, str]]): The platform of each member, by + name, if coincident footprints are between systems. + + Returns: + Dict[str, pandas.DataFrame]: the `swaths`, `area` pieces, + `observations`, and (with a maximum time difference) coincident + `pairs` (dissolved), `common` area pieces, and `differences` of + the window. + """ + last = pd.Timestamp(window_end) >= pd.Timestamp(end) + own_times = times[(times <= window_end) if last else (times < window_end)] + footprints = collect_footprints( + members, + list(times), + instrument_index=instrument_index, + mask=region, + time_step=step, + ) + if not footprints.empty: + footprints = footprints[ + footprints.valid_obs & ~footprints.geometry.is_empty + ].reset_index(drop=True) + own = ( + footprints[footprints.time.isin(own_times)] + if not footprints.empty + else footprints + ) + result = { + "swaths": _swath_segments(own, start, end, step, segment), + "area": _dissolve_pieces(own, own.get("time"), start, end), + "observations": _region_observations( + region, members, own_times, step, end, instrument_index + ), + } + if max_time_difference is not None: + pairs = _coincident_pairs(footprints, own_times, max_time_difference, systems) + result["pairs"] = _pair_segments(pairs, start, segment) + result["common"] = _dissolve_pieces(pairs, pairs.get("time_2"), start, end) + result["differences"] = pd.DataFrame( + { + "seconds": ( + np.abs(pd.to_timedelta(pairs["time_difference"]).dt.total_seconds()) + if not pairs.empty + else [] + ) + } + ) + return result + + +def _swath_segments( + footprints: gpd.GeoDataFrame, + start: datetime, + end: datetime, + step: timedelta, + segment: timedelta, +) -> gpd.GeoDataFrame: + """ + Dissolves footprints into swath segments of each instrument of each + satellite (see `tracking.tasks.compute_swaths`). + """ + if footprints.empty: + return empty_frame(SWATH_COLUMNS) + track = footprints.assign( + segment=_segment(footprints.time, start, segment), + start=footprints.time - step / 2, + end=footprints.time + step / 2, + ) + swaths = track.dissolve( + by=["satellite", "instrument", "segment"], + aggfunc={"start": "min", "end": "max"}, + as_index=False, + ) + swaths["start"] = swaths["start"].clip(lower=pd.Timestamp(start)) + swaths["end"] = swaths["end"].clip(upper=pd.Timestamp(end)) + return swaths[SWATH_COLUMNS] + + +def _region_observations( # pylint: disable=too-many-arguments + region: Union[Polygon, MultiPolygon], + members: list, + own_times: pd.DatetimeIndex, + step: timedelta, + end: datetime, + instrument_index: Optional[int], +) -> gpd.GeoDataFrame: + """ + Collects the observations of the region by members over the span of a + window's own times, to the next window's first time (a step after its + last, or the end of the analysis), with the region's representative + point as geometry (its swaths are not needed, and observations split + between windows are merged when aggregated). + """ + if len(own_times) == 0: + return empty_frame(OBSERVATION_COLUMNS) + window_start = own_times[0].to_pydatetime() + window_end = min(own_times[-1].to_pydatetime() + step, end) + if window_end <= window_start: + return empty_frame(OBSERVATION_COLUMNS) + observations = collect_region_observations( + region, members, window_start, window_end, instrument_index + ) + if observations.empty: + return empty_frame(OBSERVATION_COLUMNS) + observations = observations.set_geometry( + [region.representative_point()] * len(observations), crs="EPSG:4326" + ) + return observations[OBSERVATION_COLUMNS] + + +def _coincident_pairs( + footprints: gpd.GeoDataFrame, + own_times: pd.DatetimeIndex, + max_time_difference: timedelta, + systems: Optional[Dict[str, str]], +) -> gpd.GeoDataFrame: + """ + Finds the pairs of coincident footprints whose earlier time is one of a + window's own times, between systems if given. + """ + empty = gpd.GeoDataFrame( + { + "time_1": pd.Series([], dtype="datetime64[ns, UTC]"), + "time_2": pd.Series([], dtype="datetime64[ns, UTC]"), + "satellite_1": [], + "satellite_2": [], + "time_difference": pd.Series([], dtype="timedelta64[ns]"), + }, + geometry=[], + crs="EPSG:4326", + ) + if footprints.empty: + return empty + pairs = find_coincident_ground_track( + footprints, max_time_difference=max_time_difference + ) + if pairs.empty: + return empty + pairs = pairs[pairs.time_1.isin(own_times)] + if systems is not None: + pairs = pairs[ + pairs.satellite_1.map(systems).to_numpy() + != pairs.satellite_2.map(systems).to_numpy() + ] + return pairs.reset_index(drop=True) + + +def _pair_segments( + pairs: gpd.GeoDataFrame, start: datetime, segment: timedelta +) -> gpd.GeoDataFrame: + """ + Dissolves coincident footprints into segments of each pair of + satellites (by the later time of each pair), from the earliest to the + latest time of their footprints. + """ + if pairs.empty: + return empty_frame(PAIR_COLUMNS) + names = np.sort(pairs[["satellite_1", "satellite_2"]].to_numpy(dtype=str), axis=1) + frame = gpd.GeoDataFrame( + { + "satellite_1": names[:, 0], + "satellite_2": names[:, 1], + "segment": _segment(pairs.time_2, start, segment), + "start": pd.to_datetime(pairs.time_1, utc=True), + "end": pd.to_datetime(pairs.time_2, utc=True), + }, + geometry=pairs.geometry.to_numpy(), + crs="EPSG:4326", + ) + return frame.dissolve( + by=["satellite_1", "satellite_2", "segment"], + aggfunc={"start": "min", "end": "max"}, + as_index=False, + )[PAIR_COLUMNS] + + +@app.task +def collect_region_window_task( # pylint: disable=too-many-arguments + members: List[str], + region: str, + times: List[str], + window_end: str, + start: str, + end: str, + step: float, + segment: float, + instrument_index: Optional[int] = None, + max_time_difference: Optional[float] = None, + systems: Optional[dict] = None, +) -> list: + """ + Task to analyze a window of times of the swath coverage of a region (see + `analyze_window`). + + Args: + members (List[str]): JSON serialized member satellites. + region (str): GeoJSON serialized region geometry. + times (List[str]): ISO 8601 serialized times of the window. + window_end (str): ISO 8601 serialized end of the window. + start (str): ISO 8601 serialized start of the analysis period. + end (str): ISO 8601 serialized end of the analysis period. + step (float): Time step (seconds). + segment (float): Swath segment duration (seconds). + instrument_index (Optional[int]): Instrument index, or `None` for all. + max_time_difference (Optional[float]): Maximum time difference + (seconds) of coincident footprints, or `None` not to find them. + systems (Optional[dict]): Platform of each member, by name, if + coincident footprints are between systems. + + Returns: + list: Tagged GeoJSON (or JSON) serialized results of the window. + """ + results = analyze_window( + deserialize_members(members), + shape(json.loads(region)), + pd.DatetimeIndex([datetime.fromisoformat(t) for t in times]).tz_convert("UTC"), + datetime.fromisoformat(window_end), + datetime.fromisoformat(start), + datetime.fromisoformat(end), + timedelta(seconds=step), + timedelta(seconds=segment), + instrument_index, + None if max_time_difference is None else timedelta(seconds=max_time_difference), + systems, + ) + return [ + tag( + f"region-{kind}", + ( + frame.to_json(orient="records") + if kind == "differences" + else to_geojson(frame) + ), + ) + for kind, frame in results.items() + ] + + +def _cumulative_curve( + pieces: gpd.GeoDataFrame, + region: Union[Polygon, MultiPolygon], + region_area: float, + start: datetime, + end: datetime, +) -> tuple: + """ + Accumulates the pieces of area observed by each time of a coverage curve + into the share of the region's area observed so far. + + Returns: + tuple: the curve, and the share observed by the end + """ + times = curve_seconds(start, end) + shares = np.zeros(len(times)) + by_bin = {} + for row in pieces.itertuples(): + by_bin.setdefault(int(row.bin), []).append(row.geometry) + observed = None + for k in range(len(times)): + if k in by_bin: + piece = shapely.union_all(by_bin[k]) + observed = piece if observed is None else shapely.union(observed, piece) + if observed is not None and region_area > 0: + shares[k] = min( + 1.0, area_km2(shapely.intersection(observed, region)) / region_area + ) + curve = CoverageCurve( + times=[round(float(t), 3) for t in times], + shares=[float(s) for s in shares], + ) + return curve, float(shares[-1]) + + +def summarize_region( # pylint: disable=too-many-arguments,too-many-locals + region: Union[Polygon, MultiPolygon], + area: gpd.GeoDataFrame, + observations: gpd.GeoDataFrame, + start: datetime, + end: datetime, + common: Optional[gpd.GeoDataFrame] = None, + differences: Optional[np.ndarray] = None, +) -> tuple: + """ + Summarizes the swath coverage of a region. + + Returns: + tuple: the `RegionSummary`, and the aggregated observations + """ + region_area = area_km2(region) + curve, covered = _cumulative_curve(area, region, region_area, start, end) + duration = (end - start).total_seconds() + aggregated = ( + aggregate_observations(observations).sort_values("start", ignore_index=True) + if not observations.empty + else observations + ) + starts = ( + _seconds(aggregated["start"], start) if not aggregated.empty else np.array([]) + ) + ends = _seconds(aggregated["end"], start) if not aggregated.empty else np.array([]) + gaps = starts[1:] - ends[:-1] + edges = np.concatenate( + [ + [starts[0] if len(starts) else duration], + gaps, + [duration - ends[-1]] if len(ends) else [], + ] + ) + access, _ = summarize_values(ends - starts, np.ones(len(starts))) + revisit, _ = summarize_values(gaps, np.ones(len(gaps))) + coincidence = None + if common is not None: + common_curve, common_share = _cumulative_curve( + common, region, region_area, start, end + ) + values = np.asarray(differences if differences is not None else [], dtype=float) + time_difference, _ = summarize_values(values, np.ones(len(values))) + coincidence = SwathCoincidenceSummary( + pairs=len(values), + common=common_share, + coverage=common_curve, + time_difference=time_difference, + ) + summary = RegionSummary( + area=region_area, + covered=covered, + coverage=curve, + observations=len(aggregated), + access=access, + revisit=revisit, + max_gap=float(np.max(edges)) if len(edges) else duration, + coincidence=coincidence, + ) + return summary, aggregated + + +@app.task +def combine_region_task( # pylint: disable=too-many-arguments,too-many-locals + results: list, + region: str, + start: str, + end: str, + colors: dict, + systems: Optional[dict] = None, + coincidence: bool = False, +) -> str: + """ + Task to combine the windows of an analysis of the swath coverage of a + region (and the orbit tracks of member satellites). + + Args: + results (list): Tagged results of parallel tasks. + region (str): GeoJSON serialized region geometry. + start (str): ISO 8601 serialized start of the analysis period. + end (str): ISO 8601 serialized end of the analysis period. + colors (dict): Display colors by member satellite name. + systems (Optional[dict]): Index of the satellite or constellation by + member satellite name. + coincidence (bool): Whether the windows found coincident footprints. + + Returns: + str: JSON serialized `RegionAnalysisResult`. + """ + animation = combine_animation(results, start, colors) + start_time = datetime.fromisoformat(start) + end_time = datetime.fromisoformat(end) + geometry = shape(json.loads(region)) + + def frames(kind: str, **kwargs) -> gpd.GeoDataFrame: + return concat( + from_geojson(data, **kwargs) for data in untag(results, f"region-{kind}") + ) + + swaths = _merge_segments( + frames("swaths", datetimes=["start", "end"], columns=SWATH_COLUMNS), + ["satellite", "instrument", "segment"], + SWATH_COLUMNS, + ) + observations = frames( + "observations", + datetimes=["start", "epoch", "end"], + columns=OBSERVATION_COLUMNS, + ) + pairs = common = differences = None + if coincidence: + pairs = _merge_segments( + frames("pairs", datetimes=["start", "end"], columns=PAIR_COLUMNS), + ["satellite_1", "satellite_2", "segment"], + PAIR_COLUMNS, + ) + common = frames("common", columns=PIECE_COLUMNS) + differences = np.array( + [ + row["seconds"] + for data in untag(results, "region-differences") + for row in json.loads(data) + ], + dtype=float, + ) + summary, aggregated = summarize_region( + geometry, + frames("area", columns=PIECE_COLUMNS), + observations, + start_time, + end_time, + common, + differences, + ) + return RegionAnalysisResult( + region={ + "type": "FeatureCollection", + "features": [ + {"type": "Feature", "geometry": mapping(geometry), "properties": {}} + ], + }, + swaths=json.loads(to_geojson(swaths.drop(columns="segment"))), + coincident=( + None + if pairs is None + else json.loads(to_geojson(pairs.drop(columns="segment"))) + ), + observations=[ + RegionObservation( + satellite=str(row.satellite), + instrument=str(row.instrument), + start=float(s), + end=float(e), + ) + for row, s, e in zip( + aggregated.itertuples(), + ( + _seconds(aggregated["start"], start_time) + if not aggregated.empty + else [] + ), + _seconds(aggregated["end"], start_time) if not aggregated.empty else [], + ) + ], + tracks=animation.tracks, + colors=animation.colors, + systems=systems or {}, + summary=summary, + ).model_dump_json() + + +def _merge_segments( + frame: gpd.GeoDataFrame, by: List[str], columns: List[str] +) -> gpd.GeoDataFrame: + """ + Merges the segments of windows (a segment split between two windows is + dissolved into one), sorted by start. + """ + if frame.empty: + return empty_frame(columns) + merged = frame.dissolve( + by=by, aggfunc={"start": "min", "end": "max"}, as_index=False + ) + return merged[columns].sort_values("start", ignore_index=True) diff --git a/src/tatc_app/worker.py b/src/tatc_app/worker.py index d99bf2a..953950b 100644 --- a/src/tatc_app/worker.py +++ b/src/tatc_app/worker.py @@ -71,6 +71,7 @@ def _ssl_config(env_prefix: str, key_prefix: str = "") -> dict: "tatc_app.generation.tasks", "tatc_app.latency.tasks", "tatc_app.overflight.tasks", + "tatc_app.region.tasks", "tatc_app.tracking.tasks", ], ) diff --git a/tests/test_region.py b/tests/test_region.py new file mode 100644 index 0000000..c92defc --- /dev/null +++ b/tests/test_region.py @@ -0,0 +1,208 @@ +from datetime import datetime, timedelta, timezone +from unittest import mock + +import numpy as np +import pandas as pd +import shapely +from shapely.geometry import box +from tatc.analysis import ( + aggregate_observations, + collect_footprints, + collect_region_observations, + find_coincident_ground_track, +) +from tatc.schemas import ( + PointedInstrument, + Satellite, + SunSynchronousOrbit, + WalkerConstellation, +) + +from tatc_app.region.schemas import RegionAnalysisRequest, RegionAnalysisResult +from tatc_app.region.tasks import area_km2 + +from .base import TatcTestCase + +START = datetime(2022, 6, 1, tzinfo=timezone.utc) +END = datetime(2022, 6, 1, 12, tzinfo=timezone.utc) +STEP = timedelta(seconds=60) +DIFFERENCE = timedelta(hours=1) +REGION = box(-125, 24, -66, 50) +ORBIT = SunSynchronousOrbit( + altitude=705e3, equator_crossing_time="13:30", equator_crossing_ascending=True +) +INSTRUMENT = PointedInstrument( + name="P", cross_track_field_of_view=60, along_track_field_of_view=4 +) + + +class RegionTestCase(TatcTestCase): + def setUp(self): + super().setUp() + self.constellation = WalkerConstellation( + name="W", + orbit=ORBIT, + instruments=[INSTRUMENT], + number_satellites=4, + number_planes=4, + ) + self.satellite = Satellite( + name="S", + orbit=SunSynchronousOrbit( + altitude=705e3, + equator_crossing_time="13:00", + equator_crossing_ascending=True, + ), + instruments=[INSTRUMENT], + ) + + def request(self, **kwargs) -> RegionAnalysisRequest: + return RegionAnalysisRequest( + **{ + "satellites": [self.constellation, self.satellite], + "start": START, + "end": END, + "region": { + "type": "Polygon", + "coordinates": [list(REGION.exterior.coords)], + }, + "step": STEP, + "coincidence": {"max_time_difference": DIFFERENCE}, + **kwargs, + } + ) + + def analyze(self, request, window_steps=None) -> RegionAnalysisResult: + with mock.patch("tatc_app.region.router.WINDOW_STEPS", window_steps or 100000): + task = self.run_analysis("/analyze/region", request) + self.task_id = task["task_id"] + return RegionAnalysisResult.model_validate( + self.get_json(f"/analyze/region/{task['task_id']}") + ) + + def test_area(self): + self.assertAlmostEqual(area_km2(box(-180, -90, 180, 90)) / 510065622, 1, 5) + self.assertEqual(area_km2(None), 0) + + def test_region_analysis(self): + request = self.request() + members = request.get_members() + result = self.analyze(request, window_steps=97) + summary = result.summary + self.assertAlmostEqual(summary.area, area_km2(REGION)) + # the share observed grows to the share covered + shares = np.array(summary.coverage.shares) + self.assertTrue((np.diff(shares) >= -1e-9).all()) + self.assertEqual(shares[0], 0) + self.assertAlmostEqual(shares[-1], summary.covered) + times = list(pd.date_range(START, END, freq=STEP)) + footprints = collect_footprints( + members, times, instrument_index=None, mask=REGION, time_step=STEP + ) + footprints = footprints[footprints.valid_obs] + observed = shapely.intersection(shapely.union_all(footprints.geometry), REGION) + self.assertAlmostEqual(summary.covered, area_km2(observed) / summary.area, 4) + # the observations of the region, merged across windows + expected = aggregate_observations( + collect_region_observations(REGION, members, START, END, None) + ) + self.assertEqual(summary.observations, len(expected)) + self.assertEqual(len(result.observations), len(expected)) + # coincident footprints, paired across windows + pairs = find_coincident_ground_track( + footprints.reset_index(drop=True), max_time_difference=DIFFERENCE + ) + self.assertGreater(len(pairs), 0) + self.assertEqual(summary.coincidence.pairs, len(pairs)) + self.assertLessEqual(summary.coincidence.time_difference.max, 3600) + self.assertGreater(summary.coincidence.common, 0) + self.assertLessEqual(summary.coincidence.common, summary.covered) + # swaths and common areas to display + self.assertGreater(len(result.swaths.features), 0) + self.assertGreater(len(result.coincident.features), 0) + czml = self.get_json(f"/analyze/region/{self.task_id}/czml") + self.assertTrue(any(p["id"].startswith("coincident/") for p in czml)) + self.assertTrue(any(p["id"].startswith("swath/") for p in czml)) + + def test_windows_agree(self): + request = self.request() + one = self.analyze(request).summary + many = self.analyze(request, window_steps=50).summary + self.assertAlmostEqual(one.covered, many.covered, 6) + self.assertEqual(one.observations, many.observations) + self.assertEqual(one.coincidence.pairs, many.coincidence.pairs) + self.assertAlmostEqual(one.coincidence.common, many.coincidence.common, 6) + + def test_systems(self): + result = self.analyze( + self.request( + coincidence={"max_time_difference": DIFFERENCE, "platforms": "systems"} + ), + window_steps=200, + ) + names = [ + {f.properties["satellite_1"], f.properties["satellite_2"]} + for f in result.coincident.features + ] + self.assertGreater(len(names), 0) + # every common area is between the satellite and the constellation + for pair in names: + self.assertIn("S", pair) + members = self.analyze(self.request(), window_steps=200) + self.assertLess( + result.summary.coincidence.pairs, members.summary.coincidence.pairs + ) + + def test_without_coincidence_and_known_region(self): + result = self.analyze( + self.request( + coincidence=None, region="conus", end=START + timedelta(hours=3) + ) + ) + self.assertIsNone(result.summary.coincidence) + self.assertIsNone(result.coincident) + self.assertGreater(result.summary.area, 7e6) + + def test_saved_run(self): + request = self.request(coincidence=None, end=START + timedelta(hours=2)) + result = self.analyze(request) + response = self.client.post( + "/runs", + json={ + "name": "Region", + "analysis": "region", + "taskId": self.task_id, + "request": request.model_dump(mode="json"), + "design": { + "version": 2, + "satellites": [], + "stations": [], + "targets": [], + }, + }, + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual( + response.json()["summary"], result.summary.model_dump(mode="json") + ) + + def test_invalid_requests(self): + base = self.request().model_dump(mode="json", exclude_none=True) + single = self.satellite.model_dump(mode="json") + for changes in ( + {"region": "XYZ"}, + {"display": {"start": base["start"], "end": base["end"], "delta": 60}}, + {"satellites": [single]}, + { + "satellites": [base["satellites"][0]], + "coincidence": {"platforms": "systems"}, + }, + {"coincidence": {"maxTimeDifference": -1}}, + {"step": 0}, + ): + response = self.client.post("/analyze/region", json=base | changes) + self.assertEqual(response.status_code, 422, changes) + # one satellite, without coincident swaths, is valid + valid = base | {"satellites": [single]} + valid.pop("coincidence") + RegionAnalysisRequest.model_validate(valid) From 69a1f8fd09c2a729a2e7aa92ee8f95adc1cb7e88 Mon Sep 17 00:00:00 2001 From: Paul Grogan Date: Wed, 25 Nov 2026 00:03:13 -0700 Subject: [PATCH 3/3] Merge region swath coverage into ground track swaths The swath analysis (/analyze/swaths) takes an optional region, replacing the separate region analysis (/analyze/region, unreleased): without a region it gives unclipped swaths as before; with one, swaths clipped to it and the summary of its coverage (area observed over time, observations, revisit, and optionally coincident swaths, which now need a region). The code moves from region/ and tracking/ to swaths/, and saved runs of swaths carry a summary only with a region. Swath analyses accept display times to limit the animation: orbit tracks and swath (and coincident) segments are given only over them, limiting the size of results of long periods. With a region, footprints are still sampled over the whole analysis period, so its summary does not depend on the animation; without one, only over the animation. Without coincidence, windows are analyzed in parallel by member satellite. The GUI merges the analyses (a "Limit to a region" option), shows the animation length for swaths, and drops the shortened default duration. Analyses without a grid show the region by its outline (from a new /generate/region endpoint) and hide the grid controls; a global region of swaths is the whole globe; and the region hides over results. --- README.md | 9 +- docs/api.rst | 38 ++-- src/static/analysis.js | 175 +++++++-------- src/static/index.html | 151 +++++++------ src/static/library.js | 29 ++- src/static/region.js | 141 +++++++++++- src/tatc_app/generation/router.py | 45 +++- src/tatc_app/generation/schemas.py | 28 +++ src/tatc_app/library/router.py | 16 +- src/tatc_app/library/schemas.py | 1 - src/tatc_app/main.py | 4 +- src/tatc_app/region/router.py | 154 ------------- src/tatc_app/{region => swaths}/__init__.py | 0 src/tatc_app/swaths/router.py | 179 ++++++++++++++++ src/tatc_app/{region => swaths}/schemas.py | 148 ++++++++----- src/tatc_app/{region => swaths}/tasks.py | 202 +++++++++++------- src/tatc_app/tracking/router.py | 114 +--------- src/tatc_app/tracking/schemas.py | 77 +------ src/tatc_app/tracking/tasks.py | 116 +--------- src/tatc_app/worker.py | 2 +- tests/test_region_outline.py | 35 +++ tests/test_swaths.py | 66 +++++- .../{test_region.py => test_swaths_region.py} | 54 +++-- 23 files changed, 959 insertions(+), 825 deletions(-) delete mode 100644 src/tatc_app/region/router.py rename src/tatc_app/{region => swaths}/__init__.py (100%) create mode 100644 src/tatc_app/swaths/router.py rename src/tatc_app/{region => swaths}/schemas.py (56%) rename src/tatc_app/{region => swaths}/tasks.py (76%) create mode 100644 tests/test_region_outline.py rename tests/{test_region.py => test_swaths_region.py} (77%) diff --git a/README.md b/README.md index 30c8767..313880c 100644 --- a/README.md +++ b/README.md @@ -31,10 +31,10 @@ tasks and visualized with animated results (CZML) in the GUI: satellites and constellations) observe a point of the grid at once, within a time difference, as for cross-calibration matchups, with the statistics of coverage of those periods (and optionally their sampling sufficiency). - * Ground track swaths (`/analyze/swaths`): instrument swaths that accumulate over time. - * Swath coverage of a region (`/analyze/region`): swaths over a region, the share of its area - observed over time, its observations and revisit, and optionally coincident swaths: the - areas two satellites observe in common within a time difference. + * Ground track swaths (`/analyze/swaths`): instrument swaths that accumulate over the + animation; optionally clipped to a region, with the share of its area observed over the + analysis period, its observations and revisit, and optionally coincident swaths: the areas + two satellites observe in common within a time difference. * Data latency (`/analyze/latency`): latency to downlink observations at ground stations. * Point access (`/analyze/overflight`): access windows of satellites to target points. @@ -92,6 +92,7 @@ and response bodies. | `GET /tasks/{group_id}/progress` | Get the progress of a group of parallel tasks | | `POST /tasks/{task_id}/revoke` | Cancel a task (and, with `group_id`, its group of parallel tasks) | | `POST /generate/points`, `POST /generate/cells` | Generate points or cells (GeoJSON) | +| `POST /generate/region` | Get the outline of a region (GeoJSON) to display it | | `POST /validate/space-system` | Validate a satellite or constellation and summarize its members | | `GET /catalog/systems`, `POST /catalog/systems/{system_id}/build` | List and build satellite systems of the TAT-C system catalog | | `GET /catalog/instruments`, `POST /catalog/instruments/{entry_id}/add` | List and add instruments of the TAT-C instrument catalog | diff --git a/docs/api.rst b/docs/api.rst index 4897c67..ea8a794 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -88,20 +88,27 @@ of a coverage analysis, of coincidences rather than observations. .. autopydantic_model:: tatc_app.coincidence.schemas.CoincidenceAnalysisResult -Swath Coverage of a Region -^^^^^^^^^^^^^^^^^^^^^^^^^^ +Ground Track Swaths +^^^^^^^^^^^^^^^^^^^ + +A swath analysis samples the footprints of instruments every ``step``, +dissolved into segments that accumulate over the animation (``display``, by +default every ``step`` over the analysis period): swath segments are given +only over it. -A region analysis samples the footprints of instruments every ``step`` over -the analysis period, clipped to the region: the share of its area observed -over time (measured in an equal-area projection of the WGS 84 ellipsoid), its -observations (when any part of it is observed), and, with ``coincidence``, the -areas that two platforms observe in common within ``max_time_difference``. +With a ``region``, footprints are clipped to it and sampled over the whole +analysis period, to summarize the share of its area observed over time +(measured in an equal-area projection of the WGS 84 ellipsoid), its +observations (when any part of it is observed), and, with ``coincidence``, +the areas that two platforms observe in common within +``max_time_difference``. Without one, footprints are sampled only over the +animation. -.. autopydantic_model:: tatc_app.region.schemas.RegionAnalysisRequest +.. autopydantic_model:: tatc_app.swaths.schemas.SwathAnalysisRequest -.. autopydantic_model:: tatc_app.region.schemas.SwathCoincidenceOptions +.. autopydantic_model:: tatc_app.swaths.schemas.SwathCoincidenceOptions -.. autopydantic_model:: tatc_app.region.schemas.RegionAnalysisResult +.. autopydantic_model:: tatc_app.swaths.schemas.SwathAnalysisResult .. autopydantic_model:: tatc_app.analysis.summary.RegionSummary @@ -123,13 +130,6 @@ Point Access (Overflight) .. autopydantic_model:: tatc_app.overflight.schemas.OverflightAnalysisResult -Ground Track Swaths -^^^^^^^^^^^^^^^^^^^ - -.. autopydantic_model:: tatc_app.tracking.schemas.SwathAnalysisRequest - -.. autopydantic_model:: tatc_app.tracking.schemas.SwathAnalysisResult - Orbit and Ground Tracks ^^^^^^^^^^^^^^^^^^^^^^^ @@ -149,6 +149,10 @@ generate them. .. autopydantic_model:: tatc_app.generation.schemas.TimeGenerator +The outline of a region (a polygon, known shape, or country) displays it. + +.. autopydantic_model:: tatc_app.generation.schemas.RegionOutlineRequest + .. autoclass:: tatc_app.generation.schemas.PointGeneratorMethod :members: :undoc-members: diff --git a/src/static/analysis.js b/src/static/analysis.js index 7170a1d..41d30d3 100644 --- a/src/static/analysis.js +++ b/src/static/analysis.js @@ -1,20 +1,23 @@ -// Analysis tab: coverage and revisit, ground track swaths, data latency with -// ground stations, and point access (overflight) analyses, with animated -// results in the Cesium viewer. +// Analysis tab: coverage and revisit, coincident observations, ground track +// swaths (optionally over a region), data latency with ground stations, and +// point access (overflight) analyses, with animated results in the Cesium +// viewer. let analysisResult = null; // {type, result, taskId, payload, design, duration} let targetLayer = null; // The analyses (in the order of the analysis select): whether each analyzes -// the points (and cells) of the region, and whether it shows its results with -// a layer of targets (points and cells colored by a metric, see -// `DISPLAY_MODES`). +// a region (`"optional"` if it may, see `usesRegion`), whether it samples a +// grid of points and cells of the region (or else analyzes the region itself, +// shown by its outline), and whether it shows its results with a layer of +// targets (points and cells colored by a metric, see `DISPLAY_MODES`). const ANALYSES = { coverage: { label: "Coverage and Revisit", description: "Observations of a grid of points (and cells) by the checked instruments of the checked satellites. " + "Animates observations accumulating over the analysis period, or shows final revisit statistics.", region: true, + grid: true, targetLayer: true, endpoint: "/analyze/coverage" }, @@ -23,30 +26,26 @@ const ANALYSES = { description: "Periods when several of the checked satellites (or satellites and constellations) observe a point of the grid at once, " + "as for cross-calibration or multi-sensor matchups. Animates coincidences accumulating, or shows final statistics.", region: true, + grid: true, targetLayer: true, endpoint: "/analyze/coincidence" }, swaths: { label: "Ground Track Swaths", - description: "Ground track swaths of the checked instruments, accumulating in segments as satellites orbit. " + - "Best for periods of hours to a few days.", - region: false, + description: "Ground track swaths of the checked instruments, accumulating in segments over the animation. " + + "Limited to a region, also the share of its area observed over the analysis period, its observations and revisit, " + + "and optionally the areas several satellites observe in common within a time difference.", + region: "optional", + grid: false, targetLayer: false, endpoint: "/analyze/swaths" }, - region: { - label: "Swath Coverage of a Region", - description: "Swaths of the checked instruments over the region, sampled every step: the share of its area observed over time, " + - "its observations and revisit, and optionally the areas several satellites observe in common within a time difference.", - region: true, - targetLayer: false, - endpoint: "/analyze/region" - }, latency: { label: "Data Latency (Ground Stations)", description: "Latency from the observation of each point to its downlink at a ground station. " + "Animates contacts with ground stations and observations awaiting downlink.", region: true, + grid: true, targetLayer: true, endpoint: "/analyze/latency" }, @@ -55,6 +54,7 @@ const ANALYSES = { description: "Accesses of selected target points by each satellite, with lines of sight " + "animated during each access and a table of access windows.", region: false, + grid: false, targetLayer: false, endpoint: "/analyze/overflight" } @@ -64,6 +64,13 @@ function hasTargetLayer(type) { return ANALYSES[type].targetLayer; } +// Tests whether an analysis of a type uses the region (swaths, if limited to +// it). +function usesRegion(type) { + const region = ANALYSES[type].region; + return region === "optional" ? $("#swaths-region-enabled").is(":checked") : region; +} + function getAnalysisType() { return $("#analysis-type").val(); } @@ -478,40 +485,36 @@ function getAnalysisPayload(type, base) { sufficiency: sufficiency, sample_size: sampleSize }); - } else if (type == "region") { - const step = Number($("#region-step").val()); - const segment = Number($("#region-segment").val()); + } else if (type == "swaths") { + const step = Number($("#swaths-step").val()); + const segment = Number($("#swaths-segment").val()); if (!(step > 0) || !(segment > 0)) { $("#analysis-error").text("The step and segment must be positive.").show(); return null; } + const region = usesRegion(type); let coincidence = null; - if ($("#region-coincidence-enabled").is(":checked")) { - const minutes = Number($("#region-coincidence-difference").val()); + if (region && $("#swaths-coincidence-enabled").is(":checked")) { + const minutes = Number($("#swaths-coincidence-difference").val()); if (!(minutes >= 0)) { $("#analysis-error").text("The maximum time difference must not be negative.").show(); return null; } coincidence = { max_time_difference: minutes * 60, - platforms: $("#region-coincidence-platforms").val() + platforms: $("#swaths-coincidence-platforms").val() }; } - // footprints are sampled every step over the analysis period - return _.assign(_.omit(base, "display"), { - region: getRegionMask(), + // swaths over the animation; with a region, its coverage over the + // analysis period + // (a global region is the whole globe, not none) + return _.assign(base, { + region: region ? (getRegionMask() || boxPolygon(-180, -90, 180, 90)) : null, instrument_index: null, step: step, segment: segment * 60, coincidence: coincidence }); - } else if (type == "swaths") { - // swaths animate over the analysis period - return _.assign(_.omit(base, "display"), { - instrument_index: null, - step: Number($("#swaths-step").val()), - segment: Number($("#swaths-segment").val()) * 60 - }); } else if (type == "latency") { if (design.stations.length == 0) { $("#analysis-error").text("Add at least one ground station.").show(); @@ -584,7 +587,9 @@ function startAnalysis(type, payload, designSnapshot) { return; } clearAnalysisLayers(); - showRegionGrid(false); + // the region (its grid or outline) shows while editing it, not over + // results + showRegion(false); analysisResult = { type: type, result: result, @@ -732,7 +737,32 @@ function showAnalysisData() { }) }] }); - } else if (type == "region") { + } else if (type == "swaths") { + if (!result.summary) { + showResultsTable({ + title: "Swath Segments", + columns: [ + { title: "Satellite", key: "satellite" }, + { title: "Instrument", key: "instrument" }, + { title: "Start (UTC)", key: "start" }, + { title: "End (UTC)", key: "end" } + ], + rows: _.map(result.swaths.features, "properties"), + filename: "swath-segments", + note: "Segments over the animation; each appears once it ends. Download the full geometry with the API." + }); + return; + } + // over a region: its observations, with the swath segments as extras + const segments = { + label: "Swath segments CSV", + filename: "swath-segments.csv", + columns: ["satellite", "instrument", "start", "end"], + rows: _.map(result.swaths.features, function(feature) { + const p = feature.properties; + return [p.satellite, p.instrument, p.start, p.end]; + }) + }; const epoch = new Date(analysisResult.payload.start).getTime(); const iso = function(seconds) { return new Date(epoch + seconds * 1000).toISOString(); }; showResultsTable({ @@ -754,27 +784,20 @@ function showAnalysisData() { }; }), filename: "region-observations", - note: "Periods when any part of the region is observed (overlapping observations merged). Click a row to jump the animation to it.", + note: "Periods over the analysis period when any part of the region is observed (overlapping observations merged). " + + "Swaths show over the animation: click a row within it to jump to it.", summary: function(container) { renderRegionSummary(container, result.summary); }, + extras: [segments], onRowClick: function(row) { - viewer.clock.currentTime = Cesium.JulianDate.fromIso8601(row.start_utc); + const start = Cesium.JulianDate.fromIso8601(row.start_utc); + if (Cesium.JulianDate.greaterThan(start, viewer.clock.stopTime)) { + return; + } + viewer.clock.currentTime = start; viewer.clock.shouldAnimate = true; $("#results-dialog").modal("hide"); } }); - } else if (type == "swaths") { - showResultsTable({ - title: "Swath Segments", - columns: [ - { title: "Satellite", key: "satellite" }, - { title: "Instrument", key: "instrument" }, - { title: "Start (UTC)", key: "start" }, - { title: "End (UTC)", key: "end" } - ], - rows: _.map(result.swaths.features, "properties"), - filename: "swath-segments", - note: "Each segment appears in the animation once it ends. Download the full geometry with the API." - }); } else { const ids = _.map(result.points.features, function(f) { return f.properties.id; }); const hashes = _.map(result.points.features, function(f) { return f.properties.point_id; }); @@ -835,44 +858,26 @@ function limitAnimation() { animate.val(Math.min(requestedAnimate, limit)); } -// The swaths analysis suits short periods, so selecting it shortens a long -// duration; the duration it replaced returns on selecting another analysis -// (unless edited meanwhile). -const SWATHS_MAX_DAYS = 3; -const SWATHS_DEFAULT_DAYS = 0.25; -let durationBeforeSwaths = null; // days - -function adjustDurationForType(type) { - const input = $("#analysis-duration"); - if (type == "swaths") { - if (Number(input.val()) > SWATHS_MAX_DAYS) { - durationBeforeSwaths = input.val(); - input.val(SWATHS_DEFAULT_DAYS); - } - } else if (durationBeforeSwaths !== null) { - input.val(durationBeforeSwaths); - durationBeforeSwaths = null; - } +// Shows the region panel if the selected analysis uses the region, and the +// region itself while editing it (not over results shown). +function updateRegionPanel(showResults) { + const region = Boolean(usesRegion(getAnalysisType())); + $(".region-panel").toggle(region); + updateRegionControls(); + $("#swaths-region-options").toggle($("#swaths-region-enabled").is(":checked")); + showRegion(region && !showResults); } function changeAnalysisType() { const type = getAnalysisType(); $(".analysis-panel").removeClass("shown"); $(".analysis-panel[data-analysis~='" + type + "']").addClass("shown"); - $(".region-panel").toggle(ANALYSES[type].region); $("#analysis-description").text(ANALYSES[type].description); - $(".animate-control").toggle(type != "swaths" && type != "region"); - adjustDurationForType(type); limitAnimation(); // picking (region vertices or target points) applies to one analysis type stopMapPick(); const showResults = Boolean(analysisResult && analysisResult.type == type); - // the region shows while editing it (not over its results) - if (!ANALYSES[type].region) { - showRegion(false); - } else if (!showResults) { - showRegion(true); - } + updateRegionPanel(showResults); showAnalysisLayers(showResults); enableResultButtons(showResults); renderSiteEntities(); @@ -906,11 +911,7 @@ $(document).ready(function() { viewer.clock.currentTime = viewer.clock.startTime.clone(); changeAnalysisType(); }); - $("#analysis-duration").change(function() { - // an edited duration stays on leaving the swaths analysis - durationBeforeSwaths = null; - limitAnimation(); - }); + $("#analysis-duration").change(limitAnimation); $("#analysis-animate").change(function() { const value = Number($(this).val()); if (value > 0) { @@ -918,8 +919,14 @@ $(document).ready(function() { } limitAnimation(); }); - $("#region-coincidence-enabled").change(function() { - $("#region-coincidence-options").toggle($(this).is(":checked")); + $("#swaths-region-enabled").change(function() { + // picking region vertices stops with the region + stopMapPick(); + const type = getAnalysisType(); + updateRegionPanel(Boolean(analysisResult && analysisResult.type == type)); + }); + $("#swaths-coincidence-enabled").change(function() { + $("#swaths-coincidence-options").toggle($(this).is(":checked")); }); $("#sample-size-enabled").change(function() { $("#sample-size-options").toggle($(this).is(":checked")); diff --git a/src/static/index.html b/src/static/index.html index 2d3668c..36dfabe 100644 --- a/src/static/index.html +++ b/src/static/index.html @@ -182,7 +182,7 @@

Orbit Preview
days
- +
h
@@ -190,7 +190,17 @@
Orbit Preview
- + +
+
+
+ + +
+
+
+ +
@@ -209,7 +219,7 @@
Orbit Preview
-
+
- -
-
- -
- -
s
-
-
-
- -
- -
min
-
-
Swaths over the region accumulate as each segment completes. The animation spans the analysis duration.
-
-
-
- - -
-
- -
-
- +
s
@@ -387,7 +354,33 @@
Orbit Preview
min
-
Swaths accumulate as each segment completes. The animation spans the analysis duration.
+
Swaths accumulate as each segment completes, over the animation.
+
+
@@ -798,7 +791,7 @@