hyperdd 0.1__0-py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,228 @@
1
+ """
2
+ Straight-ray 1-D velocity model for travel times and partial derivatives.
3
+
4
+ Exact reimplementation of the straight-ray path logic in partials_1dsr.f
5
+ from hypoDD. The straight-ray approximation computes travel time as the
6
+ Euclidean distance divided by the surface-layer velocity, accounting for
7
+ station elevation.
8
+
9
+ All arrays use 0-based Python indexing.
10
+ """
11
+
12
+ import math
13
+
14
+ import numpy as np
15
+ from numpy.typing import NDArray
16
+
17
+
18
+ def straighray_tt(
19
+ dist: float,
20
+ src_dep: float,
21
+ sta_elv: float,
22
+ vp: float,
23
+ ) -> float:
24
+ """Straight-ray P-wave travel time.
25
+
26
+ Parameters
27
+ ----------
28
+ dist : float
29
+ Epicentral distance (km).
30
+ src_dep : float
31
+ Source depth (km, positive downward).
32
+ sta_elv : float
33
+ Station elevation (km, positive upward).
34
+ vp : float
35
+ P-wave velocity at the surface layer (km/s).
36
+
37
+ Returns
38
+ -------
39
+ ttp : float
40
+ P-wave travel time (s).
41
+ """
42
+ return math.sqrt(dist**2 + (src_dep + sta_elv) ** 2) / vp
43
+
44
+
45
+ def straightray_takeoff(
46
+ dist: float,
47
+ src_dep: float,
48
+ sta_elv: float,
49
+ ) -> float:
50
+ """Take-off angle for a straight ray (degrees).
51
+
52
+ Parameters
53
+ ----------
54
+ dist : float
55
+ Epicentral distance (km).
56
+ src_dep : float
57
+ Source depth (km).
58
+ sta_elv : float
59
+ Station elevation (km).
60
+
61
+ Returns
62
+ -------
63
+ ain : float
64
+ Take-off angle measured from downward vertical (degrees).
65
+ 180 - atan(dist/dz)*57.2958 when station is above source;
66
+ atan(dist/dz)*57.2958 when station is below source.
67
+ """
68
+ dz = abs(src_dep + sta_elv)
69
+ if dz == 0.0:
70
+ return 90.0
71
+ if src_dep >= -sta_elv:
72
+ # Station above source (normal case)
73
+ ain = 180.0 - math.atan(dist / dz) * 57.2958
74
+ else:
75
+ # Station below source
76
+ ain = math.atan(dist / dz) * 57.2958
77
+ return ain
78
+
79
+
80
+ def straightray_partials(
81
+ dist: float,
82
+ az: float,
83
+ ain: float,
84
+ vel: float,
85
+ ) -> tuple[float, float, float]:
86
+ """Partial derivatives of travel time w.r.t. source location.
87
+
88
+ Parameters
89
+ ----------
90
+ dist : float
91
+ Epicentral distance (km).
92
+ az : float
93
+ Azimuth from source to station (degrees, clockwise from north).
94
+ ain : float
95
+ Take-off angle (degrees, from downward vertical).
96
+ vel : float
97
+ Wave speed (km/s) -- Vp or Vs.
98
+
99
+ Returns
100
+ -------
101
+ dx : float
102
+ Partial dt/dX (east-west, s/km).
103
+ dy : float
104
+ Partial dt/dY (north-south, s/km).
105
+ dz : float
106
+ Partial dt/dZ (vertical, s/km).
107
+ """
108
+ pi = 3.141593
109
+ ain_rad = ain * pi / 180.0
110
+ az_rad_x = (az - 90.0) * pi / 180.0 # for east-west component
111
+ az_rad_y = az * pi / 180.0 # for north-south component
112
+
113
+ dx = math.sin(ain_rad) * math.cos(az_rad_x) / vel
114
+ dy = math.sin(ain_rad) * math.cos(az_rad_y) / vel
115
+ dz = math.cos(ain_rad) / vel
116
+
117
+ return dx, dy, dz
118
+
119
+
120
+ def partials_1dsr(
121
+ nsrc: int,
122
+ src_dep: NDArray[np.float64],
123
+ nsta: int,
124
+ sta_elv: NDArray[np.float64],
125
+ dists: NDArray[np.float64],
126
+ azs: NDArray[np.float64],
127
+ mod_nl: int,
128
+ mod_ratio: float,
129
+ mod_v: NDArray[np.float64],
130
+ mod_top: NDArray[np.float64],
131
+ ) -> tuple[
132
+ NDArray[np.float64],
133
+ NDArray[np.float64],
134
+ NDArray[np.float64],
135
+ NDArray[np.float64],
136
+ NDArray[np.float64],
137
+ NDArray[np.float64],
138
+ NDArray[np.float64],
139
+ NDArray[np.float64],
140
+ ]:
141
+ """Compute travel times and partial derivatives for straight-ray paths.
142
+
143
+ Reimplements the core loop of ``partials_1dsr.f``. The caller is
144
+ responsible for computing epicentral distances and azimuths (via
145
+ ``delaz2`` or equivalent) and passing them as *dists* and *azs*.
146
+
147
+ Parameters
148
+ ----------
149
+ nsrc : int
150
+ Number of sources.
151
+ src_dep : array, shape (nsrc,)
152
+ Source depths (km, positive downward).
153
+ nsta : int
154
+ Number of stations.
155
+ sta_elv : array, shape (nsta,)
156
+ Station elevations (km, positive upward).
157
+ dists : array, shape (nsta, nsrc)
158
+ Epicentral distances (km) -- ``dists[i, j]`` is the distance from
159
+ source *j* to station *i*.
160
+ azs : array, shape (nsta, nsrc)
161
+ Azimuths (degrees) from source *j* to station *i*.
162
+ mod_nl : int
163
+ Number of velocity-model layers.
164
+ mod_ratio : float
165
+ Vp/Vs ratio.
166
+ mod_v : array, shape (mod_nl,)
167
+ P-wave velocity in each layer (km/s).
168
+ mod_top : array, shape (mod_nl,)
169
+ Depth to top of each layer (km).
170
+
171
+ Returns
172
+ -------
173
+ tmp_ttp : array, shape (nsta, nsrc)
174
+ P-wave travel times (s).
175
+ tmp_tts : array, shape (nsta, nsrc)
176
+ S-wave travel times (s).
177
+ tmp_xp, tmp_yp, tmp_zp : arrays, shape (nsta, nsrc)
178
+ P-wave partial derivatives (s/km).
179
+ tmp_xs, tmp_ys, tmp_zs : arrays, shape (nsta, nsrc)
180
+ S-wave partial derivatives (s/km).
181
+ """
182
+ # Nudge sources off layer boundaries (Fortran does the same)
183
+ src_dep_adj = src_dep.copy()
184
+ for j in range(nsrc):
185
+ for k in range(mod_nl):
186
+ if abs(src_dep_adj[j] - mod_top[k]) < 0.0001:
187
+ src_dep_adj[j] -= 0.001
188
+
189
+ vp = mod_v[0] # straight-ray uses only surface-layer velocity
190
+ vs = vp / mod_ratio
191
+
192
+ tmp_ttp = np.empty((nsta, nsrc), dtype=np.float64)
193
+ tmp_tts = np.empty((nsta, nsrc), dtype=np.float64)
194
+ tmp_xp = np.empty((nsta, nsrc), dtype=np.float64)
195
+ tmp_yp = np.empty((nsta, nsrc), dtype=np.float64)
196
+ tmp_zp = np.empty((nsta, nsrc), dtype=np.float64)
197
+ tmp_xs = np.empty((nsta, nsrc), dtype=np.float64)
198
+ tmp_ys = np.empty((nsta, nsrc), dtype=np.float64)
199
+ tmp_zs = np.empty((nsta, nsrc), dtype=np.float64)
200
+
201
+ for i in range(nsta):
202
+ for j in range(nsrc):
203
+ dist = dists[i, j]
204
+ az = azs[i, j]
205
+ dep = src_dep_adj[j]
206
+ elv = sta_elv[i]
207
+
208
+ # Travel times (straight ray)
209
+ tmp_ttp[i, j] = math.sqrt(dist**2 + (dep + elv) ** 2) / vp
210
+ tmp_tts[i, j] = math.sqrt(dist**2 + (dep + elv) ** 2) / vs
211
+
212
+ # Take-off angle
213
+ ain = straightray_takeoff(dist, dep, elv)
214
+
215
+ # Partial derivatives
216
+ tmp_xp[i, j], tmp_yp[i, j], tmp_zp[i, j] = straightray_partials(
217
+ dist, az, ain, vp
218
+ )
219
+ tmp_xs[i, j], tmp_ys[i, j], tmp_zs[i, j] = straightray_partials(
220
+ dist, az, ain, vs
221
+ )
222
+
223
+ # Flip vertical partial when station is below source
224
+ if dep < -elv:
225
+ tmp_zp[i, j] = -tmp_zp[i, j]
226
+ tmp_zs[i, j] = -tmp_zs[i, j]
227
+
228
+ return tmp_ttp, tmp_tts, tmp_xp, tmp_yp, tmp_zp, tmp_xs, tmp_ys, tmp_zs
File without changes
@@ -0,0 +1,424 @@
1
+ """LSQR iterative least-squares solver for hypoDD.
2
+
3
+ Reimplementation of lsfit_lsqr.f from hypoDD using scipy.sparse.linalg.lsqr.
4
+ """
5
+
6
+ import numpy as np
7
+ from scipy.sparse import csr_matrix
8
+ from scipy.sparse.linalg import lsqr as scipy_lsqr
9
+
10
+ from .stats import resstat
11
+
12
+
13
+ def solve_lsqr(ndt, nev, nsrc, damp, idata, ev_cusp, ev_fix, src_cusp,
14
+ dt_res, dt_wt, dt_ista, dt_ic1, dt_ic2, dt_idx,
15
+ tmp_xp, tmp_yp, tmp_zp, tmp_xs, tmp_ys, tmp_zs, iter_num=1,
16
+ use_float32=True):
17
+ """LSQR iterative least-squares solver for hypoDD.
18
+
19
+ Parameters
20
+ ----------
21
+ ndt : int
22
+ Number of differential time observations.
23
+ nev : int
24
+ Number of events.
25
+ nsrc : int
26
+ Number of sources (if 1, use single source index).
27
+ damp : float
28
+ Damping parameter passed to LSQR.
29
+ idata : int
30
+ Data type flag (1=CC, 2=CT, 3=both).
31
+ ev_cusp : np.ndarray
32
+ Event IDs, shape (nev,).
33
+ ev_fix : np.ndarray
34
+ Fix flags per event, shape (nev,).
35
+ src_cusp : np.ndarray
36
+ Source event IDs, shape (nev,).
37
+ dt_res : np.ndarray
38
+ Residuals in seconds, shape (>=ndt,). MODIFIED in-place.
39
+ dt_wt : np.ndarray
40
+ Weights, shape (>=ndt,).
41
+ dt_ista : np.ndarray
42
+ Station indices (0-indexed), shape (>=ndt,).
43
+ dt_ic1 : np.ndarray
44
+ Event-1 indices (0-indexed into nev), shape (>=ndt,).
45
+ dt_ic2 : np.ndarray
46
+ Event-2 indices (0-indexed into nev), shape (>=ndt,).
47
+ dt_idx : np.ndarray
48
+ Data type index (1=CC-P, 2=CC-S, 3=CT-P, 4=CT-S), shape (>=ndt,).
49
+ tmp_xp, tmp_yp, tmp_zp : np.ndarray
50
+ P-wave partial derivatives, shape (nsta, nsrc).
51
+ tmp_xs, tmp_ys, tmp_zs : np.ndarray
52
+ S-wave partial derivatives, shape (nsta, nsrc).
53
+ iter_num : int, optional
54
+ Iteration number (for statistics bookkeeping).
55
+
56
+ Returns
57
+ -------
58
+ result : dict
59
+ Dictionary with keys:
60
+ src_dx, src_dy, src_dz, src_dt : np.ndarray (nev,)
61
+ Location/time adjustments in m and ms.
62
+ src_ex, src_ey, src_ez, src_et : np.ndarray (nev,)
63
+ 95% confidence errors in m and ms.
64
+ rms_cc, rms_ct, rms_cc0, rms_ct0 : float
65
+ Residual RMS statistics.
66
+ src_cusp : np.ndarray (nev,)
67
+ Event IDs (copied from ev_cusp).
68
+ acond : float
69
+ Condition number estimate from LSQR.
70
+ """
71
+ ncol = 4 * nev
72
+
73
+ # --- Build sparse G matrix as COO triplets ---
74
+ # Each observation contributes 8 non-zero entries (4 for event1, 4 for event2).
75
+ # Then constraint rows are added.
76
+
77
+ # Pre-count constraint entries for ev_fix
78
+ n_fix_entries = 0
79
+ for i in range(nev):
80
+ fix = ev_fix[i]
81
+ if fix == 1 or fix == 5:
82
+ n_fix_entries += 1
83
+ elif fix == 2 or fix == 6:
84
+ n_fix_entries += 2
85
+ elif fix == 3:
86
+ n_fix_entries += 3
87
+ elif fix == 4:
88
+ n_fix_entries += 4
89
+
90
+ max_nnz = 8 * ndt + n_fix_entries
91
+ rows = np.empty(max_nnz, dtype=np.int32)
92
+ cols = np.empty(max_nnz, dtype=np.int32)
93
+ vals = np.empty(max_nnz, dtype=np.float64)
94
+
95
+ # Weight arrays
96
+ wt = dt_wt[:ndt].copy()
97
+
98
+ # Data vector: start with ndt data rows, then constraint rows will be appended
99
+ nndt = ndt # current number of rows
100
+ max_rows = ndt + n_fix_entries
101
+ d = np.zeros(max_rows, dtype=np.float64)
102
+ d[:ndt] = dt_res[:ndt] * 1000.0 * wt # weighted residuals in ms
103
+
104
+ # Fill in the 8 entries per observation
105
+ idx = np.arange(ndt)
106
+ ic1 = dt_ic1[:ndt]
107
+ ic2 = dt_ic2[:ndt]
108
+ ista = dt_ista[:ndt]
109
+
110
+ if nsrc == 1:
111
+ k1_arr = np.zeros(ndt, dtype=np.int32)
112
+ k2_arr = np.zeros(ndt, dtype=np.int32)
113
+ else:
114
+ k1_arr = ic1.copy()
115
+ k2_arr = ic2.copy()
116
+
117
+ s_mask = (dt_idx[:ndt] == 2) | (dt_idx[:ndt] == 4)
118
+ p_mask = ~s_mask
119
+
120
+ # Event 1: x partial (column ic1*4+0)
121
+ # For S-phase use xs, for P-phase use xp
122
+ xp1 = np.empty(ndt, dtype=np.float64)
123
+ yp1 = np.empty(ndt, dtype=np.float64)
124
+ zp1 = np.empty(ndt, dtype=np.float64)
125
+ xp2 = np.empty(ndt, dtype=np.float64)
126
+ yp2 = np.empty(ndt, dtype=np.float64)
127
+ zp2 = np.empty(ndt, dtype=np.float64)
128
+
129
+ for i in range(ndt):
130
+ sta_i = ista[i]
131
+ k1_i = k1_arr[i]
132
+ k2_i = k2_arr[i]
133
+ if s_mask[i]:
134
+ xp1[i] = tmp_xs[sta_i, k1_i]
135
+ yp1[i] = tmp_ys[sta_i, k1_i]
136
+ zp1[i] = tmp_zs[sta_i, k1_i]
137
+ xp2[i] = tmp_xs[sta_i, k2_i]
138
+ yp2[i] = tmp_ys[sta_i, k2_i]
139
+ zp2[i] = tmp_zs[sta_i, k2_i]
140
+ else:
141
+ xp1[i] = tmp_xp[sta_i, k1_i]
142
+ yp1[i] = tmp_yp[sta_i, k1_i]
143
+ zp1[i] = tmp_zp[sta_i, k1_i]
144
+ xp2[i] = tmp_xp[sta_i, k2_i]
145
+ yp2[i] = tmp_yp[sta_i, k2_i]
146
+ zp2[i] = tmp_zp[sta_i, k2_i]
147
+
148
+ # 8 blocks of ndt entries each
149
+ # Block 0: row=i, col=ic1[i]*4+0, val=xp1[i]*wt[i]
150
+ # Block 1: row=i, col=ic1[i]*4+1, val=yp1[i]*wt[i]
151
+ # Block 2: row=i, col=ic1[i]*4+2, val=zp1[i]*wt[i]
152
+ # Block 3: row=i, col=ic1[i]*4+3, val=wt[i]
153
+ # Block 4: row=i, col=ic2[i]*4+0, val=-xp2[i]*wt[i]
154
+ # Block 5: row=i, col=ic2[i]*4+1, val=-yp2[i]*wt[i]
155
+ # Block 6: row=i, col=ic2[i]*4+2, val=-zp2[i]*wt[i]
156
+ # Block 7: row=i, col=ic2[i]*4+3, val=-wt[i]
157
+ ptr = 0
158
+
159
+ rows[ptr:ptr + ndt] = idx
160
+ cols[ptr:ptr + ndt] = ic1 * 4 + 0
161
+ vals[ptr:ptr + ndt] = xp1 * wt
162
+ ptr += ndt
163
+
164
+ rows[ptr:ptr + ndt] = idx
165
+ cols[ptr:ptr + ndt] = ic1 * 4 + 1
166
+ vals[ptr:ptr + ndt] = yp1 * wt
167
+ ptr += ndt
168
+
169
+ rows[ptr:ptr + ndt] = idx
170
+ cols[ptr:ptr + ndt] = ic1 * 4 + 2
171
+ vals[ptr:ptr + ndt] = zp1 * wt
172
+ ptr += ndt
173
+
174
+ rows[ptr:ptr + ndt] = idx
175
+ cols[ptr:ptr + ndt] = ic1 * 4 + 3
176
+ vals[ptr:ptr + ndt] = wt
177
+ ptr += ndt
178
+
179
+ rows[ptr:ptr + ndt] = idx
180
+ cols[ptr:ptr + ndt] = ic2 * 4 + 0
181
+ vals[ptr:ptr + ndt] = -xp2 * wt
182
+ ptr += ndt
183
+
184
+ rows[ptr:ptr + ndt] = idx
185
+ cols[ptr:ptr + ndt] = ic2 * 4 + 1
186
+ vals[ptr:ptr + ndt] = -yp2 * wt
187
+ ptr += ndt
188
+
189
+ rows[ptr:ptr + ndt] = idx
190
+ cols[ptr:ptr + ndt] = ic2 * 4 + 2
191
+ vals[ptr:ptr + ndt] = -zp2 * wt
192
+ ptr += ndt
193
+
194
+ rows[ptr:ptr + ndt] = idx
195
+ cols[ptr:ptr + ndt] = ic2 * 4 + 3
196
+ vals[ptr:ptr + ndt] = -wt
197
+ ptr += ndt
198
+
199
+ # --- Add ev_fix constraint rows ---
200
+ # NOTE: Mean-shift constraints are commented out in Fortran lsfit_lsqr.f.
201
+ # The Fortran LSQR operates in single-precision which provides implicit
202
+ # regularization. For borehole geometries (Example 4), this can cause
203
+ # the Python (double-precision) solver to produce larger depth perturbations.
204
+ # Constraint weights in Fortran:
205
+ # fix=1: z -> 100.0
206
+ # fix=2: z,t -> 100.0
207
+ # fix=3: x,y,z -> 10.0
208
+ # fix=4: x,y,z,t -> 100.0
209
+ # fix=5: t -> 1000.0
210
+ # fix=6: x,y -> 100.0
211
+ _fix_weights = {
212
+ 1: {2: 100.0},
213
+ 2: {2: 100.0, 3: 100.0},
214
+ 3: {0: 10.0, 1: 10.0, 2: 10.0},
215
+ 4: {0: 100.0, 1: 100.0, 2: 100.0, 3: 100.0},
216
+ 5: {3: 1000.0},
217
+ 6: {0: 100.0, 1: 100.0},
218
+ }
219
+
220
+ k = 0
221
+ for i in range(nev):
222
+ fix = ev_fix[i]
223
+ if fix == 0 or fix not in _fix_weights:
224
+ continue
225
+ for off, weight in _fix_weights[fix].items():
226
+ row_idx = nndt + k
227
+ d[row_idx] = 0.0
228
+ rows[ptr] = row_idx
229
+ cols[ptr] = i * 4 + off
230
+ vals[ptr] = weight
231
+ ptr += 1
232
+ k += 1
233
+
234
+ nndt += k
235
+ total_nnz = ptr
236
+
237
+ # Build sparse matrix
238
+ # Fortran LSQR uses single-precision (real) for rw/d arrays.
239
+ # Using float32 matches the Fortran arithmetic more closely.
240
+ _dtype = np.float32 if use_float32 else np.float64
241
+ G = csr_matrix(
242
+ (vals[:total_nnz].astype(_dtype), (rows[:total_nnz], cols[:total_nnz])),
243
+ shape=(nndt, ncol),
244
+ dtype=_dtype,
245
+ )
246
+ d_vec = d[:nndt].astype(_dtype)
247
+
248
+ # --- Column scaling ---
249
+ # Fortran: norm(j) = sqrt(sum(G[:,j]^2) / ndt)
250
+ # NOTE: Fortran uses ndt (not nndt) as denominator even when constraint rows
251
+ # are present (nndt is never updated after ev_fix rows in lsfit_lsqr.f).
252
+ col_sq_sums = np.array(G.power(2).sum(axis=0)).ravel()
253
+ norm = np.sqrt(col_sq_sums / ndt)
254
+ norm[norm == 0] = 1.0
255
+
256
+ # Scale columns: G[:,j] /= norm[j]
257
+ # Efficient: multiply by diagonal matrix on the right
258
+ from scipy.sparse import diags
259
+ norm_inv_diag = diags(1.0 / norm)
260
+ G_scaled = G @ norm_inv_diag
261
+
262
+ # --- Call scipy LSQR ---
263
+ m = nndt
264
+ n = ncol
265
+ atol = 1e-6
266
+ btol = 1e-6
267
+ conlim = 1e5
268
+ iter_lim = 100 * n
269
+
270
+ result_lsqr = scipy_lsqr(
271
+ G_scaled, d_vec,
272
+ damp=_dtype(damp),
273
+ atol=atol,
274
+ btol=btol,
275
+ conlim=conlim,
276
+ iter_lim=iter_lim,
277
+ calc_var=True,
278
+ )
279
+
280
+ x = result_lsqr[0] # solution vector
281
+ istop = result_lsqr[1] # reason for stopping
282
+ itn = result_lsqr[2]
283
+ r1norm = result_lsqr[3]
284
+ r2norm = result_lsqr[4]
285
+ anorm = result_lsqr[5]
286
+ acond = result_lsqr[6]
287
+ arnorm = result_lsqr[7]
288
+ xnorm = result_lsqr[8]
289
+ var = result_lsqr[9] # variance estimates (when calc_var=True)
290
+
291
+ # Diagnostic output for debugging
292
+ import logging
293
+ _log = logging.getLogger("hypoDD")
294
+ _log.debug(" LSQR: istop=%d itn=%d anorm=%.1f acond=%.1f arnorm=%.1f xnorm=%.1f",
295
+ istop, itn, anorm, acond, arnorm, xnorm)
296
+ _log.debug(" LSQR: G shape=%s dtype=%s, d norm=%.1f, damp=%.1f",
297
+ G_scaled.shape, G_scaled.dtype, float(np.linalg.norm(d_vec)), damp)
298
+ _log.debug(" LSQR: x[:8] (scaled) = %s", x[:min(8, len(x))])
299
+
300
+ # --- Rescale solution and standard errors ---
301
+ x /= norm
302
+ se = var / norm ** 2 # var from scipy lsqr is se(i) in Fortran (variance-like)
303
+
304
+ # --- Update residuals ---
305
+ # Fortran approach:
306
+ # Unweight and rescale G, then compute d = -dt_res*1000; aprod(1,m,n,x,d,...); dt_res = -d/1000
307
+ # This is equivalent to: dt_res_new = dt_res - (G_unweighted @ x) / 1000
308
+ # Build the unweighted, unscaled G for the data rows only to compute residuals.
309
+ # We need the original (unweighted, unscaled) G for residual computation.
310
+
311
+ # Reconstruct unweighted G for data rows:
312
+ # The weighted-scaled G entries are: val_ws = val_orig * wt * (1/norm[col])
313
+ # So val_orig = val_ws * norm[col] / wt
314
+ # But it's simpler to just rebuild the unweighted G for data rows.
315
+
316
+ # Build unweighted G for data rows only
317
+ nnz_data = 8 * ndt
318
+ rows_uw = np.empty(nnz_data, dtype=np.int32)
319
+ cols_uw = np.empty(nnz_data, dtype=np.int32)
320
+ vals_uw = np.empty(nnz_data, dtype=np.float64)
321
+ p = 0
322
+
323
+ rows_uw[p:p + ndt] = idx
324
+ cols_uw[p:p + ndt] = ic1 * 4 + 0
325
+ vals_uw[p:p + ndt] = xp1
326
+ p += ndt
327
+
328
+ rows_uw[p:p + ndt] = idx
329
+ cols_uw[p:p + ndt] = ic1 * 4 + 1
330
+ vals_uw[p:p + ndt] = yp1
331
+ p += ndt
332
+
333
+ rows_uw[p:p + ndt] = idx
334
+ cols_uw[p:p + ndt] = ic1 * 4 + 2
335
+ vals_uw[p:p + ndt] = zp1
336
+ p += ndt
337
+
338
+ rows_uw[p:p + ndt] = idx
339
+ cols_uw[p:p + ndt] = ic1 * 4 + 3
340
+ vals_uw[p:p + ndt] = 1.0
341
+ p += ndt
342
+
343
+ rows_uw[p:p + ndt] = idx
344
+ cols_uw[p:p + ndt] = ic2 * 4 + 0
345
+ vals_uw[p:p + ndt] = -xp2
346
+ p += ndt
347
+
348
+ rows_uw[p:p + ndt] = idx
349
+ cols_uw[p:p + ndt] = ic2 * 4 + 1
350
+ vals_uw[p:p + ndt] = -yp2
351
+ p += ndt
352
+
353
+ rows_uw[p:p + ndt] = idx
354
+ cols_uw[p:p + ndt] = ic2 * 4 + 2
355
+ vals_uw[p:p + ndt] = -zp2
356
+ p += ndt
357
+
358
+ rows_uw[p:p + ndt] = idx
359
+ cols_uw[p:p + ndt] = ic2 * 4 + 3
360
+ vals_uw[p:p + ndt] = -1.0
361
+ p += ndt
362
+
363
+ G_uw = csr_matrix(
364
+ (vals_uw, (rows_uw, cols_uw)),
365
+ shape=(ndt, ncol),
366
+ dtype=np.float64,
367
+ )
368
+
369
+ # Residual update: dt_res = dt_res - G_uw @ x / 1000
370
+ dd = G_uw @ x
371
+ dt_res[:ndt] -= dd / 1000.0
372
+
373
+ # --- Residual statistics ---
374
+ rms_cc, rms_ct, rms_cc0, rms_ct0, resvar = resstat(
375
+ ndt, nev, dt_res, dt_wt, dt_idx, idata
376
+ )
377
+
378
+ # --- Errors at 95% confidence level ---
379
+ # Fortran LSQR uses factor = 2.7955 (not 1.96 like SVD)
380
+ # Fortran: src_ex(i) = sqrt(se(4*i-3)) * sqrt(resvar1) * factor
381
+ # se from Fortran LSQR is like variance, so sqrt(se) gives std error
382
+ factor = 2.7955
383
+
384
+ # --- Store results ---
385
+ src_dx = np.zeros(nev, dtype=np.float64)
386
+ src_dy = np.zeros(nev, dtype=np.float64)
387
+ src_dz = np.zeros(nev, dtype=np.float64)
388
+ src_dt = np.zeros(nev, dtype=np.float64)
389
+ src_ex = np.zeros(nev, dtype=np.float64)
390
+ src_ey = np.zeros(nev, dtype=np.float64)
391
+ src_ez = np.zeros(nev, dtype=np.float64)
392
+ src_et = np.zeros(nev, dtype=np.float64)
393
+
394
+ sqrt_resvar = np.sqrt(abs(resvar))
395
+ for i in range(nev):
396
+ # Negation of solution (same as Fortran)
397
+ src_dx[i] = -x[4 * i + 0]
398
+ src_dy[i] = -x[4 * i + 1]
399
+ src_dz[i] = -x[4 * i + 2]
400
+ src_dt[i] = -x[4 * i + 3]
401
+
402
+ # Errors: sqrt(se) * sqrt(resvar) * factor
403
+ # se values are variance-like from LSQR
404
+ src_ex[i] = np.sqrt(abs(se[4 * i + 0])) * sqrt_resvar * factor
405
+ src_ey[i] = np.sqrt(abs(se[4 * i + 1])) * sqrt_resvar * factor
406
+ src_ez[i] = np.sqrt(abs(se[4 * i + 2])) * sqrt_resvar * factor
407
+ src_et[i] = np.sqrt(abs(se[4 * i + 3])) * sqrt_resvar * factor
408
+
409
+ return {
410
+ 'src_dx': src_dx,
411
+ 'src_dy': src_dy,
412
+ 'src_dz': src_dz,
413
+ 'src_dt': src_dt,
414
+ 'src_ex': src_ex,
415
+ 'src_ey': src_ey,
416
+ 'src_ez': src_ez,
417
+ 'src_et': src_et,
418
+ 'src_cusp': ev_cusp[:nev].copy(),
419
+ 'rms_cc': rms_cc,
420
+ 'rms_ct': rms_ct,
421
+ 'rms_cc0': rms_cc0,
422
+ 'rms_ct0': rms_ct0,
423
+ 'acond': acond,
424
+ }