PyGeoFetch 2.7.0.8__py3-none-any.whl → 2.7.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. pygeofetch/__init__.py +1 -1
  2. pygeofetch/insar/interferogram.py +295 -46
  3. pygeofetch/insar/workflow.py +213 -7
  4. pygeofetch/meta.yaml +1 -1
  5. pygeofetch/sar/extraction.py +531 -4
  6. {pygeofetch-2.7.0.8.dist-info → pygeofetch-2.7.1.0.dist-info}/METADATA +2 -2
  7. {pygeofetch-2.7.0.8.dist-info → pygeofetch-2.7.1.0.dist-info}/RECORD +11 -50
  8. pygeofetch-2.7.1.0.dist-info/top_level.txt +1 -0
  9. pygeofetch-2.7.0.8.dist-info/top_level.txt +0 -7
  10. pygeofetch_crop_fix_part8/pygeofetch/insar/coregister.py +0 -1659
  11. pygeofetch_crop_fix_part8/pygeofetch/insar/esd.py +0 -752
  12. pygeofetch_crop_fix_part8/pygeofetch/insar/extraction.py +0 -986
  13. pygeofetch_crop_fix_part8/pygeofetch/insar/interferogram.py +0 -3729
  14. pygeofetch_crop_fix_part8/pygeofetch/insar/tops.py +0 -416
  15. pygeofetch_crop_fix_part8/tests/insar/test_crop_offset.py +0 -85
  16. pygeofetch_crop_fix_part8/tests/insar/test_tops_deramp.py +0 -236
  17. pygeofetch_part9/pygeofetch/insar/coregister.py +0 -1659
  18. pygeofetch_part9/pygeofetch/insar/esd.py +0 -752
  19. pygeofetch_part9/pygeofetch/insar/extraction.py +0 -986
  20. pygeofetch_part9/pygeofetch/insar/interferogram.py +0 -3741
  21. pygeofetch_part9/pygeofetch/insar/tops.py +0 -416
  22. pygeofetch_part9/tests/insar/test_coreg_default.py +0 -58
  23. pygeofetch_part9/tests/insar/test_crop_offset.py +0 -85
  24. pygeofetch_part9/tests/insar/test_tops_deramp.py +0 -236
  25. pygeofetch_tops_fix_part4/files/pygeofetch/insar/coregister.py +0 -1648
  26. pygeofetch_tops_fix_part4/files/pygeofetch/insar/interferogram.py +0 -3583
  27. pygeofetch_tops_fix_part4/files/pygeofetch/insar/tops.py +0 -374
  28. pygeofetch_tops_fix_part4/files/tests/insar/_fake_safe.py +0 -70
  29. pygeofetch_tops_fix_part4/files/tests/insar/_tops_sim.py +0 -93
  30. pygeofetch_tops_fix_part4/files/tests/insar/test_tops_deramp.py +0 -177
  31. pygeofetch_tops_fix_part5/files/pygeofetch/insar/coregister.py +0 -1648
  32. pygeofetch_tops_fix_part5/files/pygeofetch/insar/interferogram.py +0 -3611
  33. pygeofetch_tops_fix_part5/files/pygeofetch/insar/tops.py +0 -374
  34. pygeofetch_tops_fix_part5/files/tests/insar/_fake_safe.py +0 -70
  35. pygeofetch_tops_fix_part5/files/tests/insar/_tops_sim.py +0 -93
  36. pygeofetch_tops_fix_part5/files/tests/insar/test_tops_deramp.py +0 -177
  37. pygeofetch_tops_fix_part6/pygeofetch/insar/esd.py +0 -752
  38. pygeofetch_tops_fix_part6/pygeofetch/insar/interferogram.py +0 -3684
  39. pygeofetch_tops_fix_part6/pygeofetch/insar/tops.py +0 -416
  40. pygeofetch_tops_fix_part6/tests/insar/_fake_safe.py +0 -70
  41. pygeofetch_tops_fix_part6/tests/insar/_tops_sim.py +0 -93
  42. pygeofetch_tops_fix_part6/tests/insar/test_tops_deramp.py +0 -218
  43. pygeofetch_tops_fix_part7/pygeofetch/insar/esd.py +0 -752
  44. pygeofetch_tops_fix_part7/pygeofetch/insar/interferogram.py +0 -3728
  45. pygeofetch_tops_fix_part7/pygeofetch/insar/tops.py +0 -416
  46. pygeofetch_tops_fix_part7/tests/insar/_fake_safe.py +0 -70
  47. pygeofetch_tops_fix_part7/tests/insar/_tops_sim.py +0 -93
  48. pygeofetch_tops_fix_part7/tests/insar/test_tops_deramp.py +0 -236
  49. {pygeofetch-2.7.0.8.dist-info → pygeofetch-2.7.1.0.dist-info}/WHEEL +0 -0
  50. {pygeofetch-2.7.0.8.dist-info → pygeofetch-2.7.1.0.dist-info}/entry_points.txt +0 -0
  51. {pygeofetch-2.7.0.8.dist-info → pygeofetch-2.7.1.0.dist-info}/licenses/LICENSE +0 -0
