Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,34 @@

## Unreleased

**A histclim file with rows its leaf does not have is refused, naming
the first row and the regions or years the file alone has.** The two
are one projection under two climates, so a row in one alone means the
other is incomplete. The rows were dropped with nothing said, while a
leaf row the histclim file lacked was refused already.

**A region left out for an invalid geometry is recorded as skipped,
apart from the regions repaired.** Under `on_invalid_geometry = "skip"`
the manifest listed the regions it left out as `repaired_geometry_regions`.
It now lists them as `skipped_invalid_geometry_regions`, with
`skipped_invalid_geometry_count`, and the source units as
`skipped_invalid_geometry_source_units`, and `RegionSet` carries them as
`skipped_invalid_ids`. In the four published artifacts checked, every
region listed as repaired has its rows.

**A `gs://` regions path passes the input check, and its bytes are
hashed into the manifest as a local file's are.** The reader took such a
path already, and the check refused it. The manifest had no hash of a
remote regions file. Reading one needs gcsfs, which the `[bigquery]`
extra installs, and a remote file in a format other than Parquet is
copied to a temporary directory first.

**`aggregate_gradient` takes `weight` with no default, and finds the
regions in the weight file's source key column.** It defaulted to
population, and read a column called `hierid` whatever the artifact's
source key was. The resident memory the pipeline logs counts pages of
the size the machine reports, where it took them as 4096 bytes.

