#!/usr/bin/env python3 """ Shaking history vs. scenario at the Agham spur (Ladakh). What this script does 1. Reads the USGS-style catalogue CSV (M>=4, 1902-2026) and the NOAA significant- earthquake JSON (historic / ancient events) and MERGES them into one event table. - nuclear explosions in the catalogue are dropped, - NOAA events after 1902 that are the same earthquake as a catalogue event are matched (date + location + magnitude) and counted ONCE. 2. Estimates median peak ground acceleration (PGA) at the spur for every merged event with the BSSA14 ground-motion model (rock, Vs30 = 760 m/s, strike-slip). 3. Compares that history with a scenario rupture on the Karakoram Fault. 4. Estimates Newmark sliding-block displacement (Jibson 2007) for debris on slopes. 5. Writes figures, per-event CSVs, a plain-text summary and a JSON file listing the earthquakes that matter for designing a building at the site. USAGE python quake_analysis_merged.py --catalog 4-to-10-further-away.csv \ --historic earthquakes.json --outdir out OUTPUTS (in --outdir) fig1_maps.png fig2_pga_history.png fig3_newmark.png fig4_completeness.png pga_per_event.csv every scored event (merged dataset) historic_by_distance.csv every NOAA event, with match status design_relevant_earthquakes.json events relevant to building design (see below) design_relevant_earthquakes.geojson the same events for GIS (QGIS, geojson.io) future_earthquake_forecast.json probabilistic forecast: hazard, probabilities, scenarios, slope table fig5_design_events_map.png fig6_recurrence.png fig7_hazard.png fig8_future_sources.png summary.txt GROUND-MOTION MODEL --gmpe auto use `pygmm` if installed, otherwise the embedded coefficients --gmpe pygmm require pygmm --gmpe embedded use the coefficients typed into this file (EMBEDDED_BSSA14) --gmpe both score with pygmm and print a cross-check against the embedded set The embedded coefficients were typed from the published table. They were cross-checked against pygmm (BooreStewartSeyhanAtkinson2014) in a separate environment (median PGA agrees to <1e-5 relative error at 49 magnitude-distance pairs, including M7.3 at 1.6 km = 0.459 g), but when pygmm is NOT installed the script labels its output UNVERIFIED because it cannot repeat that check itself. Run with --gmpe both on a machine with pygmm to confirm. Agreement with pygmm shows the equation is transcribed correctly, NOT that BSSA14 (a global shallow-crustal model) is adequate for a site 1.6 km from a Himalayan fault: the whole analysis still rests on this ONE ground-motion model (see LIMITS). FORECAST (screening-level PSHA; see run_forecast) Declustering (Gardner-Knopoff) -> Gutenberg-Richter fit by Weichert maximum likelihood with magnitude-dependent completeness -> smoothed-seismicity grid within 400 km -> BSSA14 hazard integration, plus a Karakoram Fault characteristic source whose rate comes from slip rate (rate = coupling x slip / average displacement). A logic tree covers b-value, Mmax, slip rate and characteristic magnitude (7.0-7.7). The slip-rate branches (0-4 mm/yr, see SLIP_BRANCHES) are for the Nubra sector where the site sits, and include a zero-slip (inactive) branch. The tree is also reported CONDITIONALLY on two explicit fault-activity hypotheses (HYPOTHESES: A active 2-4 mm/yr, B inactive/very low 0-1 mm/yr) with a governing envelope = max(A, B), so the answer does not hinge on the judgement weights between them. Ground-motion scatter is the BSSA14 magnitude/distance-dependent sigma (--sigma-model fixed restores 0.65), truncated two-sided at +/-3 sigma; Mmax branches are floored at the largest observed magnitude in the zone; the Gutenberg-Richter fit is reported with per-bin Poisson goodness-of-fit and an M>=6.5 tail check. Options: --smooth-km, --coupling, --completeness, --fault-trace, --sigma-model, and two SENSITIVITY options for catalogue magnitudes (--merge-mag, --mb-offset; defaults leave results unchanged). The M4.0-4.5 bin is excluded from the fit (incomplete). A split-sample back-test is printed. Only catalogue-sourced events enter the recurrence fit, the back-test and the spatial smoothing: NOAA-only records are a selected (damaging / notable) subset, not a complete sample, so they are excluded from rate estimation (the run prints how many such events fall in the zone). Uncertainty bands: the 16/84% columns are EPISTEMIC (spread across logic-tree branches), not the scatter of one earthquake's ground motion. They are weighted quantiles of the branch annual-exceedance-rate curves at each PGA level, which are then inverted at 1/T. Because branch curves can cross, the script also prints the alternative (invert each branch curve first, then take weighted quantiles of the branch PGAs). Disaggregation reports the Karakoram Fault SOURCE separately from background seismicity that happens to lie in the 0-10 km distance bin; the two are not the same thing. DESIGN-RELEVANCE RULES (design_relevant_earthquakes.json) An event is listed if ANY rule is true (thresholds are command-line options): A median PGA at the site >= --min-pga (default 0.02 g) B 84th-percentile PGA >= --min-pga84 (default 0.05 g) C M >= 6.0 within 200 km D M >= 7.0 within 500 km E M >= 5.0 within 100 km F listed in the NOAA significant-earthquake database within 500 km Each listed event carries the list of rules that selected it. The file also holds the scenario Karakoram Fault event and a list of very large events beyond the ground-motion model's range (context only, not scored). This is a screening list, NOT a hazard assessment. Design values must come from a site-specific PSHA/DSHA and the governing code. LIMITS (read before quoting any number) * Catalogue magnitudes are a mix of mb/Ms/Mw; they are treated as Mw. mb saturates for large events, so big events may be under-sized. When a catalogue event is also in NOAA, the larger of the two magnitudes is used. * Epicentre is the source location; for M>=6.5 a crude finite-fault correction (Rjb = epicentral distance - half the Wells & Coppersmith rupture length) is used. * BSSA14 is for shallow crustal earthquakes. For events deeper than 35 km (e.g. the Hindu Kush nest) the hypocentral distance is used as a rough proxy; treat as indicative. * BSSA14 is calibrated to about 400 km. Events farther away are not scored. * Event-by-event PGA values are medians; the 84th percentile is median * exp(sigma_ln) with the BSSA14 magnitude/distance-dependent sigma (a fixed 0.65 only with --sigma-model fixed). * Only ONE ground-motion model (BSSA14) is used; no Himalayan or other NGA-West2 branch, no spectral accelerations, no site response (rock, Vs30 = 760 m/s assumed, not measured), no directivity/fling. * Distances follow the BSSA14 definition (Rjb); no source depth is added. Events deeper than 35 km (about a fifth of the zone's events; many catalogue depths are defaults of 33 or 10 km) are flagged as outside BSSA14's shallow-crustal scope. The hazard grid uses a point-source distance plus a 0.38 x cell-width term (3.8 km) that represents the spread of sources inside a 10 km cell; it is not a source depth. All sources use the strike-slip equation. * The scoring cutoff (400 km) applies to the model distance Rjb, so a large event with an assumed magnitude can be scored even if its epicentre is slightly beyond 400 km (the 1827 Lahore event: 444 km epicentral, Rjb 399 km). * The finite-fault shortcut Rjb = Repi - L/2 needs no rupture strike, so it is the SMALLEST distance the rupture could have; it biases distances short (PGA high) for large events whose rupture does not point at the site. * The catalogue is incomplete for small events before ~1970 and in remote areas; the NOAA database lists only events that caused damage, deaths or other notable effects. """ import argparse import json import os import sys import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec import numpy as np import pandas as pd # -------------------------------------------------------------------------- # Constants (edit here) # -------------------------------------------------------------------------- SITE_LAT, SITE_LON = 34.317, 77.786 # spur, from 34d19'01"N 77d47'09"E SIGMA_LN = 0.65 # fixed screening sigma, used only with --sigma-model fixed SIGMA_MODEL = "bssa14" # "bssa14" (magnitude/distance dependent, default) or "fixed" BSSA14_MAX_KM = 400.0 # calibrated distance limit SCEN_RJB_KM = 1.6 # spur to Karakoram Fault (~1 mile) VS30_ROCK = 760.0 AC_LOOSE_DEBRIS_G = 0.05 # Wilson & Keefer (1985), incoherent material DEEP_KM = 35.0 # deeper than this -> hypocentral-distance proxy CATALOGUE_START = 1902 # first year of the instrumental catalogue MERGE_MAG_RULE = "max" # matched USGS/NOAA event: "max" = larger of the two magnitudes, "catalogue" = keep catalogue magnitude MB_OFFSET = 0.0 # sensitivity only: shift added to catalogue magnitudes of type mb (NOT a calibrated mb->Mw conversion) # BSSA14 PGA coefficients (strike-slip, rock). TYPED FROM MEMORY - VERIFY. EMBEDDED_BSSA14 = dict(e1=0.4856, e4=1.431, e5=0.05053, e6=-0.1662, Mh=5.5, c1=-1.134, c2=0.1917, c3=-0.008088, h=4.5) # -------------------------------------------------------------------------- # Geometry # -------------------------------------------------------------------------- def haversine_km(lat1, lon1, lat2, lon2): r = 6371.0 p1, p2 = np.radians(lat1), np.radians(lat2) dphi = p2 - p1 dl = np.radians(np.asarray(lon2) - lon1) a = np.sin(dphi / 2) ** 2 + np.cos(p1) * np.cos(p2) * np.sin(dl / 2) ** 2 return 2 * r * np.arcsin(np.sqrt(a)) def rupture_length_km(mag): """Wells & Coppersmith (1994), surface rupture length, all slip types.""" return 10 ** (-3.22 + 0.69 * np.asarray(mag, float)) def rjb_from_epicentre(mag, r_epi): mag = np.asarray(mag, float) r_epi = np.asarray(r_epi, float) return np.where(mag >= 6.5, np.maximum(r_epi - 0.5 * rupture_length_km(mag), 0.0), r_epi) def effective_distance(rjb, depth): """Distance fed to the GMPE: the Joyner-Boore distance Rjb, exactly as BSSA14 defines it (closest horizontal distance to the surface projection of the rupture). No source depth is added: BSSA14 already contains its own pseudo-depth term h, and adding a hypocentral depth to Rjb would be inconsistent with the model's definition. Events deeper than DEEP_KM are still scored (with Rjb) but flagged, because BSSA14 is a shallow-crustal model and its use for them is indicative only.""" return np.asarray(rjb, float) # -------------------------------------------------------------------------- # Ground motion # -------------------------------------------------------------------------- # BSSA14 total standard deviation for PGA (Boore et al. 2014, between-event tau and within-event phi), rock (Vs30 >= 300 # m/s so no site-dependent phi term). Coefficients typed from the published table and cross-checked against pygmm # (BooreStewartSeyhanAtkinson2014, 0.01 s) to within ~0.005 at (M7.3, 1.6 km), (M5, 20 km), (M4.2, 50 km), (M7.9, 150 km). _PHI1, _PHI2, _TAU1, _TAU2, _R1, _R2, _DPHIR = 0.695, 0.495, 0.398, 0.348, 110.0, 270.0, 0.100 def sigma_ln(mag, rjb): """Total ln sigma of BSSA14 PGA at magnitude `mag` and Joyner-Boore distance `rjb` (km); broadcasts. With --sigma-model fixed it returns the constant SIGMA_LN instead.""" mag, rjb = np.broadcast_arrays(np.asarray(mag, float), np.asarray(rjb, float)) if SIGMA_MODEL == "fixed": return np.full(mag.shape, SIGMA_LN) f = np.clip(mag - 4.5, 0.0, 1.0) # 0 at M<=4.5, 1 at M>=5.5 phi_m = _PHI1 + (_PHI2 - _PHI1) * f tau = _TAU1 + (_TAU2 - _TAU1) * f r = np.clip(rjb, _R1, _R2) phi = phi_m + _DPHIR * np.log(r / _R1) / np.log(_R2 / _R1) return np.sqrt(phi ** 2 + tau ** 2) def scen_factor(mag): """exp(sigma) at the scenario geometry: multiplies the median to give the 84th-percentile PGA.""" return float(np.exp(sigma_ln(mag, SCEN_RJB_KM))) def pga_embedded(mag, rjb): c = EMBEDDED_BSSA14 mag = np.asarray(mag, float) rjb = np.asarray(rjb, float) fe = np.where(mag <= c["Mh"], c["e1"] + c["e4"] * (mag - c["Mh"]) + c["e5"] * (mag - c["Mh"]) ** 2, c["e1"] + c["e6"] * (mag - c["Mh"])) r = np.sqrt(rjb ** 2 + c["h"] ** 2) fp = (c["c1"] + c["c2"] * (mag - 4.5)) * np.log(r) + c["c3"] * (r - 1.0) return np.exp(fe + fp) # in g def pga_pygmm(mag, rjb, vs30=VS30_ROCK): import pygmm out = np.empty(len(mag)) for i, (m, r) in enumerate(zip(mag, rjb)): scen = pygmm.Scenario(mag=float(m), dist_jb=float(r), v_s30=vs30, mechanism="SS") out[i] = pygmm.BooreStewartSeyhanAtkinson2014(scen).pga return out def pga(mag, rjb, mode): mag = np.atleast_1d(mag) rjb = np.atleast_1d(rjb) if mode == "embedded": return pga_embedded(mag, rjb) if mode == "pygmm": return pga_pygmm(mag, rjb) raise ValueError(mode) def choose_mode(requested): have_pygmm = True try: import pygmm # noqa: F401 except Exception: have_pygmm = False if requested == "auto": return ("pygmm" if have_pygmm else "embedded"), have_pygmm if requested in ("pygmm", "both") and not have_pygmm: sys.exit("pygmm requested but not installed: pip install pygmm") return ("embedded" if requested == "embedded" else "pygmm"), have_pygmm # -------------------------------------------------------------------------- # Newmark (Jibson 2007, eq. 8: critical-acceleration ratio and magnitude) # -------------------------------------------------------------------------- def newmark_cm(ac_g, amax_g, mag): ac_g = np.asarray(ac_g, float) ratio = ac_g / amax_g ok = ratio < 1.0 out = np.zeros_like(ratio) r = ratio[ok] out[ok] = 10 ** (-2.710 + np.log10((1 - r) ** 2.335 * r ** -1.478) + 0.424 * mag) return out # -------------------------------------------------------------------------- # Data loading and merging # -------------------------------------------------------------------------- def load_catalogue(path): df = pd.read_csv(path, parse_dates=["time"]) n_raw = len(df) df = df.drop_duplicates(subset="id").copy() n_dup = n_raw - len(df) n_nonquake = int((df["type"] != "earthquake").sum()) if "type" in df else 0 if "type" in df: df = df[df["type"] == "earthquake"].copy() # drop nuclear explosions etc. df["time"] = df["time"].dt.tz_convert("UTC").dt.tz_localize(None) if df["time"].dt.tz is not None else df["time"] return df.reset_index(drop=True), dict(raw=n_raw, duplicates=n_dup, non_earthquakes=n_nonquake) def load_historic(path): with open(path) as fh: raw = json.load(fh) items = pd.DataFrame(raw["items"]) meta = {k: raw[k] for k in raw if k != "items"} meta["n_items"] = len(items) mag = items["eqMagnitude"].copy() for alt in ("eqMagMw", "eqMagMs", "eqMagMb", "eqMagUnk"): if alt in items: mag = mag.fillna(items[alt]) items["mag"] = mag for col in ("month", "day", "intensity", "deaths", "eqDepth"): if col not in items: items[col] = np.nan n_no_coord = int((items.latitude.isna() | items.longitude.isna()).sum()) meta["n_no_coords"] = n_no_coord items = items[items.latitude.notna() & items.longitude.notna()].copy() items["year_f"] = items["year"] + (items["month"].fillna(6) - 0.5) / 12.0 return items.reset_index(drop=True), meta def noaa_label(r): y = int(r["year"]) if pd.notna(r["month"]) and pd.notna(r["day"]): return f"{y}-{int(r['month']):02d}-{int(r['day']):02d}" if pd.notna(r["month"]): return f"{y}-{int(r['month']):02d}" return f"{y}" def match_noaa_to_catalogue(hist, cat, max_km=200.0, max_dmag=1.5): """For each NOAA event after the catalogue start, find the same earthquake in the catalogue. Returns an array of catalogue row positions (-1 = no match).""" epoch = np.datetime64("1970-01-01T00:00:00") cat_days = ((cat["time"].values - epoch) / np.timedelta64(1, "D")).astype(float) out = np.full(len(hist), -1, dtype=int) for i, r in hist.iterrows(): if r["year"] < CATALOGUE_START: continue y = int(r["year"]) if pd.notna(r["month"]) and pd.notna(r["day"]): c = (np.datetime64(f"{y:04d}-{int(r['month']):02d}-{int(r['day']):02d}") - epoch) / np.timedelta64(1, "D") win = 2.0 elif pd.notna(r["month"]): c = (np.datetime64(f"{y:04d}-{int(r['month']):02d}-15") - epoch) / np.timedelta64(1, "D") win = 17.0 else: c = (np.datetime64(f"{y:04d}-07-01") - epoch) / np.timedelta64(1, "D") win = 184.0 cand = np.where(np.abs(cat_days - c) <= win)[0] if len(cand) == 0: continue d = haversine_km(r["latitude"], r["longitude"], cat.latitude.values[cand], cat.longitude.values[cand]) ok = d <= max_km if pd.notna(r["mag"]): ok &= np.abs(cat["mag"].values[cand] - r["mag"]) <= max_dmag if ok.any(): cand, d = cand[ok], d[ok] out[i] = cand[np.argmin(d)] return out def build_merged(cat, hist): """One row per earthquake. Columns documented below.""" m = match_noaa_to_catalogue(hist, cat) hist = hist.copy() hist["cat_pos"] = m c = pd.DataFrame({ "source": "USGS", "event_id": cat["id"].values, "date": cat["time"].dt.strftime("%Y-%m-%d %H:%M:%S").values, "year_f": (cat["time"].dt.year + (cat["time"].dt.dayofyear - 1) / 365.25).values, "lat": cat.latitude.values, "lon": cat.longitude.values, "depth": cat.depth.values, "mag": cat.mag.values, "mag_type": cat.magType.values, "mag_assumed": False, "place": cat.place.values, "noaa_intensity": np.nan, "noaa_deaths": np.nan, "noaa_mag": np.nan, "noaa_name": None, }) for i, r in hist[hist.cat_pos >= 0].iterrows(): # matched: enrich the catalogue row k = int(r["cat_pos"]) c.loc[k, "source"] = "USGS+NOAA" c.loc[k, "noaa_mag"] = r["mag"] c.loc[k, "noaa_intensity"] = r["intensity"] c.loc[k, "noaa_deaths"] = r["deaths"] c.loc[k, "noaa_name"] = r["locationName"] if MERGE_MAG_RULE == "max" and pd.notna(r["mag"]) and r["mag"] > c.loc[k, "mag"]: c.loc[k, "mag"] = r["mag"] c.loc[k, "mag_type"] = "NOAA(max)" only = hist[hist.cat_pos < 0] h = pd.DataFrame({ "source": "NOAA", "event_id": ["noaa-" + str(x) for x in only["id"].values], "date": [noaa_label(r) for _, r in only.iterrows()], "year_f": only["year_f"].values, "lat": only.latitude.values, "lon": only.longitude.values, "depth": only.eqDepth.values, "mag": only["mag"].values, "mag_type": "NOAA", "mag_assumed": only["mag"].isna().values, "place": only.locationName.values, "noaa_intensity": only.intensity.values, "noaa_deaths": only.deaths.values, "noaa_mag": only["mag"].values, "noaa_name": only.locationName.values, }) allev = pd.concat([c, h], ignore_index=True) return allev, hist def add_distances_and_pga(ev, assume_mag, mode): ev = ev.copy() ev["mag_used"] = ev["mag"].fillna(assume_mag) ev["r_epi"] = haversine_km(SITE_LAT, SITE_LON, ev.lat.values, ev.lon.values) ev["rjb"] = rjb_from_epicentre(ev["mag_used"], ev["r_epi"]) ev["r_eff"] = effective_distance(ev["rjb"], ev["depth"]) ev["scored"] = ev["r_eff"] <= BSSA14_MAX_KM ev["pga_g"] = np.nan ev["pga84_g"] = np.nan s = ev["scored"].values ev.loc[s, "pga_g"] = pga(ev.loc[s, "mag_used"].values, ev.loc[s, "r_eff"].values, mode) ev["sigma_ln"] = sigma_ln(ev["mag_used"].values, ev["rjb"].values) ev["pga84_g"] = ev["pga_g"] * np.exp(ev["sigma_ln"]) return ev # -------------------------------------------------------------------------- # Design-relevance selection # -------------------------------------------------------------------------- def relevance_reasons(r, a): why = [] if r.scored and r.pga_g >= a.min_pga: why.append(f"A: median PGA {r.pga_g:.3f} g >= {a.min_pga} g") if r.scored and r.pga84_g >= a.min_pga84: why.append(f"B: 84th-percentile PGA {r.pga84_g:.3f} g >= {a.min_pga84} g") if r.mag_used >= 6.0 and r.r_epi <= 200: why.append("C: M>=6 within 200 km") if r.mag_used >= 7.0 and r.r_epi <= 500: why.append("D: M>=7 within 500 km") if r.mag_used >= 5.0 and r.r_epi <= 100: why.append("E: M>=5 within 100 km") if r.source in ("NOAA", "USGS+NOAA") and r.r_epi <= 500: why.append("F: NOAA significant (damaging/notable) earthquake within 500 km") return why def clean(v): if isinstance(v, (np.floating, float)): return None if not np.isfinite(v) else round(float(v), 4) if isinstance(v, (np.integer,)): return int(v) if isinstance(v, (np.bool_,)): return bool(v) if v is None or (isinstance(v, float) and np.isnan(v)): return None return v def write_design_json(path, ev, args, mode, scen_pga, max_hist, scen_table): rel = [] for _, r in ev.iterrows(): why = relevance_reasons(r, args) if why: rel.append((r, why)) rel.sort(key=lambda t: (-(t[0].pga_g if t[0].scored else -1), t[0].r_epi)) events = [] for rank, (r, why) in enumerate(rel, 1): note = [] if r.mag_assumed: note.append(f"no magnitude in source; scored at assumed bounding M{args.assume_hist_mag}") if str(r.mag_type) in ("mb", "Mb", "mB") and r.mag_used >= 5.8: note.append("mb magnitude saturates for large events; true Mw may be higher") if np.isfinite(r.depth) and r.depth > DEEP_KM: note.append("deeper than 35 km: outside the shallow-crustal scope of BSSA14; scored with Rjb only, indicative") if not r.scored: note.append(f"beyond {BSSA14_MAX_KM:.0f} km: not scored by the ground-motion model") events.append({ "rank_by_pga": rank, "source": r.source, "event_id": r.event_id, "date": r.date, "latitude": clean(r.lat), "longitude": clean(r.lon), "depth_km": clean(r.depth), "magnitude": clean(r.mag_used), "magnitude_type": clean(r.mag_type), "magnitude_assumed": bool(r.mag_assumed), "place": clean(r.place), "epicentral_distance_km": clean(r.r_epi), "rjb_km": clean(r.rjb), "distance_used_for_gmpe_km": clean(r.r_eff) if r.scored else None, "median_pga_g": clean(r.pga_g), "pga_84th_percentile_g": clean(r.pga84_g), "noaa_intensity": clean(r.noaa_intensity), "noaa_deaths": clean(r.noaa_deaths), "selected_by": why, "notes": note, }) beyond = ev[(~ev.scored) & (ev.mag_used >= 7.5) & (ev.r_epi <= 1000)].sort_values("r_epi") out = { "purpose": "Earthquakes relevant to designing a building at the site. Screening list only: " "design values must come from a site-specific hazard assessment and the governing code.", "site": {"name": "Agham spur, Ladakh", "latitude": SITE_LAT, "longitude": SITE_LON, "reference_condition": f"rock, Vs30 = {VS30_ROCK:.0f} m/s"}, "method": { "ground_motion_model": "BSSA14 PGA, strike-slip, rock (" + mode + " implementation)" + ("; embedded coefficients UNVERIFIED" if mode == "embedded" else ""), "sigma_ln": SIGMA_LN, "max_distance_km": BSSA14_MAX_KM, "selection_rules": { "A": f"median PGA >= {args.min_pga} g", "B": f"84th-percentile PGA >= {args.min_pga84} g", "C": "M>=6 within 200 km", "D": "M>=7 within 500 km", "E": "M>=5 within 100 km", "F": "NOAA significant earthquake within 500 km"}, "dataset": "USGS-style catalogue and NOAA significant earthquakes merged; duplicates counted once", }, "summary": { "events_listed": len(events), "largest_scored_median_pga_g": clean(max_hist), "scenario_median_pga_g": clean(scen_pga), }, "scenario_event": { "description": f"Karakoram Fault rupture, M{args.scenario_mag}, Rjb {SCEN_RJB_KM} km", "magnitude": args.scenario_mag, "rjb_km": SCEN_RJB_KM, "median_pga_g": clean(scen_pga), "pga_84th_percentile_g": clean(scen_pga * scen_factor(args.scenario_mag)), "sensitivity_median_pga_g": scen_table, }, "events": events, "large_events_beyond_model_range_context_only": [ {"date": r.date, "magnitude": clean(r.mag_used), "place": clean(r.place), "epicentral_distance_km": clean(r.r_epi), "source": r.source, "note": "not scored; long-period shaking possible"} for _, r in beyond.iterrows()], } with open(path, "w") as fh: json.dump(out, fh, indent=2, ensure_ascii=False) return len(events) # -------------------------------------------------------------------------- # Probabilistic forecast (PSHA): declustering, recurrence, hazard, disaggregation # -------------------------------------------------------------------------- try: from scipy.special import ndtr except Exception: # pragma: no cover from math import erf def ndtr(z): return 0.5 * (1 + np.vectorize(erf)(np.asarray(z, float) / np.sqrt(2))) ZONE_KM = 400.0 # source zone radius (limit of the ground-motion model) PAD_KM = 150.0 # extra radius used for declustering / smoothing GRID_KM = 10.0 # grid spacing of the smoothed-seismicity source M0_FIT = 4.0 # lower edge of the recurrence fit FIT_EDGES = np.arange(4.0, 8.01, 0.5) HAZ_EDGES = np.round(np.arange(4.5, 8.31, 0.1), 2) # hazard magnitude bins (min design M = 4.5) # Completeness year for each 0.5-magnitude bin (key = lower edge), read from the decade counts # in the merged catalogue (M>=4.5: jump in the 1970s; M>=5: ~1964; M>=5.5: ~1930; M>=6: ~1904). # The M4.0-4.5 bin is EXCLUDED (None): its observed rate is below that of M4.5-5, i.e. the catalogue is # incomplete there for this remote region, and including it flattens the b-value. COMPLETENESS = {4.0: None, 4.5: 1973, 5.0: 1964, 5.5: 1930, 6.0: 1904, 6.5: 1902, 7.0: 1902, 7.5: 1902} # Karakoram Fault slip rate at the site, mm/yr (revised). # The site (Agham) is in the NUBRA sector of the fault. # Evidence for the Nubra / northern sector (verification status in brackets): # Mohanty et al. 2024 (EPSL 626, 118512) continuous GPS: Nubra valley (K2 segment of the northern KF) inactive; # Bangong-Chaxikang (southern KF) 1.6-3.2 mm/yr, on the Pangong strand; the Tangtse strand # takes no slip. [abstract checked] # Wang & Elliott et al. 2026 (GRL 53, e2026GL123891) GNSS+InSAR block model: northern KF (~36.2-37N) <1 mm/yr; middle and # southern (~30.5-35N) of the order of 2-4 mm/yr. The authors caution that strong coupling on the # Main Frontal Thrust may bias the inferred KF rate and that it may not equal the long-term rate. # [northern <1 mm/yr and the caveat checked; the middle/southern value was truncated in the text # I could reach, so 2-4 is taken from the critique]. The site (34.32N) lies in the 2-4 band by LATITUDE, # but that is a regional block-model rate, not a measurement on the strand 1.6 km from the site. # Brown et al. 2002 (JGR 107) cosmogenic dating of offset debris flows/moraines in Ladakh: 4 +/- 1 mm/yr. [checked] A # geological rate for the Pangong-Tangtse sector, not a measurement at the site. # Bohon et al. (c. 2010) "A New Quaternary Strand of the Karakoram Fault System, Ladakh Himalayas": Quaternary offsets in # the Tangyar valley; slip rate undetermined at the time of the abstract. [abstract checked; the # claim that Tangyar lies ~10 km from the site was NOT verified] # Wang & Shen 2020 continental-China GPS: northern KF ~0, southern ~3 mm/yr (NOT independent of the GPS data used # in the analyses Mohanty discusses; do not count as a 2nd confirmation) # Ojha 2026 (J. Struct. Geol. 207, 105695) "Stop-and-go tectonics ...": segmented, episodic kinematic readjustment, last # event ~0.5 Ma (an inferred structural age, not a dated rupture at Agham). [abstract checked] # Imsong et al. 2017 (Current Science) Nubra/Shyok morphometric study. The statement that 37-42 m stream deflections at Agham imply # ~4 mm/yr with circular ages could NOT be verified; it is NOT used as evidence here. # so 0 mm/yr is a live branch, and 4 mm/yr (the Brown et al. geological rate) is the cap. Which strand lies 1.6 km from the site, and # whether it is the inactive Nubra/K2 strand, an active parallel Quaternary strand, or something else, is NOT settled by this literature. # The weights are a judgement call, not a measurement: edit them and re-run. SLIP_BRANCHES = [(0.0, 0.15), (1.0, 0.20), (2.0, 0.30), (3.0, 0.25), (4.0, 0.10)] # mm/yr, mean ~1.95 # Fault-activity hypotheses (explicit epistemic alternatives; see run_forecast). Slip rates must appear in SLIP_BRANCHES. # A: the Agham reach slips at the regional rate (Wang 2026 2-4 mm/yr band; Mohanty 2024 southern segment; Brown 2002 4 mm/yr cap) # B: inactive / very low slip, i.e. the Nubra K2 result extends to the site (Mohanty 2024; Ojha 2026) # The weight of each hypothesis is implied by SLIP_BRANCHES and is a judgement; the conditional curves and their # envelope (max of A and B) are reported so the design number does not depend on it. HYPOTHESES = {"A_active_2to4": (2.0, 3.0, 4.0), "B_inactive_or_very_low_0to1": (0.0, 1.0)} # characteristic magnitude on the fault; 7.7 is an assumed upper-magnitude alternative (a potential magnitude, not a measured # rupture or recurrence; its attribution to a Wang 2026 fault-length / moment analysis was NOT verified). The branches are # ALTERNATIVES, not summed events. MCHAR_BRANCHES = [(7.0, 0.25), (7.3, 0.35), (7.6, 0.25), (7.7, 0.15)] MMAX_BRANCHES = [(7.5, 0.3), (7.9, 0.5), (8.3, 0.2)] # maximum magnitude of the background zone BETA_WEIGHTS = (0.25, 0.5, 0.25) # beta - sigma, beta, beta + sigma RETURN_PERIODS = (72, 475, 975, 2475, 4975) PGA_LEVELS = np.logspace(np.log10(0.005), np.log10(2.0), 70) SIGMA_TRUNC = 3.0 # ground-motion residual truncation LIFETIMES = (10, 25, 50, 100, 200) def floor_mmax(branches, m_obs): """Raise any maximum-magnitude branch below the largest OBSERVED magnitude in the source zone up to that magnitude (an Mmax below an observed event is inconsistent with the catalogue); weights of merged branches are summed.""" if not np.isfinite(m_obs): return list(branches) floor = round(float(np.ceil(m_obs * 10 - 1e-9) / 10), 1) out = {} for m, w in branches: out[max(m, floor)] = out.get(max(m, floor), 0.0) + w return sorted(out.items()) def parse_completeness(txt): comp = dict(COMPLETENESS) if txt: for part in txt.split(","): k, v = part.split(":") comp[round(float(k), 1)] = None if v.strip().lower() in ("none", "x") else int(v) return comp def gk74_window(mag): """Gardner & Knopoff (1974) distance (km) and time (days) windows.""" mag = np.asarray(mag, float) d = 10 ** (0.1238 * mag + 0.983) t = np.where(mag >= 6.5, 10 ** (0.032 * mag + 2.7389), 10 ** (0.5409 * mag - 0.547)) return d, t def decluster_gk74(year_f, lat, lon, mag): """True for mainshocks. Smaller events inside a larger event's window (+/- time, distance) are dropped.""" n = len(mag) t = np.asarray(year_f, float) * 365.25 order_t = np.argsort(t) ts, ms = t[order_t], np.asarray(mag, float)[order_t] la, lo = np.asarray(lat, float)[order_t], np.asarray(lon, float)[order_t] flagged = np.zeros(n, bool) for i in np.argsort(-ms, kind="stable"): if flagged[i]: continue d, tw = gk74_window(ms[i]) a, b = np.searchsorted(ts, ts[i] - tw, "left"), np.searchsorted(ts, ts[i] + tw, "right") idx = np.arange(a, b) idx = idx[(~flagged[idx]) & (ms[idx] < ms[i])] if len(idx): dist = haversine_km(la[i], lo[i], la[idx], lo[idx]) flagged[idx[dist <= d]] = True main = np.empty(n, bool) main[order_t] = ~flagged return main def fit_recurrence(mags, years, t_end, comp): """Weichert-type maximum likelihood for a Gutenberg-Richter law with magnitude-dependent completeness. Rate in bin i = A * (exp(-beta (lo-M0)) - exp(-beta (hi-M0))) events/yr.""" lo, hi = FIT_EDGES[:-1], FIT_EDGES[1:] start = np.array([comp[round(l, 1)] if comp[round(l, 1)] is not None else 1e9 for l in lo], float) T = np.clip(t_end - start, 0, None) idx = np.digitize(mags, FIT_EDGES) - 1 n = np.array([((idx == k) & (years >= start[k]) & (years < t_end)).sum() for k in range(len(lo))], float) use = T > 0 def f(beta): return np.exp(-beta * (lo - M0_FIT)) - np.exp(-beta * (hi - M0_FIT)) def ll(beta): ff = f(beta) return (n[use] * np.log(ff[use])).sum() - n[use].sum() * np.log((T[use] * ff[use]).sum()) g = np.linspace(0.3, 3.5, 321) b0 = g[np.argmax([ll(x) for x in g])] g2 = np.linspace(b0 - 0.02, b0 + 0.02, 81) beta = g2[np.argmax([ll(x) for x in g2])] h = 0.02 d2 = (ll(beta + h) - 2 * ll(beta) + ll(beta - h)) / h ** 2 sig = float(1 / np.sqrt(-d2)) if d2 < 0 else 0.1 return dict(beta=float(beta), b=float(beta / np.log(10)), sigma_beta=sig, A=float(n[use].sum() / (T[use] * f(beta)[use]).sum()), n=n, T=T, lo=lo, hi=hi, N=int(n.sum()), start=start) def A_for_beta(fit, beta): lo, hi, T, n = fit["lo"], fit["hi"], fit["T"], fit["n"] use = T > 0 ff = np.exp(-beta * (lo - M0_FIT)) - np.exp(-beta * (hi - M0_FIT)) return float(n[use].sum() / (T[use] * ff[use]).sum()) def bin_rates(A, beta, mmax): """Events/yr in each hazard magnitude bin for the whole zone (truncated at mmax).""" lo, hi = HAZ_EDGES[:-1], HAZ_EDGES[1:] hi_c = np.minimum(hi, mmax) r = A * (np.exp(-beta * (lo - M0_FIT)) - np.exp(-beta * (hi_c - M0_FIT))) return np.where(lo < mmax, np.maximum(r, 0.0), 0.0) def poisson_cdf(k, mu): k = int(k) return float(sum(np.exp(-mu + i * np.log(max(mu, 1e-300)) - np.sum(np.log(np.arange(1, i + 1)))) for i in range(k + 1))) def km_xy(lat, lon): return (np.asarray(lon, float) - SITE_LON) * 111.2 * np.cos(np.radians(SITE_LAT)), (np.asarray(lat, float) - SITE_LAT) * 111.2 def make_grid(): s = np.arange(-ZONE_KM, ZONE_KM + GRID_KM, GRID_KM) X, Y = np.meshgrid(s, s) d = np.hypot(X, Y) m = d <= ZONE_KM X, Y, d = X[m], Y[m], d[m] lat = SITE_LAT + Y / 111.2 lon = SITE_LON + X / (111.2 * np.cos(np.radians(SITE_LAT))) return dict(x=X, y=Y, d=d, lat=lat, lon=lon, r_eff=np.sqrt(d ** 2 + (0.38 * GRID_KM) ** 2)) def smoothed_weights(grid, ex, ey, wt, sigma_km): w = np.zeros(len(grid["x"])) for x, y, a in zip(ex, ey, wt): w += a * np.exp(-((grid["x"] - x) ** 2 + (grid["y"] - y) ** 2) / (2 * sigma_km ** 2)) return w / w.sum() def pga_lookup(mids, mode): rg = np.geomspace(0.5, 520.0, 140) tab = np.array([pga(np.full(len(rg), m), rg, mode) for m in mids]) return rg, tab def median_matrix(mids, r_cells, lookup): rg, tab = lookup out = np.empty((len(mids), len(r_cells))) for j, m in enumerate(mids): rjb = np.maximum(r_cells - 0.5 * rupture_length_km(m), 0.0) if m >= 6.5 else r_cells out[j] = np.exp(np.interp(np.log(np.maximum(rjb, 0.5)), np.log(rg), np.log(tab[j]))) return out def sigma_matrix(mids, r_cells): """ln sigma for each (magnitude bin, grid cell), using the same Joyner-Boore distance as median_matrix.""" out = np.empty((len(mids), len(r_cells))) for j, m in enumerate(mids): rjb = np.maximum(r_cells - 0.5 * rupture_length_km(m), 0.0) if m >= 6.5 else r_cells out[j] = sigma_ln(m, rjb) return out def p_exceed(x, med, sigma=None): """P(PGA > x | median, sigma) for lognormal scatter truncated at +/- SIGMA_TRUNC sigma (two-sided, so the normalising constant is Phi(3) - Phi(-3) and z is clamped to [-3, 3]: P = 1 below the lower bound, 0 above the upper). `sigma` is the ln standard deviation (scalar or array broadcastable with `med`); default is the fixed SIGMA_LN.""" sig = SIGMA_LN if sigma is None else sigma z = np.clip((np.log(x) - np.log(med)) / sig, -SIGMA_TRUNC, SIGMA_TRUNC) return (ndtr(SIGMA_TRUNC) - ndtr(z)) / (ndtr(SIGMA_TRUNC) - ndtr(-SIGMA_TRUNC)) def loglog_interp(lam, x, target): lam = np.maximum(lam, 1e-14) if target >= lam[0]: return float(x[0]) if target <= lam[-1]: return float("nan") return float(np.exp(np.interp(np.log(target), np.log(lam[::-1]), np.log(x[::-1])))) def lam_at(lam, x, xq): lam = np.maximum(lam, 1e-14) return float(np.exp(np.interp(np.log(xq), np.log(x), np.log(lam)))) def wquant(vals, w, q): o = np.argsort(vals) cw = np.cumsum(np.asarray(w)[o]) cw /= cw[-1] return float(np.asarray(vals)[o][np.searchsorted(cw, q)]) def run_forecast(ev, args, mode, comp, say): """Returns a dict with everything the forecast JSON and the figures need.""" fc = {} inst = ev[(ev.year_f >= CATALOGUE_START) & (ev.r_epi <= ZONE_KM + PAD_KM)].copy() main = decluster_gk74(inst.year_f.values, inst.lat.values, inst.lon.values, inst.mag_used.values) inst["mainshock"] = main zone = inst[inst.r_epi <= ZONE_KM] zm = zone[zone.mainshock] t_end = 2026.3 say("=" * 72) say("FORECAST MODEL: DECLUSTERING AND RECURRENCE") say(f"source zone: {ZONE_KM:.0f} km radius; events since {CATALOGUE_START}: {len(zone)}; mainshocks after " f"Gardner-Knopoff declustering: {len(zm)} ({len(zm)/len(zone)*100:.0f}%)") say("completeness years by magnitude bin: " + ", ".join(f"M{k:.1f}+:{v if v else 'excluded'}" for k, v in sorted(comp.items()))) # Rate estimation uses catalogue-sourced events only: NOAA-only records are a selected (damaging / notable) subset. def _in_window(m, y): c0 = comp[round(min(max(np.floor(m * 2) / 2, 4.0), 7.5), 1)] return c0 is not None and y >= c0 zmn = zm[zm.source == "NOAA"] n_noaa_in = int(sum(_in_window(m_, y_) for m_, y_ in zip(zmn.mag_used.values, zmn.year_f.values))) zmc = zm[zm.source != "NOAA"] say(f"NOAA-only mainshocks inside the zone: {len(zmn)} ({n_noaa_in} inside their magnitude bin's completeness window); " f"excluded from the recurrence fit, back-test and spatial smoothing, which use the {len(zmc)} catalogue-sourced mainshocks.") fit = fit_recurrence(zmc.mag_used.values, zmc.year_f.values, t_end, comp) say(f"Weichert ML fit (declustered, {fit['N']} events): b = {fit['b']:.2f} +/- {fit['sigma_beta']/np.log(10):.2f}, " f"rate M>={M0_FIT:.1f}: {fit['A']:.2f}/yr, M>=5: {fit['A']*np.exp(-fit['beta']):.2f}/yr, " f"M>=6: {fit['A']*np.exp(-2*fit['beta']):.3f}/yr (return period {1/(fit['A']*np.exp(-2*fit['beta'])):.0f} yr), " f"M>=7: {fit['A']*np.exp(-3*fit['beta']):.4f}/yr (return period {1/(fit['A']*np.exp(-3*fit['beta'])):.0f} yr)") say(" bin T(yr) observed expected two-sided Poisson p (in-sample goodness of fit)") gof, tail_o, tail_e = [], 0.0, 0.0 for k in range(len(fit["lo"])): if fit["T"][k] > 0: e = fit["T"][k] * fit["A"] * (np.exp(-fit["beta"] * (fit["lo"][k] - M0_FIT)) - np.exp(-fit["beta"] * (fit["hi"][k] - M0_FIT))) o_ = int(fit["n"][k]) p_ = float(min(1.0, 2 * min(poisson_cdf(o_, e), 1 - poisson_cdf(o_ - 1, e) if o_ > 0 else 1.0))) gof.append(dict(bin=f"M{fit['lo'][k]:.1f}-{fit['hi'][k]:.1f}", observed=o_, expected=round(float(e), 2), poisson_p_two_sided=round(p_, 3))) if fit["lo"][k] >= 6.5 - 1e-9: tail_o, tail_e = tail_o + o_, tail_e + e say(f" M{fit['lo'][k]:.1f}-{fit['hi'][k]:.1f} {fit['T'][k]:7.0f} {o_:9d} {e:9.1f} {p_:12.2f}") p_tail = float(1 - poisson_cdf(int(tail_o) - 1, tail_e)) if tail_o > 0 else 1.0 fc["fit_gof"] = dict(bins=gof, m_ge_6p5_observed=tail_o, m_ge_6p5_expected=round(float(tail_e), 2), p_at_least_observed=round(p_tail, 3)) say(f" M>=6.5 tail: observed {tail_o:.0f}, expected {tail_e:.2f}, P(N >= observed) = {p_tail:.3f}" + (" <-- WARNING: G-R fit under-predicts the large-magnitude tail (p < 0.05); the heterogeneous magnitude scales and " "small sample limit this test, but b may be too steep for M>=6.5" if p_tail < 0.05 else "")) m_obs = float(ev.loc[ev.r_epi <= ZONE_KM, "mag"].max()) if len(ev) else float("nan") mmax_branches = floor_mmax(MMAX_BRANCHES, m_obs) fc["mmax_branches"] = mmax_branches if mmax_branches != sorted(MMAX_BRANCHES): say(f"Mmax branches raised to the largest observed magnitude in the {ZONE_KM:.0f} km zone (M{m_obs:.1f}, catalogue magnitudes only): " f"{sorted(MMAX_BRANCHES)} -> {mmax_branches}") # ---- split-sample back-test: fit to data before 2000, predict 2000-2026 cut = 2000.0 bt_fit = fit_recurrence(zmc.mag_used.values, zmc.year_f.values, cut, comp) span = t_end - cut bt = [] say(f"BACK-TEST: model fitted to data before {cut:.0f} (b = {bt_fit['b']:.2f}) vs what happened in {cut:.0f}-2026") for k in range(1, len(bt_fit["lo"]) - 1): lo_, hi_ = bt_fit["lo"][k], bt_fit["hi"][k] e = span * bt_fit["A"] * (np.exp(-bt_fit["beta"] * (lo_ - M0_FIT)) - np.exp(-bt_fit["beta"] * (hi_ - M0_FIT))) o = int(((zmc.mag_used >= lo_) & (zmc.mag_used < hi_) & (zmc.year_f >= cut)).sum()) p_lo = poisson_cdf(o, e) p_hi = 1 - poisson_cdf(o - 1, e) if o > 0 else 1.0 bt.append(dict(bin=f"M{lo_:.1f}-{hi_:.1f}", expected=round(float(e), 2), observed=o, poisson_p_value_two_sided=round(float(min(1.0, 2 * min(p_lo, p_hi))), 3))) say(f" M{lo_:.1f}-{hi_:.1f}: expected {e:6.1f}, observed {o:4d} (two-sided Poisson p = {bt[-1]['poisson_p_value_two_sided']:.2f})") fc["backtest"] = bt fc["backtest_fit_b"] = bt_fit["b"] # ---- spatial distribution (smoothed seismicity) grid = make_grid() sel = inst[inst.mainshock & (inst.mag_used >= 4.5) & (inst.source != "NOAA")] start_of = lambda m: comp[round(min(max(np.floor(m * 2) / 2, 4.0), 7.5), 1)] sel = sel[[start_of(m) is not None for m in sel.mag_used.values]] # bins excluded via --completeness carry no weight wt = np.array([1.0 / (t_end - start_of(m)) for m in sel.mag_used.values]) ok = np.array([year >= start_of(m) for year, m in zip(sel.year_f.values, sel.mag_used.values)]) ex, ey = km_xy(sel.lat.values[ok], sel.lon.values[ok]) w = smoothed_weights(grid, ex, ey, wt[ok], args.smooth_km) fc.update(grid=grid, w=w, fit=fit, zone=zone, zm=zm) say(f"spatial model: {ok.sum()} declustered M>=4.5 events smoothed with a {args.smooth_km:.0f} km Gaussian kernel on a " f"{GRID_KM:.0f} km grid ({len(w)} cells); share of rate within 50 km: {w[grid['d']<=50].sum()*100:.1f}%, " f"100 km: {w[grid['d']<=100].sum()*100:.1f}%, 200 km: {w[grid['d']<=200].sum()*100:.1f}%") # ---- hazard mids = (HAZ_EDGES[:-1] + HAZ_EDGES[1:]) / 2 lookup = pga_lookup(mids, mode) med = median_matrix(mids, grid["r_eff"], lookup) sig = sigma_matrix(mids, grid["r_eff"]) C = np.empty((len(PGA_LEVELS), len(mids))) for j in range(len(mids)): C[:, j] = p_exceed(PGA_LEVELS[:, None], med[j][None, :], sig[j][None, :]) @ w fc.update(mids=mids, med=med, sig=sig) say(f"ground-motion scatter: {'BSSA14 magnitude/distance-dependent sigma' if SIGMA_MODEL == 'bssa14' else 'fixed sigma ' + str(SIGMA_LN)}" f" (background {sig.min():.2f}-{sig.max():.2f}; fault M7.3 at {SCEN_RJB_KM} km: {float(sigma_ln(7.3, SCEN_RJB_KM)):.2f}); " f"truncated at +/-{SIGMA_TRUNC:.0f} sigma; component = RotD50 horizontal (BSSA14)") def fault_lam(slip, mchar): d_avg = 10 ** (-6.32 + 0.90 * mchar) # Wells & Coppersmith 1994 average displacement (m) rate = args.coupling * slip * 1e-3 / d_avg medf = float(pga([mchar], [SCEN_RJB_KM], mode)[0]) return rate, p_exceed(PGA_LEVELS, medf, float(sigma_ln(mchar, SCEN_RJB_KM))), d_avg branches = [] for ib, (bs, wb) in enumerate(zip((-1, 0, 1), BETA_WEIGHTS)): beta = fit["beta"] + bs * fit["sigma_beta"] A = A_for_beta(fit, beta) for mmax, wm in mmax_branches: lam_bg = C @ bin_rates(A, beta, mmax) for slip, ws in SLIP_BRANCHES: for mc, wc in MCHAR_BRANCHES: rate, pe, _ = fault_lam(slip, mc) branches.append(dict(w=wb * wm * ws * wc, beta=beta, A=A, mmax=mmax, slip=slip, mchar=mc, lam_bg=lam_bg, lam_f=rate * pe, rate_f=rate)) W = np.array([b["w"] for b in branches]) W = W / W.sum() LB = np.array([b["lam_bg"] for b in branches]) LF = np.array([b["lam_f"] for b in branches]) LT = LB + LF mean_bg, mean_f = (W[:, None] * LB).sum(0), (W[:, None] * LF).sum(0) mean = mean_bg + mean_f lo16 = np.array([wquant(LT[:, i], W, 0.16) for i in range(LT.shape[1])]) hi84 = np.array([wquant(LT[:, i], W, 0.84) for i in range(LT.shape[1])]) def branch_quantiles(tgt): """Alternative band: invert every branch's own hazard curve at 1/T first, then take weighted quantiles of the branch PGAs. (The main columns instead take quantiles of branch RATES at each PGA level and invert those.) A branch whose curve stays above 1/T over the whole grid is capped at the largest grid PGA.""" xs = np.array([loglog_interp(LT[b], PGA_LEVELS, tgt) for b in range(LT.shape[0])]) xs = np.where(np.isfinite(xs), xs, PGA_LEVELS[-1]) return wquant(xs, W, 0.16), wquant(xs, W, 0.84) # conditional hazard under each explicit fault-activity hypothesis (background identical in both) SL = np.array([b["slip"] for b in branches]) hyp = {} for name, slips in HYPOTHESES.items(): msk = np.isin(SL, slips) if not msk.any(): raise ValueError(f"hypothesis {name}: none of {slips} mm/yr is in SLIP_BRANCHES") Wh = W[msk] / W[msk].sum() hyp[name] = dict(slips=slips, weight_in_tree=float(W[msk].sum()), mean=(Wh[:, None] * LT[msk]).sum(0), mean_f=(Wh[:, None] * LF[msk]).sum(0)) envelope = np.maximum.reduce([h["mean"] for h in hyp.values()]) fc.update(x=PGA_LEVELS, mean=mean, mean_bg=mean_bg, mean_f=mean_f, lo16=lo16, hi84=hi84, W=W, LT=LT, hyp=hyp, envelope=envelope) rp_table = {} say("=" * 72) say(f"fault slip-rate branches (mm/yr, weight): {', '.join(f'{s:g} ({w:g})' for s, w in SLIP_BRANCHES)}; " f"weighted mean {sum(s*w for s, w in SLIP_BRANCHES):.2f} mm/yr") say("UNIFORM-HAZARD PGA AT THE SITE (rock, Vs30 760 m/s, median ground motion; mean and 16-84% across logic-tree branches)") say(" (16/84% = EPISTEMIC spread: weighted quantiles of the branch exceedance-RATE curves at each PGA level, then inverted at 1/T;") say(" not the scatter of one earthquake's ground motion. A cross-check by inverting each branch first is printed below.)") say(f"{'return period':>14} {'P in 50 yr':>11} {'P in 100 yr':>12} {'mean PGA g':>11} {'16%':>7} {'84%':>7} share from Karakoram Fault") for rp in RETURN_PERIODS: tgt = 1.0 / rp xm = loglog_interp(mean, PGA_LEVELS, tgt) x16, x84 = loglog_interp(lo16, PGA_LEVELS, tgt), loglog_interp(hi84, PGA_LEVELS, tgt) fsh = lam_at(mean_f, PGA_LEVELS, xm) / tgt if np.isfinite(xm) else float("nan") b16, b84 = branch_quantiles(tgt) rp_table[rp] = dict(return_period_yr=rp, prob_50yr=1 - np.exp(-50 / rp), prob_100yr=1 - np.exp(-100 / rp), pga_mean_g=xm, pga_16_g=x16, pga_84_g=x84, fraction_from_karakoram_fault=fsh, pga_16_branch_inversion_g=b16, pga_84_branch_inversion_g=b84) say(f"{rp:14d} {(1-np.exp(-50/rp))*100:10.1f}% {(1-np.exp(-100/rp))*100:11.1f}% {xm:11.3f} {x16:7.3f} {x84:7.3f} {fsh*100:5.0f}%") fc["rp_table"] = rp_table say(" cross-check, 16-84% band by inverting each branch curve first (epistemic, weighted by branch weight): " + " ".join( f"{rp} yr {rp_table[rp]['pga_16_branch_inversion_g']:.3f}-{rp_table[rp]['pga_84_branch_inversion_g']:.3f} g" for rp in RETURN_PERIODS)) hyp_table = {} say("PGA BY FAULT-ACTIVITY HYPOTHESIS (g, mean over the other logic-tree branches; the envelope is max(A, B) at each level)") say(f"{'return period':>14} " + " ".join(f"{n[:26]:>27}" for n in hyp) + f" {'envelope':>10} {'blended tree':>13}") say(f"{'tree weight':>14} " + " ".join(f"{h['weight_in_tree']:27.2f}" for h in hyp.values())) for rp in RETURN_PERIODS: tgt = 1.0 / rp row = {n: loglog_interp(h["mean"], PGA_LEVELS, tgt) for n, h in hyp.items()} row["envelope"] = loglog_interp(envelope, PGA_LEVELS, tgt) row["blended_tree"] = rp_table[rp]["pga_mean_g"] hyp_table[rp] = row say(f"{rp:14d} " + " ".join(f"{row[n]:27.3f}" for n in hyp) + f" {row['envelope']:10.3f} {row['blended_tree']:13.3f}") fc["hypothesis_pga_table"] = hyp_table say(" (A and B are conditional hypotheses, not predictions; the 475/2475-yr values are ground-motion exceedance periods, " "NOT recurrence intervals of the characteristic earthquake.)") say("SLIP-BUDGET RECURRENCE OF THE CHARACTERISTIC RUPTURE (years; coupling x slip / average displacement, Wells & Coppersmith 1994;") say(" a slip-budget estimate conditional on the fault being active, not an observed recurrence interval)") act = [s_ for s_ in sorted({s_ for hs in HYPOTHESES.values() for s_ in hs}) if s_ > 0] say(f"{'Mchar':>7} {'D avg (m)':>10} " + " ".join(f"{s_:>5g} mm/yr" for s_ in act)) for mc, _ in MCHAR_BRANCHES: d_ = 10 ** (-6.32 + 0.90 * mc) say(f"{mc:7.1f} {d_:10.2f} " + " ".join( f"{(d_ / (args.coupling * s_ * 1e-3)):8.0f} " if args.coupling > 0 else f"{'inf':>10}" for s_ in act)) sens = {} if args.coupling > 0: say("SENSITIVITY of mean PGA (g) to the fraction of Karakoram Fault slip released in large earthquakes (coupling):") for c in (0.25, 0.5, 1.0): lam_c = mean_bg + (c / args.coupling) * mean_f sens[str(c)] = {str(rp): loglog_interp(lam_c, PGA_LEVELS, 1.0 / rp) for rp in (475, 975, 2475)} say(f" coupling {c:4.2f}: 475 yr {sens[str(c)]['475']:.3f} 975 yr {sens[str(c)]['975']:.3f} 2475 yr {sens[str(c)]['2475']:.3f}") say(" (the fault slip rate / coupling is the largest single uncertainty; see the fault share column above)") fc["coupling_sensitivity"] = sens # ---- disaggregation (mean model) rate_mean = sum(b["w"] / sum(bb["w"] for bb in branches) * bin_rates(b["A"], b["beta"], b["mmax"]) for b in branches) fault_mean = {} for b in branches: fault_mean[b["mchar"]] = fault_mean.get(b["mchar"], 0) + b["w"] / sum(bb["w"] for bb in branches) * b["rate_f"] r_edges = np.array([0, 10, 25, 50, 100, 200, 300, 400.01]) m_edges = np.arange(4.5, 8.51, 0.5) dis = {} for rp in (72, 475, 2475): x0 = rp_table[rp]["pga_mean_g"] Hf = np.zeros((len(m_edges) - 1, len(r_edges) - 1)) # Karakoram Fault source only P = p_exceed(x0, med, sig) G = rate_mean[:, None] * w[None, :] * P H = np.zeros((len(m_edges) - 1, len(r_edges) - 1)) for j, m in enumerate(mids): mi = min(int((m - 4.5) // 0.5), H.shape[0] - 1) ri = np.clip(np.digitize(grid["d"], r_edges) - 1, 0, H.shape[1] - 1) np.add.at(H[mi], ri, G[j]) for mc, rate in fault_mean.items(): pe = float(p_exceed(x0, np.array([float(pga([mc], [SCEN_RJB_KM], mode)[0])]), float(sigma_ln(mc, SCEN_RJB_KM)))[0]) H[min(int((mc - 4.5) // 0.5), H.shape[0] - 1), 0] += rate * pe Hf[min(int((mc - 4.5) // 0.5), H.shape[0] - 1), 0] += rate * pe tot = H.sum() H, Hf = H / tot, Hf / tot mm = (m_edges[:-1] + 0.25)[:, None] * np.ones_like(H) rr = (0.5 * (r_edges[:-1] + r_edges[1:]))[None, :] * np.ones_like(H) mi_, ri_ = np.unravel_index(np.argmax(H), H.shape) # mean magnitude and distance using bin-level resolution from the fine grid dis[rp] = dict(H=H, m_edges=m_edges, r_edges=r_edges, mode_M=float(m_edges[mi_] + 0.25), mode_R=f"{r_edges[ri_]:.0f}-{r_edges[ri_+1]:.0f} km", x0=x0, mean_M=float((H * mm).sum()), mean_R=float((H * rr).sum()), fault_share=float(Hf.sum()), # Karakoram Fault SOURCE only share_0_10_km=float(H[:, 0].sum()), # everything in the 0-10 km bin (fault + background) Hf=Hf) say(f"DISAGGREGATION at {rp}-yr PGA ({x0:.3f} g): mean M {dis[rp]['mean_M']:.2f}, mean R {dis[rp]['mean_R']:.0f} km, " f"modal bin M{dis[rp]['mode_M']-0.25:.1f}-{dis[rp]['mode_M']+0.25:.1f} at {dis[rp]['mode_R']}; " f"Karakoram Fault source: {dis[rp]['fault_share']*100:.0f}%; all sources in the 0-10 km bin: {dis[rp]['share_0_10_km']*100:.0f}% " f"(the difference is background seismicity within 10 km)") fc["dis"] = dis # ---- map of where relevant shaking comes from (contribution to rate of PGA >= x_map) x_map = 0.05 Pmap = p_exceed(x_map, med, sig) fc["x_map"] = x_map fc["cell_rate"] = (rate_mean[:, None] * Pmap).sum(0) * w fc["rate_mean_bins"] = rate_mean # ---- forecast tables (Poisson, mean model) ev_tab = [] for m, R in ((5.0, 50), (5.0, 100), (6.0, 100), (6.0, 200), (7.0, 200), (7.0, 400)): sel_bins = HAZ_EDGES[:-1] >= m - 1e-9 frac = w[grid["d"] <= R].sum() lam = float(rate_mean[sel_bins].sum() * frac) lam_fault = float(sum(r for mc, r in fault_mean.items() if mc >= m - 1e-9)) lam += lam_fault ev_tab.append(dict(magnitude_at_least=m, within_km=R, annual_rate=lam, return_period_yr=1 / lam, probability={str(T): 1 - np.exp(-lam * T) for T in LIFETIMES}, includes_karakoram_fault_characteristic_events=bool(lam_fault > 0))) fc["event_forecast"] = ev_tab say("=" * 72) say("FORECAST: probability of at least one earthquake (Poisson, mean model)") say(f"{'event':>22} " + " ".join(f"{T:>7d}yr" for T in LIFETIMES) + " return period") for r in ev_tab: say(f"{'M>=%.1f within %d km' % (r['magnitude_at_least'], r['within_km']):>22} " + " ".join(f"{r['probability'][str(T)]*100:8.1f}%" for T in LIFETIMES) + f" {r['return_period_yr']:.0f} yr") ex_tab = [] say(f"{'shaking at site':>22} " + " ".join(f"{T:>7d}yr" for T in LIFETIMES) + " (probability of exceedance)") for xq in (0.05, 0.10, 0.20, 0.30, 0.50): lam = lam_at(mean, PGA_LEVELS, xq) l16, l84 = lam_at(lo16, PGA_LEVELS, xq), lam_at(hi84, PGA_LEVELS, xq) ex_tab.append(dict(pga_g=xq, annual_rate=lam, return_period_yr=1 / lam, probability={str(T): 1 - np.exp(-lam * T) for T in LIFETIMES}, probability_16_84_100yr=[1 - np.exp(-l16 * 100), 1 - np.exp(-l84 * 100)])) say(f"{'PGA >= %.2f g' % xq:>22} " + " ".join(f"{ex_tab[-1]['probability'][str(T)]*100:8.1f}%" for T in LIFETIMES) + f" {1/lam:.0f} yr") fc["exceedance_forecast"] = ex_tab # ---- design scenarios and slope screening scen = [] for rp in (475, 2475): d = dis[rp] mmid = float(d["mean_M"]) fshare = float(d["fault_share"]) if fshare >= 0.65: character, rmid = "fault-dominated", SCEN_RJB_KM basis = "mean magnitude from disaggregation; distance = Karakoram Fault (the fault source supplies >= 65% of the rate)" elif fshare <= 0.35: character, rmid = "background-dominated", max(float(d["mean_R"]), 1.0) basis = "mean magnitude and distance from disaggregation" else: character, rmid = "mixed", max(float(d["mean_R"]), 1.0) basis = ("MIXED: the fault source supplies %.0f%% of the rate and background seismicity the rest, so no single scenario " "represents this level; mean magnitude and distance from disaggregation (a fault event of M7.0-7.5 at %.1f km " "is the largest single contributor)" % (fshare * 100, SCEN_RJB_KM)) scen.append(dict(name=f"hazard-consistent scenario, {rp}-yr return period", magnitude=round(mmid, 2), character=character, fault_source_share=round(fshare, 3), distance_km=round(rmid, 1), target_pga_g=round(rp_table[rp]["pga_mean_g"], 3), basis=basis)) scen.append(dict(name="deterministic Karakoram Fault scenario", magnitude=args.scenario_mag, distance_km=SCEN_RJB_KM, target_pga_g=None, basis="user scenario; see summary for the median and 84th-percentile PGA")) fc["scenarios"] = scen return fc # -------------------------------------------------------------------------- # Maps of the design-relevant earthquakes # -------------------------------------------------------------------------- def relevant_table(ev, args): sub = ev[ev.r_epi <= 500].copy() sub["reasons"] = [relevance_reasons(r, args) for _, r in sub.iterrows()] return sub[sub.reasons.map(len) > 0].sort_values("pga_g", ascending=False) def read_fault_trace(path): if not path: return None tr = pd.read_csv(path) return tr.iloc[:, 0].values, tr.iloc[:, 1].values # lon, lat def write_geojson(path, rel): feats = [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [SITE_LON, SITE_LAT]}, "properties": {"kind": "site", "name": "Agham spur"}}] for _, r in rel.iterrows(): feats.append({"type": "Feature", "geometry": {"type": "Point", "coordinates": [clean(r.lon), clean(r.lat)]}, "properties": {"kind": "earthquake", "source": r.source, "date": r.date, "magnitude": clean(r.mag_used), "place": clean(r.place), "epicentral_distance_km": clean(r.r_epi), "median_pga_g": clean(r.pga_g), "selected_by": r.reasons}}) with open(path, "w") as fh: json.dump({"type": "FeatureCollection", "features": feats}, fh, indent=1, ensure_ascii=False) def jsonable(o): if isinstance(o, dict): return {str(k): jsonable(v) for k, v in o.items()} if isinstance(o, (list, tuple)): return [jsonable(v) for v in o] if isinstance(o, np.ndarray): return jsonable(o.tolist()) if isinstance(o, (np.floating, float)): return None if not np.isfinite(o) else float(f"{float(o):.5g}") if isinstance(o, np.integer): return int(o) if isinstance(o, np.bool_): return bool(o) return o JIBSON_RATIO_RANGE = (0.05, 0.40) # ac/amax range treated as the regression's calibrated range; outside it results are flagged as possible # extrapolation. The bounds are taken from a review comment and should be confirmed against Jibson (2007). def extrapolated(ac, amax): r = ac / amax return bool(r < JIBSON_RATIO_RANGE[0] or r > JIBSON_RATIO_RANGE[1]) def write_forecast_json(path, fc, args, mode, comp, scen_pga, max_hist, hist_m): fit = fc["fit"] rp = fc["rp_table"] slope = [] for ac in (0.02, 0.05, 0.10, 0.20, 0.30): row = {"critical_acceleration_g": ac} for r in (475, 2475): row[f"displacement_cm_at_{r}yr_pga"] = float(newmark_cm([ac], rp[r]["pga_mean_g"], fc["dis"][r]["mean_M"])[0]) row[f"possible_extrapolation_at_{r}yr_pga"] = extrapolated(ac, rp[r]["pga_mean_g"]) row["displacement_cm_scenario_median"] = float(newmark_cm([ac], scen_pga, args.scenario_mag)[0]) row["displacement_cm_scenario_84th"] = float(newmark_cm([ac], scen_pga * scen_factor(args.scenario_mag), args.scenario_mag)[0]) row["possible_extrapolation_scenario_median"] = extrapolated(ac, scen_pga) row["possible_extrapolation_scenario_84th"] = extrapolated(ac, scen_pga * scen_factor(args.scenario_mag)) slope.append(row) scen = [] for s in fc["scenarios"]: s = dict(s) if s["target_pga_g"] is None: s["median_pga_g"] = scen_pga s["pga_84th_percentile_g"] = scen_pga * scen_factor(args.scenario_mag) scen.append(s) dis = {} for r, d in fc["dis"].items(): dis[str(r)] = dict(pga_g=d["x0"], mean_magnitude=d["mean_M"], mean_distance_km=d["mean_R"], modal_magnitude_bin=f"M{d['mode_M']-0.25:.1f}-{d['mode_M']+0.25:.1f}", modal_distance_bin=d["mode_R"], share_from_0_10_km_all_sources=d["share_0_10_km"], share_from_karakoram_fault_source=d["fault_share"], contribution_matrix_fraction={"magnitude_bin_edges": d["m_edges"], "distance_bin_edges_km": d["r_edges"], "rows_magnitude_cols_distance": d["H"], "karakoram_fault_source_only_rows_magnitude_cols_distance": d["Hf"]}) out = { "purpose": "Forecast of future earthquake shaking at the site, from the whole merged dataset, for future-proofing a building. " "A screening-level probabilistic seismic hazard analysis (PSHA); not a substitute for a site-specific study and the governing code.", "site": {"name": "Agham spur, Ladakh", "latitude": SITE_LAT, "longitude": SITE_LON, "reference_condition": f"rock, Vs30 = {VS30_ROCK:.0f} m/s, no topographic amplification"}, "headline": { f"pga_{r}yr_return_period_g": rp[r]["pga_mean_g"] for r in (475, 975, 2475) } | {"deterministic_karakoram_fault_median_pga_g": scen_pga, "deterministic_karakoram_fault_84th_percentile_pga_g": scen_pga * scen_factor(args.scenario_mag), "largest_pga_in_scored_history_g": max_hist}, "model": { "ground_motion": "BSSA14 PGA, strike-slip, rock (" + mode + " implementation)" + ("; embedded coefficients UNVERIFIED" if mode == "embedded" else ""), "ground_motion_sigma_ln": {"model": SIGMA_MODEL, "fixed_value_if_fixed": SIGMA_LN, "fault_scenario_value": float(sigma_ln(args.scenario_mag, SCEN_RJB_KM)), "background_range": [float(fc["sig"].min()), float(fc["sig"].max())]}, "residual_truncation_sigma": SIGMA_TRUNC, "truncation": "two-sided", "ground_motion_component": "RotD50 horizontal PGA (BSSA14); embedded sigma checked against pygmm", "background_source": { "zone_radius_km": ZONE_KM, "declustering": "Gardner-Knopoff (1974), +/- time window", "recurrence": "Gutenberg-Richter, Weichert maximum likelihood with magnitude-dependent completeness", "completeness_start_year_by_magnitude_bin": {f"M{k:.1f}": v for k, v in sorted(comp.items())}, "fit_goodness_of_fit": fc.get("fit_gof"), "events_used": fit["N"], "b_value": fit["b"], "b_value_sigma": fit["sigma_beta"] / np.log(10), "annual_rate_M_ge_4": fit["A"], "annual_rate_M_ge_5": fit["A"] * np.exp(-fit["beta"]), "annual_rate_M_ge_6": fit["A"] * np.exp(-2 * fit["beta"]), "annual_rate_M_ge_7": fit["A"] * np.exp(-3 * fit["beta"]), "spatial_distribution": f"smoothed seismicity, {args.smooth_km:.0f} km Gaussian kernel, {GRID_KM:.0f} km grid", "minimum_magnitude_in_hazard": float(HAZ_EDGES[0]), "logic_tree_mmax": [{"mmax": m, "weight": w} for m, w in fc["mmax_branches"]], "logic_tree_b": "b -/+ 1 sigma with weights 0.25/0.5/0.25"}, "karakoram_fault_source": { "distance_km": SCEN_RJB_KM, "coupling_fraction": args.coupling, "recurrence": "rate = coupling x slip rate / average displacement (Wells & Coppersmith 1994), Poisson", "logic_tree_slip_rate_mm_per_yr": [{"rate": s, "weight": w} for s, w in SLIP_BRANCHES], "slip_rate_basis": "Nubra/northern sector (site is at Agham): GPS and block models give ~0-1 mm/yr north, 1.6-3.2 mm/yr on the Pangong strand " "(Mohanty 2024; Wang 2026; Wang & Shen 2020). Weights are a judgement. Branches span 0 (inactive) to 4 mm/yr (cap).", "logic_tree_characteristic_magnitude": [{"magnitude": m, "weight": w} for m, w in MCHAR_BRANCHES], "recurrence_interval_yr_examples": {f"M{m}_slip{s}mm_yr": (10 ** (-6.32 + 0.90 * m)) / (args.coupling * s * 1e-3) for m, _ in MCHAR_BRANCHES for s, _ in SLIP_BRANCHES if s > 0 and args.coupling > 0}, "fault_activity_hypotheses": {n: {"slip_rates_mm_per_yr": list(h["slips"]), "implied_tree_weight": h["weight_in_tree"]} for n, h in fc["hyp"].items()}, "characteristic_magnitudes_are_alternatives_not_additive": True}, }, "uniform_hazard_table": {str(k): v for k, v in rp.items()}, "pga_by_fault_activity_hypothesis_g": {str(k): v for k, v in fc["hypothesis_pga_table"].items()}, "probability_of_exceeding_pga_at_site": fc["exceedance_forecast"], "probability_of_earthquake_in_lifetime": fc["event_forecast"], "disaggregation": dis, "sensitivity_to_fault_coupling_mean_pga_g": fc["coupling_sensitivity"], "design_scenarios": scen, "slope_screening_newmark": slope, "back_test": {"fit_period": "before 2000", "test_period": "2000-2026", "b_value_of_fit": fc["backtest_fit_b"], "bins": fc["backtest"]}, "hazard_curve": {"pga_g": fc["x"], "annual_rate_mean": fc["mean"], "annual_rate_background": fc["mean_bg"], "annual_rate_karakoram_fault": fc["mean_f"], "annual_rate_16th": fc["lo16"], "annual_rate_84th": fc["hi84"], "annual_rate_hypothesis_A_active": fc["hyp"]["A_active_2to4"]["mean"], "annual_rate_hypothesis_B_inactive_or_very_low": fc["hyp"]["B_inactive_or_very_low_0to1"]["mean"], "annual_rate_envelope_max_A_B": fc["envelope"]}, "design_considerations": [ "All PGA values are for rock (Vs30 760 m/s). Apply the actual site class, and consider topographic amplification on the spur; neither is included.", "The Karakoram Fault is about 1.6 km away. BSSA14 does not model near-fault directivity or fling, and surface-fault rupture and off-fault deformation are not covered. A mapped fault trace and a setback/rupture hazard review are needed.", "Recurrence on the fault is Poisson (time-independent) and ignores the time elapsed since its last large rupture; the instrumental record contains no M7+ on it, so a large event may be 'due' or the fault may be partly creeping. The slip-rate and coupling branches span that uncertainty.", "The deterministic fault scenario assumes the fault can rupture; it is conditional on activity and is not weighted by the slip-rate tree. Compare the 2475-year probabilistic PGA with the deterministic fault scenario (84th percentile) and with the governing building code; the higher of the checks usually governs near an active fault.", "Spectral accelerations at structural periods (not only PGA) are needed for design; run the same logic tree with a full BSSA14 implementation (e.g. pygmm) for the periods that matter.", "How much the Karakoram Fault contributes depends mainly on its slip rate and coupling (see sensitivity table and the fault_share fields). The slip rate here is for the Nubra sector and is poorly constrained: GPS says inactive (Nubra, Mohanty 2024) to a few mm/yr (southern segment, block models) and which published segment the strand at 1.6 km belongs to is unresolved. A segment-specific paleoseismic or trenching study would replace it. PGA above ~1 g at long return periods is driven by the 3-sigma tail of ground-motion scatter at 1.6 km; review it with a specialist (it is not a true upper bound: GMPE, site, rupture-geometry and catalogue uncertainties are not in the logic tree).", "Slope and debris stability: use the Newmark table with the critical accelerations from a geotechnical survey of the spur.", "Magnitudes mix mb/Ms/Mw and are treated as Mw; the catalogue is incomplete before ~1973 for small events, and rates for M>=7 rest on a handful of events."], } with open(path, "w") as fh: json.dump(jsonable(out), fh, indent=2, ensure_ascii=False) # -------------------------------------------------------------------------- # Forecast / map figures # -------------------------------------------------------------------------- def draw_rings(ax, rads, **kw): th = np.linspace(0, 2 * np.pi, 361) for rad in rads: ax.plot(SITE_LON + rad / (111.2 * np.cos(np.radians(SITE_LAT))) * np.cos(th), SITE_LAT + rad / 111.2 * np.sin(th), **kw) def fig_design_map(ev, rel, args, path, trace): from matplotlib.colors import LogNorm from matplotlib.lines import Line2D coslat = np.cos(np.radians(SITE_LAT)) fig, ax = plt.subplots(1, 2, figsize=(18, 8.4)) norm, cmap = LogNorm(vmin=3e-3, vmax=6e-2), "YlOrRd" bg = ev[ev.source != "NOAA"] mappable = None for k, a in enumerate(ax): ext = 520.0 if k == 0 else 170.0 sub = bg[bg.r_epi <= ext * 1.4] a.scatter(sub.lon, sub.lat, s=3, c="0.82", zorder=1) for kind, mk in (("cat", "o"), ("noaa", "D")): sel = rel[rel.source.isin(["NOAA", "USGS+NOAA"])] if kind == "noaa" else rel[rel.source == "USGS"] s_ = sel[sel.scored] if len(s_): mappable = a.scatter(s_.lon, s_.lat, c=s_.pga_g, cmap=cmap, norm=norm, marker=mk, s=(s_.mag_used - 3.8).clip(lower=0.3) ** 3 * 14, edgecolor="k", lw=.8, zorder=3) u_ = sel[~sel.scored] if len(u_): a.scatter(u_.lon, u_.lat, c="0.55", marker=mk, s=(u_.mag_used - 3.8).clip(lower=0.3) ** 3 * 14, edgecolor="k", lw=.8, zorder=3) draw_rings(a, (100, 200, 300, 400, 500) if k == 0 else (25, 50, 100, 150), color="k", lw=.8, ls="--", alpha=.6) for rad in ((100, 200, 300, 400, 500) if k == 0 else (25, 50, 100, 150)): a.text(SITE_LON, SITE_LAT + rad / 111.2, f"{rad} km", fontsize=8, ha="center", va="bottom", alpha=.7) if trace is not None: a.plot(trace[0], trace[1], color="darkred", lw=2, label="fault trace", zorder=4) a.scatter([SITE_LON], [SITE_LAT], marker="*", s=420, c="red", edgecolor="k", zorder=6) lab = rel[(rel.r_epi <= ext)] lab = lab[(lab.mag_used >= 7.0)] if k == 0 else lab.head(10) for _, r in lab.iterrows(): a.annotate(f"{r.date[:4]} M{r.mag_used:.1f}", (r.lon, r.lat), xytext=(5, 5), textcoords="offset points", fontsize=8, bbox=dict(boxstyle="round,pad=0.15", fc="white", ec="none", alpha=.7), zorder=7) a.set_xlim(SITE_LON - ext / (111.2 * coslat), SITE_LON + ext / (111.2 * coslat)) a.set_ylim(SITE_LAT - ext / 111.2, SITE_LAT + ext / 111.2) a.set_aspect(1 / coslat) a.set_xlabel("Longitude") a.set_ylabel("Latitude") a.set_title(("Regional view, within 520 km (labels: M>=7)" if k == 0 else "Near field, within 170 km (labels: 10 highest PGA)")) cb = fig.colorbar(mappable, ax=ax, fraction=0.02, pad=0.01) cb.set_label("Median PGA at the site from that event (g, rock)") h = [Line2D([], [], marker="o", ls="", mfc="w", mec="k", label="catalogue event"), Line2D([], [], marker="D", ls="", mfc="w", mec="k", label="NOAA-listed (damaging/notable)"), Line2D([], [], marker="o", ls="", mfc="0.55", mec="k", label="beyond 400 km: not scored"), Line2D([], [], marker="*", ls="", mfc="red", mec="k", ms=14, label="site"), Line2D([], [], marker="o", ls="", mfc="0.82", mec="0.82", ms=4, label="other catalogue events")] ax[0].legend(handles=h, loc="lower left", fontsize=8) fig.suptitle(f"Earthquakes relevant to building design at the site (n = {len(rel)}; marker size = magnitude)", fontsize=13) plt.savefig(path, dpi=110, bbox_inches="tight") plt.close() def fig_recurrence(fc, path): fit, zone, zm = fc["fit"], fc["zone"], fc["zm"] fig, ax = plt.subplots(1, 3, figsize=(18, 5.6)) a = ax[0] mid = (fit["lo"] + fit["hi"]) / 2 use = fit["T"] > 0 rate = np.where(use, fit["n"] / np.maximum(fit["T"], 1), np.nan) err = np.where(use, np.sqrt(np.maximum(fit["n"], 1)) / np.maximum(fit["T"], 1), np.nan) a.errorbar(mid, rate, yerr=err, fmt="o", color="k", capsize=3, label="observed (declustered, completeness-corrected)") for bs, ls, lab in ((0, "-", "model, best b"), (-1, ":", "b + 1 sigma"), (1, ":", "b - 1 sigma")): beta = fit["beta"] + bs * fit["sigma_beta"] Ab = A_for_beta(fit, beta) a.plot(mid, Ab * (np.exp(-beta * (fit["lo"] - M0_FIT)) - np.exp(-beta * (fit["hi"] - M0_FIT))), ls, color="tab:red", label=lab) a.set_yscale("log") a.set_xlabel("Magnitude (bin centre, 0.5 wide)") a.set_ylabel("Events per year per bin") a.set_title(f"Recurrence within {ZONE_KM:.0f} km: b = {fit['b']:.2f}") a.legend(fontsize=8) a.grid(alpha=.3, which="both") a = ax[1] bt = fc["backtest"] xs = np.arange(len(bt)) a.bar(xs - 0.2, [b["expected"] for b in bt], 0.4, color="tab:red", label=f"expected (model fitted before 2000)") a.bar(xs + 0.2, [b["observed"] for b in bt], 0.4, color="k", label="observed 2000-2026") a.set_xticks(xs) a.set_xticklabels([b["bin"] for b in bt], rotation=30) a.set_yscale("log") a.set_title("Back-test: predicted vs actual counts, 2000-2026") a.legend(fontsize=8) a.grid(alpha=.3, axis="y", which="both") a = ax[2] dec = np.arange(1900, 2040, 10) z45 = zone[zone.mag_used >= 4.5] a.bar(dec[:-1] + 3, np.histogram(z45.year_f, dec)[0], width=3.6, color="0.65", label="all events M>=4.5") a.bar(dec[:-1] + 7, np.histogram(z45[z45.mainshock].year_f, dec)[0], width=3.6, color="tab:blue", label="after declustering") a.set_yscale("log") a.set_xlabel("Decade") a.set_title(f"Declustering: {int(z45.mainshock.sum())} of {len(z45)} events (M>=4.5) kept") a.legend(fontsize=8) plt.tight_layout() plt.savefig(path, dpi=110) plt.close() def fig_hazard(fc, path): fig = plt.figure(figsize=(23, 6)) gs = GridSpec(1, 4, figure=fig, width_ratios=[1.3, 1, 1, 1], wspace=0.35) a = fig.add_subplot(gs[0]) x = fc["x"] a.fill_between(x, np.maximum(fc["lo16"], 1e-12), np.maximum(fc["hi84"], 1e-12), color="tab:red", alpha=.2, label="16-84% of logic tree") a.plot(x, fc["mean"], color="tab:red", lw=2.2, label="mean total (slip 0-4 mm/yr)") if "hyp" in fc: a.plot(x, fc["envelope"], color="tab:purple", lw=1.4, ls="-", alpha=.8, label="envelope = max(A, B)") for (n, h), c in zip(fc["hyp"].items(), ("tab:orange", "tab:green")): a.plot(x, h["mean"], color=c, lw=1.1, ls=":", label=f"hypothesis {n.split('_')[0]}: {n.split('_', 1)[1].replace('_', ' ')} mm/yr") a.plot(x, np.maximum(fc["mean_bg"], 1e-12), color="tab:blue", lw=1.3, label="background seismicity") a.plot(x, np.maximum(fc["mean_f"], 1e-12), color="k", lw=1.3, ls="--", label="Karakoram Fault (characteristic)") for rp, d in fc["rp_table"].items(): a.axhline(1 / rp, color="0.6", lw=.7) a.text(x[0] * 1.05, 1 / rp * 1.1, f"{rp} yr", fontsize=8, color="0.35") if np.isfinite(d["pga_mean_g"]): a.plot([d["pga_mean_g"]], [1 / rp], "o", color="tab:red") a.set_xscale("log") a.set_yscale("log") a.set_xlim(0.005, 2) a.set_ylim(1e-5, 1) a.set_xlabel("PGA at the site (g, rock)") a.set_ylabel("Annual rate of exceedance") a.set_title("Seismic hazard curve") a.legend(fontsize=8, loc="lower left") a.grid(alpha=.3, which="both") for k, rp in enumerate((72, 475, 2475)): a = fig.add_subplot(gs[k + 1]) d = fc["dis"][rp] H = d["H"] * 100 im = a.imshow(H, origin="lower", aspect="auto", cmap="viridis") a.set_xticks(range(H.shape[1])) a.set_xticklabels([f"{int(d['r_edges'][i])}-{int(round(d['r_edges'][i+1]))}" for i in range(H.shape[1])], rotation=30, fontsize=8) a.set_yticks(range(H.shape[0])) a.set_yticklabels([f"M{d['m_edges'][i]:.1f}-{d['m_edges'][i+1]:.1f}" for i in range(H.shape[0])], fontsize=8) for i in range(H.shape[0]): for j in range(H.shape[1]): if H[i, j] >= 1: a.text(j, i, f"{H[i,j]:.0f}", ha="center", va="center", color="w" if H[i, j] < H.max() * .6 else "k", fontsize=8) a.set_xlabel("Distance (km)") a.set_title(f"What causes the {rp}-yr PGA ({d['x0']:.2f} g)?\nmean M{d['mean_M']:.1f}, % contribution") plt.colorbar(im, ax=a, fraction=0.046) plt.savefig(path, dpi=110, bbox_inches="tight") plt.close() def fig_future_sources(ev, rel, fc, args, path, trace): from matplotlib.colors import Normalize coslat = np.cos(np.radians(SITE_LAT)) g = fc["grid"] n = int(round(2 * ZONE_KM / GRID_KM)) + 1 arr = np.full((n, n), np.nan) ix = np.round((g["x"] + ZONE_KM) / GRID_KM).astype(int) iy = np.round((g["y"] + ZONE_KM) / GRID_KM).astype(int) arr[iy, ix] = np.log10(np.maximum(fc["cell_rate"], 1e-12)) half = GRID_KM / 2 ext = [SITE_LON + (-ZONE_KM - half) / (111.2 * coslat), SITE_LON + (ZONE_KM + half) / (111.2 * coslat), SITE_LAT + (-ZONE_KM - half) / 111.2, SITE_LAT + (ZONE_KM + half) / 111.2] fig, a = plt.subplots(figsize=(11, 9.5)) vmax = np.nanmax(arr) im = a.imshow(arr, origin="lower", extent=ext, cmap="magma_r", vmin=vmax - 3.5, vmax=vmax, aspect=1 / coslat) cb = plt.colorbar(im, ax=a, fraction=0.04, pad=0.02) cb.set_label(f"log10 annual rate per {GRID_KM:.0f}x{GRID_KM:.0f} km cell of earthquakes that shake the site at >= {fc['x_map']:.2f} g") draw_rings(a, (50, 100, 200, 300, 400), color="k", lw=.7, ls="--", alpha=.6) for rad in (50, 100, 200, 300, 400): a.text(SITE_LON, SITE_LAT + rad / 111.2, f"{rad} km", fontsize=8, ha="center", va="bottom") a.scatter(rel.lon, rel.lat, s=10, facecolor="none", edgecolor="cyan", lw=.8, label="design-relevant events (past)") if trace is not None: a.plot(trace[0], trace[1], color="darkred", lw=2, label="fault trace") a.scatter([SITE_LON], [SITE_LAT], marker="*", s=420, c="red", edgecolor="k", zorder=6, label="site") r = fc["rp_table"] txt = "Mean PGA at site (rock):\n" + "\n".join(f" {k:>4} yr return: {r[k]['pga_mean_g']:.2f} g" for k in (475, 975, 2475)) a.text(0.02, 0.98, txt, transform=a.transAxes, va="top", fontsize=9, family="monospace", bbox=dict(boxstyle="round", fc="white", alpha=.85)) a.legend(loc="lower left", fontsize=8) a.set_xlabel("Longitude") a.set_ylabel("Latitude") a.set_title("Where future shaking at the site will come from (background seismicity model;\n" "the Karakoram Fault source, ~1.6 km from the site, is added separately and is not shown)") plt.savefig(path, dpi=110, bbox_inches="tight") plt.close() # -------------------------------------------------------------------------- # Main # -------------------------------------------------------------------------- def main(): global SIGMA_MODEL, MERGE_MAG_RULE, MB_OFFSET ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--catalog", default="4-to-10-further-away.csv") ap.add_argument("--historic", default="earthquakes.json") ap.add_argument("--outdir", default="out") ap.add_argument("--gmpe", default="auto", choices=["auto", "pygmm", "embedded", "both"]) ap.add_argument("--scenario-mag", type=float, default=7.3) ap.add_argument("--assume-hist-mag", type=float, default=7.5, help="bounding magnitude for NOAA events that have no magnitude") ap.add_argument("--min-pga", type=float, default=0.02, help="rule A: median PGA threshold (g)") ap.add_argument("--min-pga84", type=float, default=0.05, help="rule B: 84th-percentile PGA threshold (g)") ap.add_argument("--smooth-km", type=float, default=50.0, help="Gaussian smoothing distance of the background seismicity") ap.add_argument("--coupling", type=float, default=1.0, help="fraction of Karakoram Fault slip released in large earthquakes") ap.add_argument("--completeness", default="", help='override completeness years, e.g. "4.0:1976,5.0:1965"') ap.add_argument("--fault-trace", default="", help="optional CSV (lon,lat per row) of the fault trace, drawn on the maps") ap.add_argument("--sigma-model", choices=("bssa14", "fixed"), default="bssa14", help="ground-motion scatter: BSSA14 magnitude/distance-dependent (default) or a fixed 0.65") ap.add_argument("--max-depth-km", type=float, default=0.0, help="SENSITIVITY ONLY: drop catalogue events deeper than this (0 = keep all). BSSA14 is a shallow-crustal model; many " "catalogue depths are default values (33 or 10 km), so this tests the effect of deeper sources on the background rates") ap.add_argument("--merge-mag", choices=("max", "catalogue"), default="max", help="magnitude of a USGS event also listed by NOAA: larger of the two (default; mb saturates) or the catalogue value (sensitivity)") ap.add_argument("--mb-offset", type=float, default=0.0, help="SENSITIVITY ONLY: add this to catalogue magnitudes of type mb before anything else (not a calibrated mb->Mw conversion)") args = ap.parse_args() SIGMA_MODEL = args.sigma_model MERGE_MAG_RULE = args.merge_mag MB_OFFSET = args.mb_offset os.makedirs(args.outdir, exist_ok=True) mode, have_pygmm = choose_mode(args.gmpe) lines = [] def say(s=""): print(s) lines.append(s) cat, cinfo = load_catalogue(args.catalog) if MB_OFFSET: cat.loc[cat["magType"] == "mb", "mag"] = cat.loc[cat["magType"] == "mb", "mag"] + MB_OFFSET n_deep_dropped = 0 if args.max_depth_km > 0: keep = cat["depth"].isna() | (cat["depth"] <= args.max_depth_km) n_deep_dropped = int((~keep).sum()) cat = cat[keep].reset_index(drop=True) hist, meta = load_historic(args.historic) ev, hist = build_merged(cat, hist) ev = add_distances_and_pga(ev, args.assume_hist_mag, mode) n_matched = int((hist.cat_pos >= 0).sum()) say("=" * 72) say("DATA") say(f"catalogue file: {cinfo['raw']} rows; dropped {cinfo['duplicates']} duplicate ids and " f"{cinfo['non_earthquakes']} non-earthquakes (nuclear explosions) -> {len(cat)} earthquakes, " f"{cat.time.min():%Y-%m-%d} to {cat.time.max():%Y-%m-%d}, M{cat.mag.min():.1f}-{cat.mag.max():.1f}") say(f"NOAA json: {meta['n_items']} items ({meta['n_no_coords']} without coordinates, skipped); file says page " f"{meta.get('page')} of {meta.get('totalPages')}, {meta.get('totalItems')} items in total; " f"years {hist.year.min():.0f} to {hist.year.max():.0f}") if meta["n_items"] < meta.get("totalItems", 0): say(f" WARNING: only {meta['n_items']} of {meta['totalItems']} NOAA items are in this file. " f"Fetch the other page(s).") say(f"MERGED: {len(ev)} distinct earthquakes = {int((ev.source=='USGS').sum())} catalogue-only + " f"{int((ev.source=='USGS+NOAA').sum())} in both + {int((ev.source=='NOAA').sum())} NOAA-only " f"({n_matched} post-{CATALOGUE_START} NOAA events matched to a catalogue event and counted once)") say(f"scored with the ground-motion model (<= {BSSA14_MAX_KM:.0f} km): {int(ev.scored.sum())} events") if MB_OFFSET or MERGE_MAG_RULE != "max" or n_deep_dropped or args.completeness: say(f"SENSITIVITY RUN (not the base case): --merge-mag {MERGE_MAG_RULE}, --mb-offset {MB_OFFSET:+.2f}, " f"--max-depth-km {args.max_depth_km:g} ({n_deep_dropped} catalogue events dropped), --completeness '{args.completeness}'") say(f"ground-motion model used for results: {mode}" + ("" if mode == "pygmm" else " (embedded coefficients: UNVERIFIED, see docstring)")) sc = ev[ev.scored].copy() if args.gmpe == "both" or (args.gmpe == "auto" and have_pygmm): alt = "embedded" if mode == "pygmm" else "pygmm" other = pga(sc["mag_used"].values, sc["r_eff"].values, alt) rel = np.abs(other / sc["pga_g"].values - 1) say(f"CROSS-CHECK pygmm vs embedded: max |diff| = {rel.max()*100:.2f}%, " f"median = {np.median(rel)*100:.2f}% (should be ~0 if the typed coefficients are right)") say("=" * 72) say("EVENTS BY EPICENTRAL DISTANCE (merged dataset)") say(f"{'radius km':>9} {'N(all)':>8} {'maxM':>5} {'N(M>=5)':>8} {'N(M>=6)':>8} {'N(M>=7)':>8}") for rad in (25, 50, 100, 150, 200, 300, 500, 1000, 1700): s = ev[ev.r_epi <= rad] if len(s): say(f"{rad:9d} {len(s):8d} {s.mag_used.max():5.2f} {(s.mag_used>=5).sum():8d} " f"{(s.mag_used>=6).sum():8d} {(s.mag_used>=7).sum():8d}") say("=" * 72) say("TOP 15 EVENTS BY ESTIMATED MEDIAN PGA AT THE SPUR (merged dataset)") for _, r in sc.sort_values("pga_g", ascending=False).head(15).iterrows(): say(f" {r.date[:10]:>10} M{r.mag_used:4.2f} epi {r.r_epi:6.1f} km Rjb {r.rjb:6.1f} km " f"PGA {r.pga_g:.3f} g [{r.source}] {r.place}") for thr in (0.01, 0.02, 0.05, 0.10): say(f" events with median PGA >= {thr:4.2f} g: {(sc.pga_g>=thr).sum():4d} " f"(84th pct: {(sc.pga84_g>=thr).sum():4d}) of {len(sc)} scored") say("=" * 72) say("NOAA EVENTS CLOSEST TO THE SPUR") noaa_all = ev[ev.source.isin(["NOAA", "USGS+NOAA"])] for _, r in noaa_all.sort_values("r_epi").head(12).iterrows(): m = "no magnitude" if r.mag_assumed else f"M{r.mag_used:.1f}" inten = "" if pd.isna(r.noaa_intensity) else f", intensity {r.noaa_intensity:.0f}" say(f" {r.date:>10} {r.r_epi:6.0f} km {m}{inten} {r.noaa_name}") say(f" nearest NOAA event: {noaa_all.r_epi.min():.0f} km; within 200 km: {(noaa_all.r_epi<=200).sum()}, " f"within 500 km: {(noaa_all.r_epi<=500).sum()}") unk = sc[sc.mag_assumed] if len(unk): say(f" scored events with no magnitude, scored at an ASSUMED M{args.assume_hist_mag}:") for _, r in unk.sort_values("r_epi").iterrows(): say(f" {r.date:>10} {r.r_epi:5.0f} km bounding PGA {r.pga_g:.3f} g {r.place}") imax = sc["pga_g"].idxmax() max_hist = float(sc.loc[imax, "pga_g"]) hist_m = float(sc.loc[imax, "mag_used"]) say(f" largest scored median PGA, all data: {max_hist:.3f} g (M{hist_m:.1f}, {sc.loc[imax,'date'][:10]}, " f"{sc.loc[imax,'place']})") say("=" * 72) say("SCENARIO: rupture on the Karakoram Fault") scen_m = np.array([7.0, args.scenario_mag, 7.6]) scen_table = {} for rj in (0.5, SCEN_RJB_KM, 5.0, 10.0): vals = pga(scen_m, np.full(3, rj), mode) scen_table[f"rjb_{rj}_km"] = {f"M{m:.1f}": round(float(v), 3) for m, v in zip(scen_m, vals)} say(" Rjb %4.1f km: " % rj + " ".join(f"M{m:.1f} -> {v:.2f} g" for m, v in zip(scen_m, vals))) scen_pga = float(pga([args.scenario_mag], [SCEN_RJB_KM], mode)[0]) say(f" chosen scenario M{args.scenario_mag} at {SCEN_RJB_KM} km: median {scen_pga:.2f} g, " f"84th pct ~{scen_pga*scen_factor(args.scenario_mag):.2f} g") say(f" ratio scenario / largest historic shaking: {scen_pga/max_hist:.1f}x") say("=" * 72) say("SLIP BUDGET (why ~100 years of catalogue says little)") span = 2026 - CATALOGUE_START say(f"{'rate mm/yr':>10} {'deficit since 1902 (m)':>24} {'years to build 3 m':>20}") for rate in (0.5, 1, 2, 3, 4): say(f"{rate:10.1f} {rate*span/1000:24.2f} {3000/rate:20.0f}") say(" (0 mm/yr, an inactive Nubra segment, builds no deficit)") say("=" * 72) say("NEWMARK DISPLACEMENT (Jibson 2007 eq. 8; scatter ~0.5 log units, screening only)") say(f"{'ac (g)':>7} {'historic max':>14} {'scenario med':>14} {'scenario 84th':>14} (cm; * = ac/PGA outside {JIBSON_RATIO_RANGE[0]}-{JIBSON_RATIO_RANGE[1]}: possible extrapolation)") for ac in (0.02, 0.05, 0.10, 0.20, 0.30): a = newmark_cm([ac], max_hist, hist_m)[0] b = newmark_cm([ac], scen_pga, args.scenario_mag)[0] c = newmark_cm([ac], scen_pga * scen_factor(args.scenario_mag), args.scenario_mag)[0] fa = "*" if extrapolated(ac, max_hist) else " " fb = "*" if extrapolated(ac, scen_pga) else " " fc_ = "*" if extrapolated(ac, scen_pga * scen_factor(args.scenario_mag)) else " " say(f"{ac:7.2f} {a:13.3f}{fa} {b:13.1f}{fb} {c:13.1f}{fc_}") # ---- completeness table (merged dataset, all distances and within 500 km) say("=" * 72) say("COMPLETENESS: events per decade, merged dataset (all distances | within 500 km)") inst = ev[ev.year_f >= CATALOGUE_START] d_all = (inst.year_f // 10 * 10).astype(int).value_counts().sort_index() d_500 = (inst[inst.r_epi <= 500].year_f // 10 * 10).astype(int).value_counts().sort_index() say(" " + ", ".join(f"{d}s:{n}|{int(d_500.get(d, 0))}" for d, n in d_all.items())) say(f" pre-{CATALOGUE_START} (NOAA only): {int((ev.year_f < CATALOGUE_START).sum())} events") # ---- design-relevant JSON jpath = os.path.join(args.outdir, "design_relevant_earthquakes.json") n_rel = write_design_json(jpath, ev, args, mode, scen_pga, max_hist, scen_table) say("=" * 72) say(f"DESIGN-RELEVANT EVENTS written to design_relevant_earthquakes.json: {n_rel} events") rel = relevant_table(ev, args) write_geojson(os.path.join(args.outdir, "design_relevant_earthquakes.geojson"), rel) trace = read_fault_trace(args.fault_trace) # ---- probabilistic forecast comp = parse_completeness(args.completeness) fc = run_forecast(ev, args, mode, comp, say) write_forecast_json(os.path.join(args.outdir, "future_earthquake_forecast.json"), fc, args, mode, comp, scen_pga, max_hist, hist_m) say("=" * 72) say("wrote future_earthquake_forecast.json and design_relevant_earthquakes.geojson") fig_design_map(ev, rel, args, os.path.join(args.outdir, "fig5_design_events_map.png"), trace) fig_recurrence(fc, os.path.join(args.outdir, "fig6_recurrence.png")) fig_hazard(fc, os.path.join(args.outdir, "fig7_hazard.png")) fig_future_sources(ev, rel, fc, args, os.path.join(args.outdir, "fig8_future_sources.png"), trace) # ---------------------------------------------------------------------- # FIGURES # ---------------------------------------------------------------------- src_style = {"USGS": dict(c="tab:blue", label="catalogue only"), "USGS+NOAA": dict(c="tab:purple", label="catalogue + NOAA (matched)"), "NOAA": dict(c="tab:red", label="NOAA only")} coslat = np.cos(np.radians(SITE_LAT)) def ring(ax, rad, **kw): th = np.linspace(0, 2 * np.pi, 361) ax.plot(SITE_LON + rad / (111.2 * coslat) * np.cos(th), SITE_LAT + rad / 111.2 * np.sin(th), **kw) # Fig 1: maps fig, ax = plt.subplots(1, 2, figsize=(17, 7.6)) a = ax[0] s = ev[(ev.r_epi <= 400) & (ev.source != "NOAA")] a.scatter(s.lon, s.lat, s=(s.mag_used - 3.5).clip(lower=0.1) ** 3 * 9, c="tab:blue", alpha=.35, edgecolor="k", lw=.3, label="catalogue M>=4 (size = M)") hh = ev[(ev.r_epi <= 400) & ev.source.isin(["NOAA", "USGS+NOAA"])] a.scatter(hh.lon, hh.lat, marker="D", s=70, facecolor="none", edgecolor="tab:red", lw=1.4, label="NOAA significant") for rad, ls in ((50, "-"), (100, "--"), (200, ":"), (400, "-.")): ring(a, rad, color="k", ls=ls, lw=1) a.text(SITE_LON + rad / (111.2 * coslat) * 0.72, SITE_LAT + rad / 111.2 * 0.72 + 0.03, f"{rad} km", fontsize=9) a.scatter([SITE_LON], [SITE_LAT], marker="*", s=380, c="red", edgecolor="k", zorder=5, label="site") for _, r in hh.nsmallest(6, "r_epi").iterrows(): a.annotate(r.date[:4], (r.lon, r.lat), xytext=(4, 4), textcoords="offset points", fontsize=8, color="tab:red") a.set_xlim(SITE_LON - 5.5, SITE_LON + 5.5) a.set_ylim(SITE_LAT - 4.3, SITE_LAT + 4.3) a.set_aspect(1 / coslat) a.set_xlabel("Longitude") a.set_ylabel("Latitude") a.legend(loc="lower left", fontsize=8) a.set_title("Within 400 km (merged dataset)") a = ax[1] a.scatter(ev.lon, ev.lat, s=(ev.mag_used - 3.5).clip(lower=0.1) ** 3 * 4, c="tab:blue", alpha=.25, edgecolor="none") big = ev[ev.mag_used >= 7.5] a.scatter(big.lon, big.lat, s=(big.mag_used - 3.5) ** 3 * 4, facecolor="none", edgecolor="k", lw=1) for rad, ls in ((200, ":"), (500, "--"), (1000, "-"), (1500, "-.")): ring(a, rad, color="k", ls=ls, lw=1) a.scatter([SITE_LON], [SITE_LAT], marker="*", s=380, c="red", edgecolor="k", zorder=5) for _, r in big.nsmallest(8, "r_epi").iterrows(): a.annotate(f"{r.date[:4]} M{r.mag_used:.1f}", (r.lon, r.lat), xytext=(5, 4), textcoords="offset points", fontsize=8) a.set_aspect(1 / coslat) a.set_xlabel("Longitude") a.set_title("Regional view: rings at 200, 500, 1000, 1500 km (M>=7.5 outlined)") plt.tight_layout() plt.savefig(os.path.join(args.outdir, "fig1_maps.png"), dpi=110) plt.close() # Fig 2: PGA history, broken time axis (ancient | instrumental) fig, ax = plt.subplots(1, 2, figsize=(17, 6.4), sharey=True, gridspec_kw={"width_ratios": [1, 1.6], "wspace": 0.03}) a0, a1 = ax pre = sc[sc.year_f < CATALOGUE_START] known, unkn = pre[~pre.mag_assumed], pre[pre.mag_assumed] a0.scatter(known.year_f, known.pga_g, marker="D", s=60, facecolor="none", edgecolor="tab:red", label="NOAA, listed M") a0.scatter(unkn.year_f, unkn.pga_g, marker="x", s=60, c="tab:red", label=f"NOAA, no M (bounding M{args.assume_hist_mag})") a0.set_xlim(-300, 1905) a0.set_title("Historic / ancient record (NOAA significant earthquakes)") a0.set_xlabel("Year") a0.set_ylabel("Estimated median PGA at spur (g, rock)") a0.legend(loc="lower left", fontsize=8) post = sc[sc.year_f >= CATALOGUE_START] for k, st in src_style.items(): p = post[post.source == k] if len(p): a1.scatter(p.year_f, p.pga_g, s=16 if k == "USGS" else 50, c=st["c"], alpha=.5 if k == "USGS" else .9, marker="o" if k == "USGS" else "D", label=st["label"]) top5 = post.nlargest(5, "pga_g") a1.scatter(top5.year_f, top5.pga_g, s=140, facecolor="none", edgecolor="k", label="5 largest") a1.scatter([2035], [scen_pga], marker="*", s=450, c="red", edgecolor="k", zorder=6) a1.text(1990, scen_pga * 1.18, f"Scenario M{args.scenario_mag} at {SCEN_RJB_KM} km: ~{scen_pga:.2f} g (median)", color="red", fontsize=10) a1.set_xlim(1900, 2042) a1.set_title("Instrumental record, 1902-2026") a1.set_xlabel("Year") a1.legend(loc="lower right", fontsize=8) for a in ax: a.set_yscale("log") a.set_ylim(3e-4, 1.5) a.axhline(AC_LOOSE_DEBRIS_G, color="tab:orange", lw=1.5) a.axhline(0.1, color="tab:red", lw=1.1, ls="--") a.grid(alpha=.3, which="both") a1.text(1903, AC_LOOSE_DEBRIS_G * 1.1, "0.05 g: example of a very weak slope (illustrative; ac is slope-specific)", fontsize=9, color="tab:orange") a1.text(1903, 0.11, "0.1 g", fontsize=9, color="tab:red") plt.savefig(os.path.join(args.outdir, "fig2_pga_history.png"), dpi=110, bbox_inches="tight") plt.close() # Fig 3: Newmark curves acs = np.linspace(0.01, 0.4, 200) fig, a = plt.subplots(figsize=(8.5, 6)) a.plot(acs, newmark_cm(acs, max_hist, hist_m), label=f"largest past shaking ({max_hist:.2f} g, M{hist_m:.1f})", color="tab:blue") a.plot(acs, newmark_cm(acs, scen_pga, args.scenario_mag), label=f"scenario median ({scen_pga:.2f} g, M{args.scenario_mag})", color="red") a.plot(acs, newmark_cm(acs, scen_pga * scen_factor(args.scenario_mag), args.scenario_mag), "--", label="scenario 84th percentile", color="darkred") a.axvline(AC_LOOSE_DEBRIS_G, color="tab:orange", lw=1.3) a.text(AC_LOOSE_DEBRIS_G * 1.04, 3e-3, "ac = 0.05 g\nvery weak slope", color="tab:orange", fontsize=9) a.axhline(1.0, color="gray", ls=":") a.text(0.25, 1.15, "1 cm: illustrative screening level", color="gray", fontsize=9) a.set_yscale("log") a.set_ylim(1e-3, 1e3) a.set_xlabel("Critical acceleration of the slope, ac (g)") a.set_ylabel("Newmark displacement (cm, median; scatter ~x3)") a.set_title("Sliding-block displacement, Jibson (2007) eq. 8") a.legend() a.grid(alpha=.3, which="both") plt.tight_layout() plt.savefig(os.path.join(args.outdir, "fig3_newmark.png"), dpi=110) plt.close() # Fig 4: completeness of the COMBINED dataset (all events, all distances) fig = plt.figure(figsize=(17, 10)) gs = GridSpec(2, 4, figure=fig, hspace=0.32, wspace=0.45) ax_a = fig.add_subplot(gs[0, 0:2]) ax_b = fig.add_subplot(gs[0, 2:4]) ax_c = fig.add_subplot(gs[1, 0:2]) ax_d = fig.add_subplot(gs[1, 2:4]) old = ev[ev.year_f < 1900] cent = np.arange(-300, 2000, 100) n_old = np.histogram(old.year_f, bins=cent)[0] n_old5 = np.histogram(old[old.r_epi <= 500].year_f, bins=cent)[0] ax_a.bar(cent[:-1] + 50, n_old, width=90, color="tab:red", alpha=.45, label="all distances") ax_a.bar(cent[:-1] + 50, n_old5, width=90, color="tab:red", label="within 500 km") ax_a.set_xlabel("Year (100-year bins)") ax_a.set_ylabel("NOAA events per century") ax_a.set_title(f"Pre-1900: NOAA significant earthquakes only (n = {len(old)})") ax_a.legend(fontsize=8) dec = np.arange(1900, 2040, 10) bottoms = np.zeros(len(dec) - 1) for k in ("USGS", "USGS+NOAA", "NOAA"): n = np.histogram(inst[inst.source == k].year_f, bins=dec)[0] ax_b.bar(dec[:-1] + 5, n, width=8, bottom=bottoms, color=src_style[k]["c"], label=src_style[k]["label"]) bottoms += n n500 = np.histogram(inst[inst.r_epi <= 500].year_f, bins=dec)[0] ax_b.step(dec[:-1] + 5, n500, where="mid", color="k", lw=1.5, marker="o", ms=4, label="within 500 km (all sources)") ax_b.set_yscale("log") ax_b.set_ylim(1.5, max(bottoms.max(), 10) * 2.5) ax_b.set_xlabel("Decade") ax_b.set_ylabel("Events per decade (log)") ax_b.set_title(f"1900 onward: whole merged dataset (n = {len(inst)}); counts jump in the 1970s") ax_b.legend(fontsize=8) for thr, col in ((4.0, "tab:blue"), (5.0, "tab:green"), (6.0, "tab:orange"), (7.0, "tab:red")): t = ev[(ev.mag_used >= thr)].sort_values("year_f") t = t[t.year_f >= 1900] if len(t): ax_c.step(t.year_f.values, np.arange(1, len(t) + 1), where="post", color=col, label=f"M>={thr:.0f} (n = {len(t)})") ax_c.set_yscale("log") ax_c.set_xlabel("Year") ax_c.set_ylabel("Cumulative number of events (log)") ax_c.set_title("Cumulative counts by magnitude: a kink in the slope marks the start of complete reporting") ax_c.legend(fontsize=8, loc="lower right") ax_c.grid(alpha=.3, which="both") for k, st in src_style.items(): p = inst[inst.source == k] ax_d.scatter(p.year_f, p.mag_used, s=5 if k == "USGS" else 40, c=st["c"], alpha=.3 if k == "USGS" else .9, marker="o" if k == "USGS" else "D", label=st["label"]) ax_d.set_xlabel("Year") ax_d.set_ylabel("Magnitude") ax_d.set_title("Magnitude vs time: the lower envelope rises going back in time") ax_d.legend(fontsize=8, loc="upper left", markerscale=1.5) ax_d.grid(alpha=.3) plt.savefig(os.path.join(args.outdir, "fig4_completeness.png"), dpi=110, bbox_inches="tight") plt.close() # ---- audit outputs cols = ["source", "event_id", "date", "lat", "lon", "depth", "mag", "mag_type", "mag_assumed", "place", "noaa_intensity", "noaa_deaths", "r_epi", "rjb", "r_eff", "pga_g", "pga84_g"] sc.sort_values("pga_g", ascending=False)[cols].to_csv(os.path.join(args.outdir, "pga_per_event.csv"), index=False) hist_out = hist.copy() hist_out["r_epi"] = haversine_km(SITE_LAT, SITE_LON, hist_out.latitude.values, hist_out.longitude.values) hist_out["matched_catalogue_id"] = [cat["id"].iloc[k] if k >= 0 else "" for k in hist_out.cat_pos] hist_out.sort_values("r_epi")[["year", "month", "day", "locationName", "latitude", "longitude", "mag", "intensity", "r_epi", "matched_catalogue_id"]].to_csv( os.path.join(args.outdir, "historic_by_distance.csv"), index=False) with open(os.path.join(args.outdir, "summary.txt"), "w") as fh: fh.write("\n".join(lines) + "\n") print(f"\nwrote figures, CSVs, JSON and summary.txt to {args.outdir}/") if __name__ == "__main__": main()