pygeofetch/__init__.py CHANGED
@@ -30,7 +30,7 @@ CLI::
30
30
  pygeofetch doctor
31
31
  """
32
32
 
33
- __version__ = "2.7.0.8.4"
33
+ __version__ = "2.7.1.0.4"
34
34
  __author__ = "PyGeoFetch Contributors"
35
35
  __license__ = "MIT"
36
36
 
@@ -202,6 +202,138 @@ def make_fingerprint(arguments: Dict[str, Any], settings: Dict[str, Any]) -> Dic
202
202
  return body
203
203
 
204
204
 
205
+ # ──────────────────────────────────────────────────────────────────────────
206
+ # Streaming cleanup (verify-then-delete) support for process_pairs.
207
+ #
208
+ # These helpers never touch the InSAR maths: they only inspect what
209
+ # process_pair() has already saved and decide when an input scene is no
210
+ # longer needed.
211
+ # ──────────────────────────────────────────────────────────────────────────
212
+
213
+ # process_pair() arguments that name scene data which streaming_cleanup may
214
+ # delete once every pair using them has been saved AND verified. Orbit files
215
+ # and the DEM are small / shared and are never deleted.
216
+ _CLEANUP_INPUT_KEYS = ("reference", "secondary", "reference_safe_zip", "secondary_safe_zip")
217
+
218
+ # Written next to result.json after a verified save. It records a fingerprint of
219
+ # everything EXCEPT the scene paths, so a later resume can still recognise the pair
220
+ # as current after those scenes have been deleted (the regular fingerprint hashes
221
+ # the input files themselves, and cannot be rebuilt once they are gone).
222
+ _CLEANUP_MARKER = "streaming_cleanup.json"
223
+
224
+ # A saved pair needs at least this share of valid coherence pixels to verify.
225
+ _MIN_VALID_FRACTION = 0.01
226
+
227
+
228
+ def _verify_saved_pair(folder: Union[str, Path]) -> "tuple[bool, str]":
229
+ """
230
+ The *verify* step of verify-then-delete, run on what process_pair() saved.
231
+
232
+ Checks result.json parses, wrapped_phase/coherence/amplitude GeoTIFFs open
233
+ as one band with identical non-empty shape, interferogram_complex.npy has
234
+ that same shape, geometry.pkl exists when result.json says it should, the
235
+ coherence holds valid (>= 0) values that are not all zero, and the complex
236
+ interferogram is not empty. Reads are decimated, so it is cheap on large
237
+ pairs. Returns (ok, reason).
238
+ """
239
+ import json
240
+
241
+ import numpy as np
242
+
243
+ folder = Path(folder)
244
+ try:
245
+ side = json.loads((folder / _RESULT_JSON).read_text())
246
+ except (OSError, ValueError) as exc:
247
+ return False, f"{_RESULT_JSON} unreadable ({exc})"
248
+
249
+ try:
250
+ import rasterio
251
+
252
+ shapes = {}
253
+ coh = None
254
+ for name in ("wrapped_phase", "coherence", "amplitude"):
255
+ with rasterio.open(folder / f"{name}.tif") as ds:
256
+ if ds.count != 1 or ds.height < 1 or ds.width < 1:
257
+ return False, f"{name}.tif has unexpected shape"
258
+ shapes[name] = (ds.height, ds.width)
259
+ if name == "coherence":
260
+ step = max(1, max(ds.height, ds.width) // 1024)
261
+ coh = ds.read(1, out_shape=(max(1, ds.height // step), max(1, ds.width // step)))
262
+ if len(set(shapes.values())) != 1:
263
+ return False, f"product shapes disagree: {shapes}"
264
+ shape = shapes["coherence"]
265
+ cplx = np.load(folder / "interferogram_complex.npy", mmap_mode="r")
266
+ if tuple(cplx.shape) != tuple(shape):
267
+ return False, f"interferogram_complex.npy shape {tuple(cplx.shape)} != {shape}"
268
+ step = max(1, max(shape) // 1024)
269
+ sample = np.asarray(cplx[::step, ::step])
270
+ if side.get("has_geometry") and not (folder / "geometry.pkl").is_file():
271
+ return False, "geometry.pkl is missing"
272
+ except Exception as exc: # noqa: BLE001 - any read failure means "not verified"
273
+ return False, f"could not read saved products ({exc})"
274
+
275
+ valid = np.isfinite(coh) & (coh >= 0)
276
+ if valid.mean() < _MIN_VALID_FRACTION:
277
+ return False, f"only {valid.mean():.2%} valid coherence pixels"
278
+ if not np.any(coh[valid] > 0):
279
+ return False, "coherence is all zero"
280
+ if not np.any(np.isfinite(sample) & (np.abs(sample) > 0)):
281
+ return False, "interferogram is empty"
282
+ return True, "ok"
283
+
284
+
285
+ def _write_cleanup_marker(folder: Union[str, Path], params_hash: str) -> None:
286
+ """Atomically record the scene-independent fingerprint of a verified pair."""
287
+ import json
288
+
289
+ folder = Path(folder)
290
+ tmp = folder / (_CLEANUP_MARKER + ".tmp")
291
+ tmp.write_text(json.dumps({"params_hash": params_hash, "pipeline_version": PIPELINE_VERSION}))
292
+ tmp.replace(folder / _CLEANUP_MARKER)
293
+
294
+
295
+ def _read_cleanup_marker(folder: Union[str, Path]) -> Optional[Dict[str, Any]]:
296
+ import json
297
+
298
+ try:
299
+ return json.loads((Path(folder) / _CLEANUP_MARKER).read_text())
300
+ except (OSError, ValueError):
301
+ return None
302
+
303
+
304
+ def _delete_input(path: str, protect: Path) -> bool:
305
+ """
306
+ Delete one input scene file, then its parent folder if that is now empty.
307
+
308
+ Directories are never removed recursively (an input given as a folder is
309
+ left alone with a warning), nothing inside ``protect`` (the results
310
+ folder) is touched, and a failure only logs: the pair's results are
311
+ already safe on disk.
312
+ """
313
+ import os
314
+
315
+ p = Path(path)
316
+ try:
317
+ if not p.exists():
318
+ return False
319
+ if p.is_dir():
320
+ logger.warning("streaming_cleanup: %s is a directory; not deleting it", p)
321
+ return False
322
+ if protect.resolve() in p.resolve().parents:
323
+ logger.warning("streaming_cleanup: %s is inside the results folder; not deleting it", p)
324
+ return False
325
+ p.unlink()
326
+ logger.info("streaming_cleanup: deleted %s", p.name)
327
+ try:
328
+ os.rmdir(p.parent) # succeeds only when the folder is empty
329
+ except OSError:
330
+ pass
331
+ return True
332
+ except OSError as exc:
333
+ logger.warning("streaming_cleanup: could not delete %s (%s)", p, exc)
334
+ return False
335
+
336
+
205
337
  @dataclass
206
338
  class InterferogramResult:
207
339
  """Result of interferogram formation for one SLC pair."""
@@ -1644,6 +1776,40 @@ class InterferogramGenerator:
1644
1776
  return saved.get("hash") == self.pair_fingerprint(
1645
1777
  reference_date=reference_date, secondary_date=secondary_date, **process_pair_kwargs)["hash"]
1646
1778
 
1779
+ def _pair_params_hash(self, kw: Dict[str, Any]) -> str:
1780
+ """Fingerprint hash of a pair's dates, settings and non-scene inputs (orbit files, DEM, options),
1781
+ deliberately excluding the scene paths that streaming_cleanup deletes. See _CLEANUP_MARKER."""
1782
+ import inspect
1783
+
1784
+ bound = inspect.signature(self.process_pair).bind(**kw)
1785
+ bound.apply_defaults()
1786
+ args = {k: v for k, v in bound.arguments.items() if k not in _CLEANUP_INPUT_KEYS}
1787
+ return self._pair_fingerprint(args)["hash"]
1788
+
1789
+ def _resume_state(self, out: Path, kw: Dict[str, Any], verify: bool):
1790
+ """Decide whether one pair can be skipped. Returns (current, reason, via_marker).
1791
+
1792
+ The regular fingerprint check is tried first. If it fails only because streaming_cleanup already
1793
+ deleted the scenes, the marker written at the time of cleanup is accepted instead, provided its
1794
+ scene-independent hash still matches. A pair is only called current when its saved products also
1795
+ verify (always when scenes are gone or verify=True; the plain resume path is unchanged)."""
1796
+ rd, sd = kw["reference_date"], kw["secondary_date"]
1797
+ folder = out / f"{rd}_{sd}"
1798
+ pair_kw = {k: v for k, v in kw.items() if k not in ("reference_date", "secondary_date")}
1799
+ current = self.is_pair_current(out, rd, sd, **pair_kw)
1800
+ via_marker = False
1801
+ if not current:
1802
+ scenes_gone = any(kw.get(k) is not None and not Path(str(kw[k])).exists()
1803
+ for k in _CLEANUP_INPUT_KEYS)
1804
+ marker = _read_cleanup_marker(folder) if scenes_gone else None
1805
+ if marker and marker.get("params_hash") == self._pair_params_hash(kw):
1806
+ current = via_marker = True
1807
+ if current and (verify or via_marker):
1808
+ ok, why = _verify_saved_pair(folder)
1809
+ if not ok:
1810
+ return False, f"saved products failed verification ({why})", via_marker
1811
+ return current, "", via_marker
1812
+
1647
1813
  def process_pairs(
1648
1814
  self,
1649
1815
  pairs,
@@ -1651,6 +1817,8 @@ class InterferogramGenerator:
1651
1817
  resume: bool = True,
1652
1818
  keep_results: bool = False,
1653
1819
  stop_on_error: bool = False,
1820
+ streaming_cleanup: bool = False,
1821
+ keep_inputs=None,
1654
1822
  **common_kwargs,
1655
1823
  ):
1656
1824
  """Process many pairs one after another, saving each under output_dir/<ref>_<sec>.
