hyperdd 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hyperdd/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """HyperDD: Scalable double-difference earthquake relocation."""
2
+
3
+ __version__ = "0.1.0"
hyperdd/config.py ADDED
@@ -0,0 +1,186 @@
1
+ """Parse hypoDD.inp control files (v1 and v2 formats).
2
+
3
+ Returns a HypoDDConfig dataclass with all parameters needed to run hypoDD.
4
+ """
5
+
6
+ import numpy as np
7
+
8
+ from .core.datatypes import HypoDDConfig, VelocityModel1D
9
+
10
+
11
+ def _read_noncomment_lines(filepath):
12
+ """Read all non-comment lines from a hypoDD input file.
13
+
14
+ Lines starting with '*' are treated as comments and skipped.
15
+ Blank lines are preserved as empty strings (they can represent
16
+ empty file names). Leading/trailing whitespace is stripped.
17
+ """
18
+ lines = []
19
+ with open(filepath) as f:
20
+ for line in f:
21
+ stripped = line.strip()
22
+ if not stripped.startswith('*'):
23
+ lines.append(stripped)
24
+ return lines
25
+
26
+
27
+ def parse_inp(filepath):
28
+ """Parse a hypoDD.inp control-parameter file.
29
+
30
+ Supports both the v1 format (used by hypoDD 1.x) and the v2 format
31
+ whose first non-comment line is ``hypoDD_2``.
32
+
33
+ Parameters
34
+ ----------
35
+ filepath : str or path-like
36
+ Path to the hypoDD.inp file.
37
+
38
+ Returns
39
+ -------
40
+ HypoDDConfig
41
+ Populated configuration dataclass.
42
+ """
43
+ all_lines = _read_noncomment_lines(filepath)
44
+ cfg = HypoDDConfig()
45
+
46
+ idx = 0
47
+ version = 2 if all_lines[0].startswith('hypoDD') else 1
48
+ if version == 2:
49
+ idx = 1
50
+
51
+ # ---- Input files (blank line = no file) ----
52
+ cfg.fn_cc = all_lines[idx]; idx += 1
53
+ cfg.fn_ct = all_lines[idx]; idx += 1
54
+ cfg.fn_eve = all_lines[idx]; idx += 1
55
+ cfg.fn_sta = all_lines[idx]; idx += 1
56
+
57
+ # ---- Output files (blank line = no file) ----
58
+ cfg.fn_loc = all_lines[idx]; idx += 1
59
+ cfg.fn_reloc = all_lines[idx]; idx += 1
60
+ cfg.fn_stares = all_lines[idx]; idx += 1
61
+ cfg.fn_res = all_lines[idx]; idx += 1
62
+ cfg.fn_srcpar = all_lines[idx]; idx += 1
63
+
64
+ # From here on, skip blank lines (only file names can be blank)
65
+ lines = [l for l in all_lines[idx:] if l]
66
+ idx = 0
67
+
68
+ # ---- Data type selection ----
69
+ parts = lines[idx].split(); idx += 1
70
+ cfg.idata = int(parts[0])
71
+ cfg.iphase = int(parts[1])
72
+ cfg.maxdist = float(parts[2])
73
+
74
+ # ---- Event clustering ----
75
+ # v1: OBSCC OBSCT (2 values)
76
+ # v2: OBSCC OBSCT MINDIST MAXDIST MAXGAP (5 values)
77
+ parts = lines[idx].split(); idx += 1
78
+ cfg.minobs_cc = int(parts[0])
79
+ cfg.minobs_ct = int(parts[1])
80
+ if version == 2 and len(parts) >= 5:
81
+ cfg.minds = float(parts[2])
82
+ cfg.maxds = float(parts[3])
83
+ cfg.maxgap = float(parts[4])
84
+
85
+ # ---- Solution control ----
86
+ # v1: ISTART ISOLV NSET (3 values, no IAQ)
87
+ # v2: ISTART ISOLV IAQ NSET (4 values)
88
+ parts = lines[idx].split(); idx += 1
89
+ cfg.istart = int(parts[0])
90
+ cfg.isolv = int(parts[1])
91
+ if version == 2:
92
+ cfg.iaq = int(parts[2])
93
+ cfg.nset = int(parts[3])
94
+ else:
95
+ cfg.iaq = 0
96
+ cfg.nset = int(parts[2])
97
+
98
+ # ---- Iteration parameters (one line per set) ----
99
+ # NITER WTCCP WTCCS WRCC WDCC WTCTP WTCTS WRCT WDCT DAMP [label]
100
+ for _s in range(cfg.nset):
101
+ parts = lines[idx].split(); idx += 1
102
+ cfg.niter.append(int(parts[0]))
103
+ cfg.wt_ccp.append(float(parts[1]))
104
+ cfg.wt_ccs.append(float(parts[2]))
105
+ cfg.wrcc.append(float(parts[3]))
106
+ cfg.wdcc.append(float(parts[4]))
107
+ cfg.wt_ctp.append(float(parts[5]))
108
+ cfg.wt_cts.append(float(parts[6]))
109
+ cfg.wrct.append(float(parts[7]))
110
+ cfg.wdct.append(float(parts[8]))
111
+ cfg.damp.append(float(parts[9]))
112
+
113
+ # ---- Velocity model ----
114
+ if version == 2:
115
+ # v2 has an explicit IMOD line
116
+ cfg.imod = int(lines[idx]); idx += 1
117
+ else:
118
+ # v1 has no IMOD line; the model is always imod=0
119
+ cfg.imod = 0
120
+
121
+ if cfg.imod == 0:
122
+ # Fixed Vp/Vs: NLAY RATIO, then TOP values, then VEL values
123
+ parts = lines[idx].split(); idx += 1
124
+ nlay = int(parts[0])
125
+ ratio = float(parts[1])
126
+ top = list(map(float, lines[idx].split())); idx += 1
127
+ vel = list(map(float, lines[idx].split())); idx += 1
128
+ cfg.vel_model = VelocityModel1D(
129
+ nl=nlay,
130
+ v=np.array(vel[:nlay], dtype=np.float32),
131
+ top=np.array(top[:nlay], dtype=np.float32),
132
+ ratio=np.array([ratio] * nlay, dtype=np.float32),
133
+ )
134
+ elif cfg.imod == 1:
135
+ # Variable Vp/Vs: TOP vals -9, VEL vals -9, RATIO vals -9
136
+ vals = list(map(float, lines[idx].split())); idx += 1
137
+ top = [v for v in vals if v != -9]
138
+ vals = list(map(float, lines[idx].split())); idx += 1
139
+ vel = [v for v in vals if v != -9]
140
+ vals = list(map(float, lines[idx].split())); idx += 1
141
+ ratios = [v for v in vals if v != -9]
142
+ nlay = len(top)
143
+ cfg.vel_model = VelocityModel1D(
144
+ nl=nlay,
145
+ v=np.array(vel, dtype=np.float32),
146
+ top=np.array(top, dtype=np.float32),
147
+ ratio=np.array(ratios, dtype=np.float32),
148
+ )
149
+ elif cfg.imod == 5:
150
+ # Constant velocity: same format as imod=0 OR individual lines
151
+ # Try NLAY RATIO format first; if only 1 value, it's individual lines
152
+ parts = lines[idx].split()
153
+ if len(parts) >= 2:
154
+ # NLAY RATIO format
155
+ idx += 1
156
+ nlay = int(parts[0])
157
+ ratio = float(parts[1])
158
+ top_vals = list(map(float, lines[idx].split())); idx += 1
159
+ vel_vals = list(map(float, lines[idx].split())); idx += 1
160
+ else:
161
+ # Individual lines: TOP, VEL, RATIO (one value each)
162
+ top_vals = list(map(float, lines[idx].split())); idx += 1
163
+ vel_vals = list(map(float, lines[idx].split())); idx += 1
164
+ ratio_vals = list(map(float, lines[idx].split())); idx += 1
165
+ nlay = len(top_vals)
166
+ ratio = ratio_vals[0]
167
+ cfg.vel_model = VelocityModel1D(
168
+ nl=nlay,
169
+ v=np.array(vel_vals[:nlay], dtype=np.float32),
170
+ top=np.array(top_vals[:nlay], dtype=np.float32),
171
+ ratio=np.array([ratio] * nlay, dtype=np.float32),
172
+ )
173
+
174
+ # ---- Cluster / event selection ----
175
+ if idx < len(lines):
176
+ parts = lines[idx].split(); idx += 1
177
+ cfg.iclust = int(parts[0])
178
+
179
+ # Event IDs (optional, may span multiple lines)
180
+ cusps = []
181
+ while idx < len(lines):
182
+ parts = lines[idx].split(); idx += 1
183
+ cusps.extend([int(p) for p in parts])
184
+ cfg.icusp = np.array(cusps, dtype=np.int32) if cusps else np.array([], dtype=np.int32)
185
+
186
+ return cfg
File without changes
@@ -0,0 +1,65 @@
1
+ import numpy as np
2
+
3
+
4
+ def cluster_events(nev, ev_cusp, ndt, dt_c1, dt_c2, dt_idx, idata, minobs_cc, minobs_ct):
5
+ """Cluster events based on shared observations.
6
+
7
+ Matches Fortran cluster1.f: counts total observations per event pair,
8
+ then links pairs with total >= (minobs_cc + minobs_ct).
9
+
10
+ Returns list of clusters, each a list of event indices (0-indexed).
11
+ """
12
+ # Adjust thresholds by data type (Fortran cluster1.f lines 70-71)
13
+ if idata == 0 or idata == 1:
14
+ minobs_ct = 0
15
+ if idata == 0 or idata == 2:
16
+ minobs_cc = 0
17
+ min_total = minobs_cc + minobs_ct
18
+
19
+ # Count total observations per event pair (Fortran: apair_n)
20
+ pair_count = {}
21
+ for i in range(ndt):
22
+ ic1_cusp = int(dt_c1[i])
23
+ ic2_cusp = int(dt_c2[i])
24
+ key = (min(ic1_cusp, ic2_cusp), max(ic1_cusp, ic2_cusp))
25
+ pair_count[key] = pair_count.get(key, 0) + 1
26
+
27
+ # Union-Find
28
+ parent = list(range(nev))
29
+
30
+ def find(x):
31
+ while parent[x] != x:
32
+ parent[x] = parent[parent[x]]
33
+ x = parent[x]
34
+ return x
35
+
36
+ def union(x, y):
37
+ px, py = find(x), find(y)
38
+ if px != py:
39
+ parent[px] = py
40
+
41
+ # Build cusp -> index map
42
+ cusp_to_idx = {}
43
+ for i in range(nev):
44
+ cusp_to_idx[int(ev_cusp[i])] = i
45
+
46
+ # Merge events with sufficient links (Fortran cluster1.f line 82)
47
+ for (c1, c2), n_obs in pair_count.items():
48
+ if c1 not in cusp_to_idx or c2 not in cusp_to_idx:
49
+ continue
50
+ if n_obs >= min_total:
51
+ union(cusp_to_idx[c1], cusp_to_idx[c2])
52
+
53
+ # Collect clusters
54
+ clusters = {}
55
+ for i in range(nev):
56
+ root = find(i)
57
+ if root not in clusters:
58
+ clusters[root] = []
59
+ clusters[root].append(i)
60
+
61
+ # Sort by size (largest first), filter singletons
62
+ result = sorted(clusters.values(), key=len, reverse=True)
63
+ result = [c for c in result if len(c) > 1]
64
+
65
+ return result
@@ -0,0 +1,65 @@
1
+ """Data structures for hypodd, corresponding to Fortran common blocks and parameters."""
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+ import numpy as np
6
+
7
+
8
+ @dataclass
9
+ class VelocityModel1D:
10
+ """1D velocity model corresponding to the MOD structure in hypoDD."""
11
+
12
+ nl: int # number of layers
13
+ v: np.ndarray # P velocities (km/s), shape (nl,)
14
+ top: np.ndarray # layer tops (km), shape (nl,)
15
+ ratio: np.ndarray # Vp/Vs per layer, shape (nl,)
16
+
17
+
18
+ @dataclass
19
+ class HypoDDConfig:
20
+ """Configuration parameters for hypoDD, corresponding to hypoDD.inp."""
21
+
22
+ # Input files
23
+ fn_cc: str = ""
24
+ fn_ct: str = ""
25
+ fn_eve: str = ""
26
+ fn_sta: str = ""
27
+ # Output files
28
+ fn_loc: str = ""
29
+ fn_reloc: str = ""
30
+ fn_res: str = ""
31
+ fn_stares: str = ""
32
+ fn_srcpar: str = ""
33
+ # Parameters
34
+ idata: int = 0 # 1=CC, 2=CT, 3=both
35
+ iphase: int = 0 # 1=P, 2=S, 3=P&S
36
+ maxdist: float = 0.0 # max station-cluster distance
37
+ minobs_cc: int = 0
38
+ minobs_ct: int = 0
39
+ minds: float = -999.0
40
+ maxds: float = -999.0
41
+ maxgap: float = -999.0
42
+ istart: int = 0 # 1=single source, 2=catalog
43
+ isolv: int = 0 # 1=SVD, 2=LSQR
44
+ iaq: int = 0 # airquake removal
45
+ nset: int = 0 # number of iteration sets
46
+ imod: int = 0 # velocity model type
47
+ iclust: int = 0 # cluster to relocate (0=all)
48
+ icusp: np.ndarray = field(default_factory=lambda: np.array([], dtype=np.int32))
49
+ vel_model: VelocityModel1D = None
50
+ # Iteration parameters (lists, one per set)
51
+ niter: list = field(default_factory=list)
52
+ wt_ccp: list = field(default_factory=list)
53
+ wt_ccs: list = field(default_factory=list)
54
+ wrcc: list = field(default_factory=list)
55
+ wdcc: list = field(default_factory=list)
56
+ wt_ctp: list = field(default_factory=list)
57
+ wt_cts: list = field(default_factory=list)
58
+ wrct: list = field(default_factory=list)
59
+ wdct: list = field(default_factory=list)
60
+ damp: list = field(default_factory=list)
61
+ # GraphDD extensions
62
+ gnc_kernel: str = "" # "" = off, "tls", "huber", "cauchy"
63
+ gnc_threshold: float = 3.0 # MAD multiplier for kernel threshold
64
+ solver_backend: str = "lsqr" # "lsqr", "lsmr", "cholesky", "pcg"
65
+ robust_loss: str = None # None, "huber", "cauchy", "tukey"
hyperdd/core/dtres.py ADDED
@@ -0,0 +1,44 @@
1
+ import numpy as np
2
+
3
+
4
+ def compute_residuals(ndt, nsrc, dt_dt, dt_idx, dt_ista, dt_ic1, dt_ic2,
5
+ src_t, tmp_ttp, tmp_tts):
6
+ """Compute double-difference residuals (vectorized).
7
+
8
+ dt_dt: observed differential times
9
+ dt_idx: phase type (1=cc-P, 2=cc-S, 3=ct-P, 4=ct-S)
10
+ dt_ista, dt_ic1, dt_ic2: station and event pair indices (0-indexed)
11
+ src_t: source origin time corrections in milliseconds
12
+ tmp_ttp, tmp_tts: travel time arrays (nsta, nsrc)
13
+
14
+ Returns: dt_cal, dt_res arrays
15
+ """
16
+ dt_cal = np.zeros(ndt, dtype=np.float32)
17
+ dt_res = np.zeros(ndt, dtype=np.float32)
18
+
19
+ if nsrc == 1:
20
+ dt_res[:ndt] = dt_dt[:ndt]
21
+ else:
22
+ ista = dt_ista[:ndt]
23
+ ic1 = dt_ic1[:ndt]
24
+ ic2 = dt_ic2[:ndt]
25
+ idx = dt_idx[:ndt]
26
+
27
+ s_mask = (idx == 2) | (idx == 4)
28
+ p_mask = ~s_mask
29
+
30
+ # P-phase
31
+ if np.any(p_mask):
32
+ tt1_p = tmp_ttp[ista[p_mask], ic1[p_mask]] - src_t[ic1[p_mask]] / 1000.0
33
+ tt2_p = tmp_ttp[ista[p_mask], ic2[p_mask]] - src_t[ic2[p_mask]] / 1000.0
34
+ dt_cal[p_mask] = tt1_p - tt2_p
35
+
36
+ # S-phase
37
+ if np.any(s_mask):
38
+ tt1_s = tmp_tts[ista[s_mask], ic1[s_mask]] - src_t[ic1[s_mask]] / 1000.0
39
+ tt2_s = tmp_tts[ista[s_mask], ic2[s_mask]] - src_t[ic2[s_mask]] / 1000.0
40
+ dt_cal[s_mask] = tt1_s - tt2_s
41
+
42
+ dt_res[:ndt] = dt_dt[:ndt] - dt_cal[:ndt]
43
+
44
+ return dt_cal, dt_res
@@ -0,0 +1,152 @@
1
+ """Sparse Jacobian assembly for the DD system.
2
+
3
+ Builds the weighted sparse Jacobian matrix J and data vector d from
4
+ observation arrays and partial derivatives. This is the core matrix
5
+ that all solver backends (LSQR, Cholesky, PCG) operate on.
6
+
7
+ Factored out from sparse_chol.py so it can be shared across solvers
8
+ and eventually accept per-observation partials directly (no nsta x nsrc arrays).
9
+ """
10
+
11
+ import numpy as np
12
+ from scipy.sparse import csr_matrix
13
+
14
+
15
+ # Constraint weights for fixed events (from Fortran hypoDD)
16
+ _FIX_WEIGHTS = {
17
+ 1: {2: 100.0},
18
+ 2: {2: 100.0, 3: 100.0},
19
+ 3: {0: 10.0, 1: 10.0, 2: 10.0},
20
+ 4: {0: 100.0, 1: 100.0, 2: 100.0, 3: 100.0},
21
+ 5: {3: 1000.0},
22
+ 6: {0: 100.0, 1: 100.0},
23
+ }
24
+
25
+
26
+ def build_dd_system(ndt, nev, nsrc, dt_res, dt_wt, dt_ista, dt_ic1, dt_ic2, dt_idx,
27
+ tmp_xp, tmp_yp, tmp_zp, tmp_xs, tmp_ys, tmp_zs,
28
+ ev_fix, use_float32=True):
29
+ """Build weighted sparse Jacobian G and data vector d for the DD system.
30
+
31
+ Returns
32
+ -------
33
+ G : csr_matrix, shape (nndt, 4*nev)
34
+ Weighted, column-scaled sparse Jacobian.
35
+ d_vec : ndarray, shape (nndt,)
36
+ Weighted data vector (residuals in ms).
37
+ norm : ndarray, shape (4*nev,)
38
+ Column scaling factors (for unscaling solution).
39
+ xp1, yp1, zp1, xp2, yp2, zp2 : ndarray, shape (ndt,)
40
+ Per-observation unweighted partials (for residual update).
41
+ """
42
+ ncol = 4 * nev
43
+ wt = dt_wt[:ndt].copy()
44
+
45
+ # Count constraint entries
46
+ n_fix_entries = 0
47
+ for i in range(nev):
48
+ fix = ev_fix[i]
49
+ if fix in _FIX_WEIGHTS:
50
+ n_fix_entries += len(_FIX_WEIGHTS[fix])
51
+
52
+ max_nnz = 8 * ndt + n_fix_entries
53
+ rows = np.empty(max_nnz, dtype=np.int32)
54
+ cols = np.empty(max_nnz, dtype=np.int32)
55
+ vals = np.empty(max_nnz, dtype=np.float64)
56
+
57
+ nndt = ndt
58
+ max_rows = ndt + n_fix_entries
59
+ d = np.zeros(max_rows, dtype=np.float64)
60
+ d[:ndt] = dt_res[:ndt] * 1000.0 * wt
61
+
62
+ idx = np.arange(ndt)
63
+ ic1 = dt_ic1[:ndt]
64
+ ic2 = dt_ic2[:ndt]
65
+ ista = dt_ista[:ndt]
66
+
67
+ if nsrc == 1:
68
+ k1_arr = np.zeros(ndt, dtype=np.int32)
69
+ k2_arr = np.zeros(ndt, dtype=np.int32)
70
+ else:
71
+ k1_arr = ic1.copy()
72
+ k2_arr = ic2.copy()
73
+
74
+ s_mask = (dt_idx[:ndt] == 2) | (dt_idx[:ndt] == 4)
75
+
76
+ # Vectorized partial extraction
77
+ xp1 = np.where(s_mask, tmp_xs[ista, k1_arr], tmp_xp[ista, k1_arr]).astype(np.float64)
78
+ yp1 = np.where(s_mask, tmp_ys[ista, k1_arr], tmp_yp[ista, k1_arr]).astype(np.float64)
79
+ zp1 = np.where(s_mask, tmp_zs[ista, k1_arr], tmp_zp[ista, k1_arr]).astype(np.float64)
80
+ xp2 = np.where(s_mask, tmp_xs[ista, k2_arr], tmp_xp[ista, k2_arr]).astype(np.float64)
81
+ yp2 = np.where(s_mask, tmp_ys[ista, k2_arr], tmp_yp[ista, k2_arr]).astype(np.float64)
82
+ zp2 = np.where(s_mask, tmp_zs[ista, k2_arr], tmp_zp[ista, k2_arr]).astype(np.float64)
83
+
84
+ # Fill 8 blocks (weighted)
85
+ ptr = 0
86
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic1*4+0; vals[ptr:ptr+ndt] = xp1*wt; ptr += ndt
87
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic1*4+1; vals[ptr:ptr+ndt] = yp1*wt; ptr += ndt
88
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic1*4+2; vals[ptr:ptr+ndt] = zp1*wt; ptr += ndt
89
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic1*4+3; vals[ptr:ptr+ndt] = wt; ptr += ndt
90
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic2*4+0; vals[ptr:ptr+ndt] = -xp2*wt; ptr += ndt
91
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic2*4+1; vals[ptr:ptr+ndt] = -yp2*wt; ptr += ndt
92
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic2*4+2; vals[ptr:ptr+ndt] = -zp2*wt; ptr += ndt
93
+ rows[ptr:ptr+ndt] = idx; cols[ptr:ptr+ndt] = ic2*4+3; vals[ptr:ptr+ndt] = -wt; ptr += ndt
94
+
95
+ # Add ev_fix constraint rows
96
+ k = 0
97
+ for i in range(nev):
98
+ fix = ev_fix[i]
99
+ if fix == 0 or fix not in _FIX_WEIGHTS:
100
+ continue
101
+ for off, weight in _FIX_WEIGHTS[fix].items():
102
+ row_idx = nndt + k
103
+ d[row_idx] = 0.0
104
+ rows[ptr] = row_idx
105
+ cols[ptr] = i * 4 + off
106
+ vals[ptr] = weight
107
+ ptr += 1
108
+ k += 1
109
+ nndt += k
110
+ total_nnz = ptr
111
+
112
+ # Build sparse G
113
+ _dtype = np.float32 if use_float32 else np.float64
114
+ G = csr_matrix(
115
+ (vals[:total_nnz].astype(_dtype), (rows[:total_nnz], cols[:total_nnz])),
116
+ shape=(nndt, ncol), dtype=_dtype,
117
+ )
118
+ d_vec = d[:nndt].astype(_dtype)
119
+
120
+ # Column scaling (same as LSQR: norm = sqrt(sum(G[:,j]^2) / ndt))
121
+ col_sq_sums = np.array(G.power(2).sum(axis=0)).ravel()
122
+ norm = np.sqrt(col_sq_sums / ndt)
123
+ norm[norm == 0] = 1.0
124
+
125
+ from scipy.sparse import diags
126
+ G_scaled = G @ diags(1.0 / norm)
127
+
128
+ return G_scaled, d_vec, norm, xp1, yp1, zp1, xp2, yp2, zp2
129
+
130
+
131
+ def update_residuals(ndt, dt_res, x, ic1, ic2, xp1, yp1, zp1, xp2, yp2, zp2):
132
+ """Update residuals after solve: dt_res -= J_unweighted @ x / 1000."""
133
+ idx = np.arange(ndt)
134
+ ncol = len(x)
135
+
136
+ nnz_data = 8 * ndt
137
+ rows_uw = np.empty(nnz_data, dtype=np.int32)
138
+ cols_uw = np.empty(nnz_data, dtype=np.int32)
139
+ vals_uw = np.empty(nnz_data, dtype=np.float64)
140
+ p = 0
141
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic1*4+0; vals_uw[p:p+ndt] = xp1; p += ndt
142
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic1*4+1; vals_uw[p:p+ndt] = yp1; p += ndt
143
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic1*4+2; vals_uw[p:p+ndt] = zp1; p += ndt
144
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic1*4+3; vals_uw[p:p+ndt] = 1.0; p += ndt
145
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic2*4+0; vals_uw[p:p+ndt] = -xp2; p += ndt
146
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic2*4+1; vals_uw[p:p+ndt] = -yp2; p += ndt
147
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic2*4+2; vals_uw[p:p+ndt] = -zp2; p += ndt
148
+ rows_uw[p:p+ndt] = idx; cols_uw[p:p+ndt] = ic2*4+3; vals_uw[p:p+ndt] = -1.0; p += ndt
149
+
150
+ G_uw = csr_matrix((vals_uw, (rows_uw, cols_uw)), shape=(ndt, ncol), dtype=np.float64)
151
+ dd = G_uw @ x
152
+ dt_res[:ndt] -= dd / 1000.0
@@ -0,0 +1,71 @@
1
+ """Robust kernels and GNC (Graduated Non-Convexity) schedule for GraphDD."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def kernel_weights(residuals, c, kernel="tls", mu=None):
7
+ """Compute IRLS weights for robust kernels.
8
+
9
+ Parameters
10
+ ----------
11
+ residuals : ndarray
12
+ Residual values.
13
+ c : float
14
+ Kernel threshold parameter.
15
+ kernel : str
16
+ One of "l2", "huber", "cauchy", "tls".
17
+ mu : float or None
18
+ GNC surrogate parameter (1.0=convex/L2, 0.0=target kernel).
19
+ If None, use the target kernel directly.
20
+
21
+ Returns
22
+ -------
23
+ w : ndarray
24
+ Per-observation weights in [0, 1].
25
+ """
26
+ r = np.abs(residuals)
27
+
28
+ if mu is not None and kernel == "tls":
29
+ if mu >= 1.0:
30
+ return np.ones_like(r, dtype=np.float64)
31
+ if mu > 0.0:
32
+ return _gnc_tls_weights(r, c, mu)
33
+
34
+ if kernel == "l2":
35
+ return np.ones_like(r, dtype=np.float64)
36
+ elif kernel == "huber":
37
+ w = np.ones_like(r, dtype=np.float64)
38
+ mask = r > c
39
+ w[mask] = c / r[mask]
40
+ return w
41
+ elif kernel == "cauchy":
42
+ return 1.0 / (1.0 + (r / c) ** 2)
43
+ elif kernel == "tls":
44
+ w = np.ones_like(r, dtype=np.float64)
45
+ w[r > c] = 0.0
46
+ return w
47
+ else:
48
+ raise ValueError(f"Unknown kernel: {kernel}")
49
+
50
+
51
+ def _gnc_tls_weights(r, c, mu):
52
+ """GNC surrogate weights for TLS kernel."""
53
+ w = np.ones_like(r, dtype=np.float64)
54
+ r_thresh = c * np.sqrt(mu / (1.0 + mu))
55
+
56
+ outlier = r > r_thresh
57
+ if np.any(outlier):
58
+ r_out = r[outlier]
59
+ w[outlier] = np.clip((c ** 2 * mu) / (r_out ** 2 * (1.0 + mu)), 0.0, 1.0)
60
+
61
+ return w
62
+
63
+
64
+ def gnc_mu(iteration, total_iterations):
65
+ """Compute GNC mu for a given iteration.
66
+
67
+ mu transitions linearly from 1.0 (iteration 1) to 0.0 (last iteration).
68
+ """
69
+ if total_iterations <= 1:
70
+ return 0.0
71
+ return max(0.0, 1.0 - iteration / (total_iterations - 1))