**A model takes the row of its own name in a model weights table,
letter for letter, or the row declared for it, and a model with
neither is refused.** Before, the library dropped `surrogate_` from the
Expand Down
6 changes: 2 additions & 4 deletions cil_regionalization/backends/bigquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
from cil_regionalization.grid import GridSpec
from cil_regionalization.manifest import build_manifest, record_schema
from cil_regionalization.nearest_cell import find_missing_regions, synthesize_rows
from cil_regionalization.regions import RegionSet
from cil_regionalization.regions import RegionSet, _geometry_record
from cil_regionalization.schema import OutputSchema
from cil_regionalization.validate import check_grid_invariants, check_sum_to_one
from cil_regionalization.weights import WeightSpec
Expand Down Expand Up @@ -1118,9 +1118,7 @@ def _assemble_result(
manifest.inputs["regions_table"] = regions.table
if regions.source_uri is not None:
manifest.inputs["regions_path"] = regions.source_uri
if regions.repaired_ids:
manifest.extra["repaired_geometry_count"] = len(regions.repaired_ids)
manifest.extra["repaired_geometry_regions"] = list(regions.repaired_ids)
manifest.extra.update(_geometry_record(regions))
for w in non_area:
if w.table is not None:
manifest.inputs[f"weight:{w.name}"] = w.table
Expand Down
21 changes: 15 additions & 6 deletions cil_regionalization/backends/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
from cil_regionalization.grid import GridSpec
from cil_regionalization.manifest import build_manifest, hash_file, record_schema
from cil_regionalization.nearest_cell import find_missing_regions, synthesize_rows
from cil_regionalization.regions import RegionSet
from cil_regionalization.regions import RegionSet, _geometry_record
from cil_regionalization.schema import OutputSchema, SourceUnits
from cil_regionalization.validate import (
check_grid_invariants,
Expand Down Expand Up @@ -215,9 +215,7 @@ def _compute_grid(
)
manifest.inputs.update(_input_checksums(regions, weights))
manifest.extra["min_segment_area"] = drop_stats
if regions.repaired_ids:
manifest.extra["repaired_geometry_count"] = len(regions.repaired_ids)
manifest.extra["repaired_geometry_regions"] = list(regions.repaired_ids)
manifest.extra.update(_geometry_record(regions))
manifest.extra.update(_unknown_id_record(regions))
manifest.timing_seconds["compute_total"] = time.perf_counter() - t0

Expand Down Expand Up @@ -417,8 +415,16 @@ def _compute_polygons(
manifest.extra.update(_unknown_id_record(regions))
if regions.repaired_ids:
manifest.extra["repaired_geometry_regions"] = regions.repaired_ids
if regions.skipped_invalid_ids:
manifest.extra["skipped_invalid_geometry_regions"] = (
regions.skipped_invalid_ids
)
if source_set.repaired_ids:
manifest.extra["repaired_geometry_source_units"] = source_set.repaired_ids
if source_set.skipped_invalid_ids:
manifest.extra["skipped_invalid_geometry_source_units"] = (
source_set.skipped_invalid_ids
)
if near_edge_regions:
manifest.extra["near_domain_edge_regions"] = near_edge_regions
if near_edge_sources:
Expand Down Expand Up @@ -1078,10 +1084,13 @@ def _input_checksums(
regions: RegionSet,
weights: list[WeightSpec],
) -> dict[str, str]:
"""Hash the regions file and each weight raster for the manifest."""
"""Hash the regions file and each weight raster for the manifest. A
`gs://` regions file has the hash of the bytes it was read from."""
inputs: dict[str, str] = {}
path = regions.source_uri
if path is not None and not str(path).startswith("gs://") and Path(path).exists():
if regions.source_sha256 is not None:
inputs["geometry:regions"] = regions.source_sha256
elif path is not None and not str(path).startswith("gs://") and Path(path).exists():
inputs["geometry:regions"] = hash_file(path)
for w in weights:
if w.is_area:
Expand Down
11 changes: 8 additions & 3 deletions cil_regionalization/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,15 @@ def __init__(self, report: SumToOneReport, result: WeightsResult):

def check_inputs_exist(cfg: Config) -> list[str]:
"""A message for each input of ``cfg`` that is not on the local disk.
The inputs checked are regions.path, source.path unless it is a
``gs://`` URI, and each weight raster on the local backend."""
The inputs checked are regions.path and source.path unless they are
``gs://`` URIs, which are read and hashed when the run reads them, and
each weight raster on the local backend."""
problems: list[str] = []
if cfg.regions.path is not None and not Path(cfg.regions.path).exists():
if (
cfg.regions.path is not None
and not cfg.regions.path.startswith("gs://")
and not Path(cfg.regions.path).exists()
):
problems.append(f"regions.path does not exist: {cfg.regions.path}")
if (
cfg.source is not None
Expand Down
26 changes: 18 additions & 8 deletions cil_regionalization/gradients.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,17 @@ def aggregate_gradient(
regions: list[str],
gradient: np.ndarray,
*,
weight: str = "pop",
weight: str,
scale: np.ndarray | None = None,
normalize: bool = False,
) -> tuple[pd.DataFrame, np.ndarray]:
"""The target key frame and the gradient aggregated to the weight
file's targets, target by coefficient.

``gradient`` is coefficient by region, in the order of ``regions``,
and the shares are the column ``<weight>wt``. Weight rows for other
and the shares are the column ``<weight>wt``, which has no default.
A region is a value of the artifact's one source key column. Weight
rows for other
regions are ignored, as with ``restrict_to_sources``. For a total,
an extensive value, leave ``scale`` and ``normalize`` alone, and
each region's gradient is split by the weight shares and summed. For
Expand All @@ -131,9 +133,10 @@ def aggregate_gradient(
a difference of gradients, such as one against histclim, equals
differencing the aggregated ones.

Raises if the share column is missing, if a region has no weight
rows, if ``scale`` is not one value per region, or if a target has
zero total weight under ``normalize``.
Raises if the share column is missing, if the artifact's source key
is not one column, if a region has no weight rows, if ``scale`` is not
one value per region, or if a target has zero total weight under
``normalize``.
"""
frame = weights.frame
key_cols = list(weights.schema.id_fields)
Expand All @@ -143,9 +146,16 @@ def aggregate_gradient(
f"weight file has no {share_col!r} column "
f"(columns: {sorted(frame.columns)})"
)
source_keys = list(weights.schema.source_units.key_columns)
if len(source_keys) != 1:
raise ValueError(
f"a gradient region is one value of the source key, and this "
f"weight file's source key is {source_keys}"
)
(region_col,) = source_keys
index = {r: i for i, r in enumerate(regions)}
rows = frame[frame["hierid"].isin(index)]
covered = set(rows["hierid"])
rows = frame[frame[region_col].isin(index)]
covered = set(rows[region_col])
absent = [r for r in regions if r not in covered]
if absent:
raise ValueError(
Expand All @@ -167,7 +177,7 @@ def aggregate_gradient(
f"scale has shape {scale_vec.shape}; expected ({len(regions)},)"
)
for row in rows.itertuples(index=False):
r = index[row.hierid]
r = index[getattr(row, region_col)]
t = tindex[tuple(getattr(row, c) for c in key_cols)]
w = getattr(row, share_col) * scale_vec[r]
out[t] += w * gradient[:, r]
Expand Down
6 changes: 6 additions & 0 deletions cil_regionalization/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ def _build_merged_manifest(
"repaired_geometry_regions": supplement.get("extra", {}).get(
"repaired_geometry_regions", []
),
"skipped_invalid_geometry_count": supplement.get("extra", {}).get(
"skipped_invalid_geometry_count", 0
),
"skipped_invalid_geometry_regions": supplement.get("extra", {}).get(
"skipped_invalid_geometry_regions", []
),
"bq_compute_location": supplement.get("extra", {}).get(
"bq_compute_location"
),
Expand Down
34 changes: 30 additions & 4 deletions cil_regionalization/pipelines/montecarlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -2308,11 +2308,14 @@ def _peak_rss_gb() -> float:


def _current_rss_gb() -> Optional[float]:
"""This process's current resident memory in GB (Linux only)."""
"""This process's current resident memory in GB (Linux only). The
count is in pages, of the size the machine reports."""
import resource

try:
with open("/proc/self/statm") as f:
pages = int(f.read().split()[1])
return pages * 4096 / 1e9
return pages * resource.getpagesize() / 1e9
except OSError:
return None

Expand Down Expand Up @@ -2409,8 +2412,9 @@ def _subtract_leaf(
for row, in a float64 value column. In the projection trees this is
the scenario file minus its histclim sibling, before any weighting.
Raises if the two files differ in columns, if a key repeats in
either, or if a row of ``frame`` has no match in the file. Rows of
the file with no match in ``frame`` are dropped.
either, or if a row of either has no match in the other. They are
one projection under two climates, so a row in one alone means the
other is incomplete.
"""
other = _read_leaf(path, data_cfg, artifact)
keys = [c for c in frame.columns if c != data_cfg.value_col]
Expand All @@ -2427,6 +2431,28 @@ def _subtract_leaf(
f"subtract file {path} covers {len(merged)} of {len(frame)} "
f"rows; the two files must cover the same regions and years"
)
if len(other) != len(merged):
# each row of the file matched at most one row of frame
flagged = other[keys].merge(frame[keys], on=keys, how="left", indicator=True)
alone = flagged.loc[flagged["_merge"] == "left_only", keys]
first = {
k: v.item() if hasattr(v, "item") else v for k, v in alone.iloc[0].items()
}
only = []
for key in keys:
values = sorted(set(alone[key]) - set(frame[key]), key=str)
if values:
shown = ", ".join(str(v) for v in values[:3])
more = f" and {len(values) - 3} more" if len(values) > 3 else ""
only.append(f"{key} {shown}{more}")
where = f" The subtract file alone has {'; '.join(only)}." if only else ""
raise ValueError(
f"subtract file {path} has {len(alone)} "
f"{'row' if len(alone) == 1 else 'rows'} the leaf does not "
f"have (first: {first}); the two files must cover the same "
f"regions and years.{where} They are one projection under two "
f"climates, so a row in one alone means the other is incomplete."
)
merged[data_cfg.value_col] = merged[data_cfg.value_col].astype("float64") - merged[
f"{data_cfg.value_col}_subtract"
].astype("float64")
Expand Down
Loading