@@ -1659,72 +1827,153 @@ class InterferogramGenerator:
1659
1827
  reference_date, secondary_date, ... ). common_kwargs apply to every pair; a pair's own dict wins.
1660
1828
  resume: pairs whose folder already holds a complete save made with the same inputs and settings
1661
1829
  are skipped before any SLC is opened (checked with the same fingerprint process_pair stores).
1830
+ With streaming_cleanup the saved products are also verified first, and a pair whose scenes
1831
+ were deleted by an earlier cleanup is still recognised (see _CLEANUP_MARKER).
1662
1832
  keep_results: False (default) keeps only a small record per pair, so memory stays flat however many
1663
1833
  pairs run; True also returns each InterferogramResult (loaded from disk for skipped pairs).
1664
1834
  stop_on_error: False records the failure and carries on with the next pair.
1835
+ streaming_cleanup: False (default) changes nothing. True applies verify-then-delete to the
1836
+ INPUTS of each pair (reference / secondary extracted SLCs and reference_safe_zip /
1837
+ secondary_safe_zip):
1838
+ try process_pair() as before, saving to output_dir/<ref>_<sec>;
1839
+ verify re-open the saved products (shape, validity, not empty);
1840
+ delete an input is deleted only once EVERY pair in this call that uses it has been saved
1841
+ and verified, so a scene shared by several pairs survives until its last pair;
1842
+ except the error is recorded and the inputs of that pair are KEPT (so is any scene the
1843
+ failed pair shares with others);
1844
+ finally gc.collect().
1845
+ Deleted inputs cannot be recomputed from: to redo a pair, re-download its scenes. Pairs in other
1846
+ calls are not known to this one, so either pass all the pairs that need a scene in ONE call, or
1847
+ name the scenes a LATER call still needs in keep_inputs.
1848
+ Orbit files and the DEM are never deleted.
1849
+ keep_inputs: paths (extracted SLCs or zips) that streaming_cleanup must not delete in this call. For
1850
+ a rolling run, one pair per call, pass the scenes the next pair shares with this one; they are
1851
+ then freed by the call that finishes their last pair.
1665
1852
 
1666
1853
  Returns a list of records: reference_date, secondary_date, status ("skipped: already generated",
1667
1854
  "computed", "failed"), folder, metadata (the pair's summary, loaded from result.json when skipped),
1668
- error, and result (only with keep_results). The decision for every pair is printed, so a run that
1669
- did not skip anything says so.
1855
+ error, deleted (inputs removed after this pair, streaming_cleanup only) and result (only with
1856
+ keep_results). The decision for every pair is printed, so a run that did not skip anything says so.
1670
1857
  """
1671
1858
  import gc
1672
1859
  import json
1860
+ import os
1673
1861
 
1674
1862
  out = Path(output_dir)
1675
1863
  pairs = list(pairs)
1676
1864
  records = []
1677
1865
  n_skip = n_done = n_fail = 0
1678
- print(f"process_pairs: {len(pairs)} pairs, output_dir={out}, resume={resume}")
1679
- for i, spec in enumerate(pairs, 1):
1866
+ print(f"process_pairs: {len(pairs)} pairs, output_dir={out}, resume={resume}"
1867
+ + (", streaming_cleanup=True" if streaming_cleanup else ""))
1868
+
1869
+ specs = []
1870
+ for spec in pairs:
1680
1871
  kw = {**common_kwargs, **spec}
1681
- rd, sd = kw.get("reference_date"), kw.get("secondary_date")
1682
- if not (rd and sd):
1872
+ if not (kw.get("reference_date") and kw.get("secondary_date")):
1683
1873
  raise InputError("input", "every pair needs reference_date and secondary_date")
1874
+ specs.append(kw)
1875
+
1876
+ # Streaming bookkeeping. pending[input] = indices of pairs that still need that input; an input
1877
+ # becomes deletable when its set is empty. A pair leaves the sets only once its results are
1878
+ # saved and verified, so a failed pair pins every input it uses.
1879
+ pending: Dict[str, set] = {}
1880
+ states: Dict[int, Any] = {}
1881
+ if streaming_cleanup:
1882
+ for i, kw in enumerate(specs):
1883
+ for key in _CLEANUP_INPUT_KEYS:
1884
+ if kw.get(key) is not None:
1885
+ pending.setdefault(os.path.abspath(str(kw[key])), set()).add(i)
1886
+
1887
+ for held in (keep_inputs or ()) if streaming_cleanup else ():
1888
+ held = os.path.abspath(str(held))
1889
+ if held in pending:
1890
+ pending[held].add(-1) # -1 is never finished: this call leaves the file alone
1891
+
1892
+ def _finish(i: int) -> list:
1893
+ """Pair i is saved and verified: release its inputs and delete those nobody else needs."""
1894
+ deleted = []
1895
+ for key in _CLEANUP_INPUT_KEYS:
1896
+ if specs[i].get(key) is None:
1897
+ continue
1898
+ path = os.path.abspath(str(specs[i][key]))
1899
+ pending[path].discard(i)
1900
+ if not pending[path] and _delete_input(path, protect=out):
1901
+ deleted.append(path)
1902
+ return deleted
1903
+
1904
+ if streaming_cleanup and resume:
1905
+ # Decide every pair up front: pairs that are already done release their inputs straight away.
1906
+ for i, kw in enumerate(specs):
1907
+ try:
1908
+ states[i] = self._resume_state(out, kw, verify=True)
1909
+ except Exception as exc: # noqa: BLE001
1910
+ logger.warning("resume check failed for %s_%s (%s); computing it",
1911
+ kw["reference_date"], kw["secondary_date"], exc)
1912
+ for i, st in states.items():
1913
+ if st[0]:
1914
+ _finish(i)
1915
+
1916
+ for i, (kw, spec) in enumerate(zip(specs, pairs), 1):
1917
+ rd, sd = kw["reference_date"], kw["secondary_date"]
1684
1918
  folder = out / f"{rd}_{sd}"
1685
1919
  rec = {"reference_date": rd, "secondary_date": sd, "folder": folder, "status": None,
1686
1920
  "metadata": None, "error": None, "result": None}
1921
+ if streaming_cleanup:
1922
+ rec["deleted"] = []
1687
1923
  tag = f"[{i}/{len(pairs)}] {rd} -> {sd}"
1688
- current = False
1689
- if resume:
1690
- try:
1691
- current = self.is_pair_current(out, rd, sd, **{k: v for k, v in kw.items()
1692
- if k not in ("reference_date", "secondary_date")})
1693
- except Exception as exc: # noqa: BLE001
1694
- logger.warning("resume check failed for %s_%s (%s); computing it", rd, sd, exc)
1695
- if current:
1696
- rec["status"] = "skipped: already generated"
1697
- try:
1698
- rec["metadata"] = _restore(json.loads((folder / _RESULT_JSON).read_text()).get("metadata") or {})
1699
- if keep_results:
1700
- rec["result"] = InterferogramResult.load(folder)
1701
- except Exception as exc: # noqa: BLE001
1702
- logger.warning("could not read saved result for %s_%s (%s)", rd, sd, exc)
1703
- n_skip += 1
1704
- print(f"{tag}: {rec['status']}")
1705
- else:
1706
- why = "resume off" if not resume else (
1707
- "no complete save" if InterferogramResult.saved_fingerprint(folder) is None
1708
- else "saved with different inputs/settings/version")
1709
- print(f"{tag}: computing ({why})")
1710
- try:
1711
- res = self.process_pair(output_dir=out, resume=False, **kw)
1712
- rec["status"] = "computed"
1713
- rec["metadata"] = dict(res.metadata)
1714
- if keep_results:
1715
- rec["result"] = res
1716
- n_done += 1
1717
- del res
1718
- except Exception as exc: # noqa: BLE001
1719
- rec["status"] = "failed"
1720
- rec["error"] = f"{type(exc).__name__}: {exc}"
1721
- n_fail += 1
1722
- print(f"{tag}: FAILED {rec['error']}")
1723
- if stop_on_error:
1724
- records.append(rec)
1725
- raise
1726
- records.append(rec)
1727
- gc.collect()
1924
+ current, why_not = False, ""
1925
+ try:
1926
+ if resume:
1927
+ try:
1928
+ # Plain resume keeps its original cost; verification is added only for streaming runs
1929
+ # (or when the scenes are gone and the marker is all there is to go on).
1930
+ current, why_not, _ = states.get(i - 1) or self._resume_state(
1931
+ out, kw, verify=streaming_cleanup)
1932
+ except Exception as exc: # noqa: BLE001
1933
+ logger.warning("resume check failed for %s_%s (%s); computing it", rd, sd, exc)
1934
+ if current:
1935
+ rec["status"] = "skipped: already generated"
1936
+ try:
1937
+ rec["metadata"] = _restore(json.loads((folder / _RESULT_JSON).read_text()).get("metadata") or {})
1938
+ if keep_results:
1939
+ rec["result"] = InterferogramResult.load(folder)
1940
+ except Exception as exc: # noqa: BLE001
1941
+ logger.warning("could not read saved result for %s_%s (%s)", rd, sd, exc)
1942
+ n_skip += 1
1943
+ print(f"{tag}: {rec['status']}")
1944
+ else:
1945
+ why = why_not or ("resume off" if not resume else (
1946
+ "no complete save" if InterferogramResult.saved_fingerprint(folder) is None
1947
+ else "saved with different inputs/settings/version"))
1948
+ print(f"{tag}: computing ({why})")
1949
+ try:
1950
+ res = self.process_pair(output_dir=out, resume=False, **kw)
1951
+ rec["metadata"] = dict(res.metadata)
1952
+ if keep_results:
1953
+ rec["result"] = res
1954
+ del res
1955
+ if streaming_cleanup:
1956
+ ok, bad = _verify_saved_pair(folder)
1957
+ if not ok:
1958
+ raise RuntimeError(f"saved products failed verification ({bad}); "
1959
+ f"input scenes kept")
1960
+ _write_cleanup_marker(folder, self._pair_params_hash(kw))
1961
+ rec["deleted"] = _finish(i - 1)
1962
+ rec["status"] = "computed"
1963
+ n_done += 1
1964
+ except Exception as exc: # noqa: BLE001
1965
+ rec["status"] = "failed"
1966
+ rec["error"] = f"{type(exc).__name__}: {exc}"
1967
+ if streaming_cleanup:
1968
+ logger.error("%s: %s -- inputs of this pair kept", tag, rec["error"])
1969
+ n_fail += 1
1970
+ print(f"{tag}: FAILED {rec['error']}")
1971
+ if stop_on_error:
1972
+ records.append(rec)
1973
+ raise
1974
+ records.append(rec)
1975
+ finally:
1976
+ gc.collect()
1728
1977
  print(f"process_pairs: {n_skip} skipped, {n_done} computed, {n_fail} failed")
1729
1978
  return records
1730
1979