API Reference#
LayTracer — fast two-point ray tracing in 1-D layered media.
Public API#
Model#
|
Layers traversed by a ray between source and receiver depths. |
|
Pre-extracted numpy arrays from a velocity DataFrame. |
|
Extract the layer stack between source and receiver depths. |
Solver#
|
Solve the two-point ray tracing problem for an arbitrary path. |
|
Result of a single two-point ray trace. |
|
Numerical certificate for one two-point solve. |
Multi-ray#
|
Trace rays for all source-receiver pairs. |
|
Container for multi-ray tracing results. |
|
One ordered reflection or transmission in a prescribed itinerary. |
|
An ordered, fixed-topology phase itinerary. |
|
Sparse derivatives for one fixed-topology ray. |
Approximation#
|
Predict first-order output changes for one fixed-topology ray. |
|
Select deterministic farthest-point anchors covering a point cloud. |
|
First-order changes predicted from one ray sensitivity record. |
|
Deterministic point-cloud anchor selection and assignments. |
|
Fitted topology-safe endpoint-Taylor traveltime approximator. |
|
Predicted traveltimes and anchor-assignment diagnostics. |
Amplitude#
|
Normal-incidence displacement transmission coefficient. |
|
Compute SH-SH reflection and transmission coefficients. |
|
Compute all eight P-SV reflection/transmission coefficients. |
|
Return the critical angle for a faster outgoing wave. |
|
Find critical angles for one or more outgoing wave speeds. |
|
Find Brewster-like angles (deep minima) in R/T coefficient curves. |
|
Apply Červený (2001) normalization to a displacement R/T coefficient. |
Visualisation#
|
Standalone visualisation helpers for LayTracer. |
Model#
- class laytracer.LayerStack(h, vp, vs, rho=None, qp=None, qs=None)[source]#
Layers traversed by a ray between source and receiver depths.
- Parameters:
- hnumpy.ndarray
Layer thicknesses (m), shape
(N,). Ordered from the shallowest traversed depth to the deepest.- vpnumpy.ndarray
P-wave velocities (m/s), shape
(N,).- vsnumpy.ndarray
S-wave velocities (m/s), shape
(N,).- rhonumpy.ndarray or None
Densities (kg/m³), shape
(N,), or None.- qpnumpy.ndarray or None
P-wave quality factors, shape
(N,), or None.- qsnumpy.ndarray or None
S-wave quality factors, shape
(N,), or None.
- property n_layers#
Number of layers in the stack.
- class laytracer.ModelArrays(depths, vp, vs, rho=None, qp=None, qs=None)[source]#
Pre-extracted numpy arrays from a velocity DataFrame.
Use
from_dataframeto construct once and pass tobuild_layer_stackto avoid repeated DataFrame column access when tracing many rays.
- laytracer.build_layer_stack(vel_model, z_src, z_rcv)[source]#
Extract the layer stack between source and receiver depths.
The returned
LayerStackcontains the layers traversed by a ray connecting z_src and z_rcv, with partial thicknesses at the source and receiver layers. Layers are always ordered from the shallowest point to the deepest, regardless of which endpoint is the source.- Parameters:
- vel_modelpandas.DataFrame or ModelArrays
Velocity model. A DataFrame must have columns
Depth,Vp,Vs(optional:Rho,Qp,Qs). AModelArraysinstance avoids repeated column extraction when tracing many rays.- z_srcfloat
Source depth (positive downward, m).
- z_rcvfloat
Receiver depth (positive downward, m).
- Returns:
- LayerStack
Solver#
- laytracer.solve(h, v, segments, interactions, epicentral_dist, z_src, z_rcv, requested=None, return_ray_path=True, need_ray_parameter=True, need_tstar=False, need_spreading=False, need_trans_product=False, transcoef_method='standard', tol=0.0001, max_iter=10, need_complex_coefficient_product=False, need_diagnostics=False)[source]#
Solve the two-point ray tracing problem for an arbitrary path.
- Parameters:
- hnumpy.ndarray
Concatenated layer thicknesses for the entire path (m).
- vnumpy.ndarray
Concatenated phase velocities (Vp or Vs) for the entire path (m/s).
- segmentslist of dict
Metadata for each logical monotonic segment (used for reconstruction). Dict keys: ‘h’, ‘v’, ‘phase’, ‘start_z’, ‘end_z’.
- interactionslist of dict
Metadata for interactions (reflections/refractions) impacting amplitude. Dict keys: ‘type’, ‘depth’, ‘in_phase’, ‘out_phase’, ‘seg_idx’.
- interactions are assumed to occur at the END of the defined segment.
- class laytracer.RayResult(travel_time, ray_path, ray_parameter, tstar=None, spreading=None, trans_product=None, complex_coefficient_product=None, diagnostics=None)[source]#
Result of a single two-point ray trace.
- Attributes:
- travel_timefloat
Total travel time (s).
- ray_pathnumpy.ndarray or None
Ray coordinates in the 2-D ray plane, shape
(M, 2)with columns[x, z]. None if not requested.- ray_parameterfloat or None
Horizontal slowness p (s/m).
- tstarfloat or None
Attenuation operator \(t^*\) (s), if requested.
- spreadingfloat or None
Relative geometrical spreading factor \(\mathcal{L}\), if requested.
- trans_productfloat or None
Product of transmission-coefficient magnitudes along the ray, if requested.
- complex_coefficient_productcomplex or None
Signed/complex cumulative interface coefficient, if requested.
- diagnosticsSolveDiagnostics or None
Numerical certificate, if requested.
- class laytracer.SolveDiagnostics(converged, method, iterations, initial_q, final_q, initial_ray_parameter, ray_parameter, signed_offset_residual, absolute_offset_residual, conditioning, criticality_margin, fallback_iterations=0, failure_reason=None)[source]#
Numerical certificate for one two-point solve.
- Attributes:
- convergedbool
Whether the independently recomputed offset meets
tol.- methodstr
"q_newton"for the quadratic iteration or"q_brentq"for the safeguarded bracketed fallback.- iterationsint
Number of quadratic Newton updates attempted.
- fallback_iterationsint
Number of bracketed iterations, or zero when no fallback was used.
- initial_q, final_qfloat
Initial and accepted dimensionless ray parameters.
- initial_ray_parameter, ray_parameterfloat
Initial and accepted physical horizontal slownesses (s/m).
- signed_offset_residual, absolute_offset_residualfloat
Recomputed offset minus requested offset, and its magnitude (m).
- conditioningfloat
Dimensionless logarithmic slope
abs(q / X * dX/dq). The zero-offset limit is reported as one.- criticality_marginfloat
1 - p * vmax; values approaching zero indicate grazing propagation in the fastest traversed leg.- failure_reasonstr or None
Populated only when a numerical certificate cannot be produced.
- laytracer.offset(q, h, lmd)[source]#
Total horizontal range \(X(q)\).
\[X(q) = \sum_{k=1}^{N} \frac{q\,\lambda_k\,h_k} {\sqrt{1 + (1 - \lambda_k^2)\,q^2}}\]- Parameters:
- qfloat
Dimensionless ray parameter.
- hnumpy.ndarray
Layer thicknesses (m), shape
(N,).- lmdnumpy.ndarray
Velocity ratios \(\lambda_k = v_k / v_{\max}\), shape
(N,).
- Returns:
- float
- laytracer.offset_dq(q, h, lmd)[source]#
First derivative \(\mathrm{d}X/\mathrm{d}q\).
\[\frac{\mathrm{d}X}{\mathrm{d}q} = \sum_{k=1}^{N} \frac{\lambda_k\,h_k} {\bigl[1 + (1 - \lambda_k^2)\,q^2\bigr]^{3/2}}\]
- laytracer.offset_dq2(q, h, lmd)[source]#
Second derivative \(\mathrm{d}^2X/\mathrm{d}q^2\).
\[\frac{\mathrm{d}^2X}{\mathrm{d}q^2} = -3\,q\,\sum_{k=1}^{N} \frac{(1 - \lambda_k^2)\,\lambda_k\,h_k} {\bigl[1 + (1 - \lambda_k^2)\,q^2\bigr]^{5/2}}\]
- laytracer.q_from_p(p, vmax)[source]#
Convert horizontal slowness p to dimensionless parameter q.
\[q = \frac{p\,v_{\max}}{\sqrt{1 - p^2\,v_{\max}^2}}\]
- laytracer.p_from_q(q, vmax)[source]#
Convert dimensionless parameter q to horizontal slowness p.
\[p = \frac{q}{v_{\max}\,\sqrt{1 + q^2}}\]
- laytracer.initial_q(X_target, h, lmd)[source]#
Asymptotic initial estimate \(q_0\) for the Newton iteration.
Two linear asymptotes of \(X(q)\):
Near-field (\(q\to 0\)): \(X \approx m_0\,q\), where \(m_0 = \sum \lambda_k h_k\).
Far-field (\(q\to\infty\)): \(X \approx m_\infty q + b_\infty\), where \(m_\infty = \sum_{k:\,\lambda_k=1} h_k\) and \(b_\infty = \sum_{k:\,\lambda_k<1} \frac{\lambda_k h_k}{\sqrt{1-\lambda_k^2}}\).
The initial estimate is chosen as:
\(q_0 = X / m_0\) when \(X \le X^*\) (near-field),
\(q_0 = (X - b_\infty) / m_\infty\) otherwise.
where \(X^* = m_0\,q^*\) and \(q^* = b_\infty/(m_0-m_\infty)\).
- laytracer.newton_step(q_i, X_target, h, lmd)[source]#
One second-order (quadratic) Newton step.
Solves the local quadratic approximation
\[\tfrac{1}{2}\,X''(q_i)\,\Delta q^2 + X'(q_i)\,\Delta q + \bigl[X(q_i) - X_R\bigr] = 0\]and selects the root that minimises \(|X(q_i+\Delta q)-X_R|\).
- Parameters:
- q_ifloat
Current iterate.
- X_targetfloat
Desired horizontal range.
- h, lmdnumpy.ndarray
Layer thicknesses and velocity ratios.
- Returns:
- q_newfloat
Updated iterate.
- X_newfloat
Offset at
q_new.
Multi-ray interface#
- laytracer.trace_rays(sources, receivers, velocity_df, source_phase='P', reflection=None, refraction=None, requested=('travel_times', 'rays', 'ray_parameters'), transcoef_method='standard', n_jobs=-1, backend='loky', sequential_limit=10000, rays_per_chunk=None, tol=0.0001, max_iter=10, verbose=True, itinerary=None)[source]#
Trace rays for all source-receiver pairs.
Every source is paired with every receiver, producing
n_src x n_rcvrays (each source traced to all receivers).- Parameters:
- sourcesnumpy.ndarray
Source coordinates, shape
(n_src, 3)or(3,).- receiversnumpy.ndarray
Receiver coordinates, shape
(n_rcv, 3)or(3,).- velocity_dfpandas.DataFrame
Velocity model with columns
Depth,Vp,Vsand optionallyRho,Qp,Qs.- source_phasestr or sequence of str
Initial wave phase(s) at source:
'P','SV','SH', or legacy'S'(alias for'SV'). If a sequence is provided, a dictionary ofTraceResultobjects keyed by canonical phase is returned.- reflectionlist of (depth, phase), optional
Reflection points as
(depth, out_phase)tuples.- refractionlist of (depth, phase), optional
Refraction / mode-conversion points as
(depth, out_phase)tuples.- requestedsequence of str, optional
Explicit set of requested outputs. Valid names are
travel_times,rays,ray_parameters,tstar,spreading,trans_product,complex_coefficient_product,diagnostics, andsensitivities. The set must includetravel_times. Diagnostic and sensitivity records are allocated only when explicitly requested.- transcoef_methodstr
'standard'(Zoeppritz) or'normalized'. The legacy spelling'angle'is an alias for'standard'.- n_jobsint
Number of parallel jobs (
-1= all physical cores).- backendstr
Joblib parallel backend (default
'loky').- sequential_limitint
If the total number of rays is below this threshold, run sequentially to avoid parallel overhead.
- rays_per_chunkint or None
Maximum number of rays per task above
sequential_limit. It bounds the memory a task holds while it runs, not the size of the output. If None, it is chosen from the number of rays and workers and from the measured output size per ray (see Notes).- tolfloat
Newton convergence tolerance (m).
- max_iterint
Maximum Newton iterations.
- verbosebool
If True, print the task plan, the estimated output size and the progress of tracing above
sequential_limit.- itineraryRayItinerary, optional
Explicit ordered interaction sequence. It cannot be combined with legacy
reflectionorrefractionarguments. The itinerary’s source phase is authoritative; a non-default explicitsource_phasemust agree with it.
- Returns:
- TraceResult or dict of TraceResult
Notes
Above
sequential_limitthe source-receiver matrix is split into tiles of at mostrays_per_chunkrays. Each task writes its rays into NumPy columns, and the columns are copied into the preallocated output as soon as the task finishes. Memory use is therefore the output itself plus a few tiles per worker, independent of the number of rays. With thelokybackend each worker gets one BLAS/OpenMP thread, because tracing makes no BLAS calls and OpenBLAS on Windows commits a buffer for every thread when NumPy is imported.The output size per ray is measured on a probe of up to 64 rays: exactly for array outputs and approximately for ray paths, diagnostics and sensitivities. With
rays_per_chunk=Nonea tile holds at most 65,536 rays and 16 MiB of results, and each worker gets at least 16 tasks. ARuntimeWarningis issued if the estimated output exceeds the available memory.
- class laytracer.TraceResult(travel_times, rays=None, ray_parameters=None, tstar=None, spreading=None, trans_product=None, source_phase=None, complex_coefficient_product=None, diagnostics=None, sensitivities=None)[source]#
Container for multi-ray tracing results.
- Attributes:
- travel_timesnumpy.ndarray
Travel times (s), shape
(n_rays,).- rayslist of numpy.ndarray or None
Ray paths; each element is shape
(M_i, 3)in the original 3-D coordinate system. None if not requested.- ray_parametersnumpy.ndarray or None
Horizontal slowness p for each ray, shape
(n_rays,).- tstarnumpy.ndarray or None
Attenuation operator \(t^*\) for each ray, shape
(n_rays,).- spreadingnumpy.ndarray or None
Relative geometrical spreading factor for each ray, shape
(n_rays,).- trans_productnumpy.ndarray or None
Real, nonnegative product of interface-coefficient magnitudes along each ray.
- source_phasestr or None
Canonical source phase for this result.
- complex_coefficient_productnumpy.ndarray or None
Signed/complex cumulative interface coefficient for each ray.
- diagnosticslist of SolveDiagnostics or None
Per-ray numerical certificates, if requested.
- sensitivitieslist of RaySensitivity or None
Per-ray fixed-topology analytic derivatives, if requested.
- class laytracer.Interaction(depth, kind, outgoing_phase)[source]#
One ordered reflection or transmission in a prescribed itinerary.
- Parameters:
- depthfloat
Model-interface depth (m, positive downward).
- kind{“reflect”, “transmit”}
Whether propagation reverses or retains its vertical direction.
- outgoing_phase{“P”, “SV”, “SH”, “S”}
Phase immediately after the interaction.
"S"is normalized to"SV".
- class laytracer.RayItinerary(source_phase, interactions)[source]#
An ordered, fixed-topology phase itinerary.
- class laytracer.RaySensitivity(vp_layer_indices, dtravel_time_dvp, dray_parameter_dvp, vs_layer_indices, dtravel_time_dvs, dray_parameter_dvs, interface_indices, dtravel_time_dinterface_depths, dray_parameter_dinterface_depths, dtravel_time_dsource, dtravel_time_dreceiver, dray_parameter_dsource, dray_parameter_dreceiver, ray_parameter=nan, doffset_dray_parameter=nan, valid=True, reason=None)[source]#
Sparse derivatives for one fixed-topology ray.
Layer derivative arrays contain values only for the model-layer indices listed by the corresponding
*_layer_indicesfield. Interface indices are row indices into the modelDeptharray; the surface row is omitted.The derivatives are valid while layer membership, prescribed phase itinerary, and the propagating branch remain unchanged.
ray_parameteranddoffset_dray_parameterretain \(p\) and \(X_p=\partial X/\partial p\) from the solved ray. They support the optional second-order endpoint predictor without another ray solve.
Traveltime approximation#
- laytracer.linearized_ray_change(sensitivity, *, delta_vp=None, delta_vs=None, delta_interface_depths=None, delta_source=None, delta_receiver=None)[source]#
Predict first-order output changes for one fixed-topology ray.
- Parameters:
- sensitivityRaySensitivity
Valid sparse sensitivity record returned by
trace_rays.- delta_vp, delta_vsarray-like, optional
Full model-row-indexed velocity perturbations (m/s).
- delta_interface_depthsarray-like, optional
Full model-row-indexed interface-depth perturbations (m).
- delta_source, delta_receiverarray-like, optional
Three-component endpoint-coordinate perturbations (m).
- Returns:
- LinearizedRayChange
First-order traveltime and physical ray-parameter changes.
Notes
Omitted perturbations are treated as zero. The calculation is valid only while the ray topology represented by
sensitivityremains unchanged.
- laytracer.select_anchors(points, max_distance, groups=None)[source]#
Select deterministic farthest-point anchors covering a point cloud.
- Parameters:
- pointsarray-like
Finite point coordinates, shape
(n_points, 3).- max_distancefloat
Maximum Euclidean point-to-anchor distance (m).
- groupsarray-like, optional
One group label per point. Coverage is constructed independently in each group, which can prevent anchors from crossing model layers.
- Returns:
- AnchorSelection
Selected indices and coordinates plus nearest-anchor assignments.
Notes
Selection begins at the lexicographically smallest point in each group, then repeatedly adds the farthest uncovered point. Ties are resolved by original point index, making the result deterministic.
- class laytracer.LinearizedRayChange(delta_travel_time, delta_ray_parameter)[source]#
First-order changes predicted from one ray sensitivity record.
- Attributes:
- delta_travel_timefloat
Predicted traveltime change (s).
- delta_ray_parameterfloat
Predicted physical horizontal-slowness change (s/m).
- class laytracer.AnchorSelection(indices, points, assignments, distances)[source]#
Deterministic point-cloud anchor selection and assignments.
- Attributes:
- indicesnumpy.ndarray
Indices of selected anchors in the input point array.
- pointsnumpy.ndarray
Selected anchor coordinates, shape
(n_anchors, 3).- assignmentsnumpy.ndarray
Anchor-position assigned to each input point.
- distancesnumpy.ndarray
Euclidean distance from each point to its assigned anchor (m).
- class laytracer.TravelTimeApproximator(velocity_model, source_phase, itinerary, fit_sources, fit_receivers, source_max_distance, receiver_max_distance, source_anchor_indices, receiver_anchor_indices, anchor_sources, anchor_receivers, anchor_trace, anchor_topologies)[source]#
Fitted topology-safe endpoint-Taylor traveltime approximator.
Use
fitto construct instances. The fitted velocity model and itinerary are fixed; model changes require refitting.- Attributes:
- source_anchor_indices, receiver_anchor_indicesnumpy.ndarray
Original endpoint indices retained as anchors.
- anchor_sources, anchor_receiversnumpy.ndarray
Anchor coordinates.
- anchor_traceTraceResult
Exact Cartesian-product ray trace at the anchors.
- source_max_distance, receiver_max_distancefloat or None
Endpoint coverage limits used during fitting.
- property exact_ray_count#
Number of exact source-anchor to receiver-anchor rays.
- classmethod fit(sources, receivers, velocity_model, *, source_max_distance, receiver_max_distance, source_phase='P', itinerary=None, n_jobs=-1, backend='loky', sequential_limit=5000, rays_per_chunk=None, tol=1e-06, max_iter=20, verbose=False)[source]#
Fit exact anchors to a source-receiver target domain.
- Parameters:
- sources, receiversarray-like
Endpoint coordinates with shape
(N, 3)or(3,).- velocity_modelpandas.DataFrame
Layer model accepted by
trace_rays.- source_max_distance, receiver_max_distancefloat or None
Maximum endpoint-to-anchor distances (m).
Noneretains every supplied endpoint of that type as an exact anchor.- source_phase{“P”, “SV”, “SH”, “S”}
One direct-ray source phase. Ignored when
itineraryis given.- itineraryRayItinerary, optional
Explicit ordered fixed-topology path.
- n_jobs, backend, sequential_limit, rays_per_chunk, tol, max_iter, verbose
Controls forwarded to the exact anchor call to
trace_rays.
- Returns:
- TravelTimeApproximator
Fitted anchor set and exact anchor rays.
- predict(sources=None, receivers=None, *, order=1)[source]#
Predict traveltimes for targets inside the fitted anchor domain.
- Parameters:
- sources, receiversarray-like, optional
Query endpoints. Omitted arrays default to the corresponding points supplied to
fit.- order{1, 2}
Endpoint Taylor order. Second order adds fixed-topology curvature and evaluates direct same-layer paths exactly. The default retains the original first-order predictor.
- Returns:
- TravelTimePrediction
Source-major predictions, masks, reason codes, and anchor mapping.
Notes
Unsupported targets are returned as
NaNand are never retraced. Possible reason codes are"unreachable_topology","no_topology_match","outside_anchor_distance", and"invalid_anchor_sensitivity".
- class laytracer.TravelTimePrediction(travel_times, valid_mask, reasons, anchor_ray_indices, source_anchor_distances, receiver_anchor_distances, n_sources, n_receivers)[source]#
Predicted traveltimes and anchor-assignment diagnostics.
All one-dimensional arrays use source-major ordering: every receiver for source zero, followed by every receiver for source one, and so on.
- Attributes:
- travel_timesnumpy.ndarray
Predicted traveltimes (s); invalid entries are
NaN.- valid_masknumpy.ndarray
Whether each prediction is valid.
- reasonsnumpy.ndarray
Reason code for each prediction.
- anchor_ray_indicesnumpy.ndarray
Flat index of the selected exact anchor ray, or
-1if invalid.- source_anchor_distances, receiver_anchor_distancesnumpy.ndarray
Endpoint distances to the selected anchor ray (m), or
NaNif invalid.- n_sources, n_receiversint
Dimensions used by the matrix-view properties.
- property travel_time_matrix#
Return traveltimes with shape
(n_sources, n_receivers).
- property valid_matrix#
Return the validity mask with shape
(n_sources, n_receivers).
- property reason_matrix#
Return reason codes with shape
(n_sources, n_receivers).
- property anchor_ray_index_matrix#
Return selected anchor-ray indices in source-major matrix form.
- property source_anchor_distance_matrix#
Return source-to-anchor distances in source-major matrix form.
- property receiver_anchor_distance_matrix#
Return receiver-to-anchor distances in source-major matrix form.
Amplitude#
- laytracer.transmission_normal(v1, rho1, v2, rho2)[source]#
Normal-incidence displacement transmission coefficient.
\[T = \frac{2\,Z_1}{Z_1 + Z_2}, \qquad Z_i = \rho_i\,v_i\]- Parameters:
- v1, rho1float
Velocity (m/s) and density (kg/m³) on the incident side.
- v2, rho2float
Velocity and density on the transmitted side.
- Returns:
- float
Displacement amplitude transmission coefficient.
- laytracer.sh_rt_coefficients(p, vs1, rho1, vs2, rho2)[source]#
Compute SH-SH reflection and transmission coefficients.
The welded solid-solid SH system is decoupled from the P-SV system in isotropic layered media. With vertical slowness \(\eta_i = \sqrt{1/v_{Si}^2 - p^2}\), the displacement coefficients are
\[R_{SHSH} = \frac{\rho_1 v_{S1}^2 \eta_1 - \rho_2 v_{S2}^2 \eta_2} {\rho_1 v_{S1}^2 \eta_1 + \rho_2 v_{S2}^2 \eta_2},\]\[T_{SHSH} = \frac{2 \rho_1 v_{S1}^2 \eta_1} {\rho_1 v_{S1}^2 \eta_1 + \rho_2 v_{S2}^2 \eta_2}.\]- Parameters:
- pfloat or array_like
Ray parameter (horizontal slowness, s/m). Scalar or 1-D array.
- vs1, rho1float
S-wave velocity and density of the incident medium.
- vs2, rho2float
S-wave velocity and density of the transmitted medium.
- Returns:
- dict
Keys
'Rshsh'and'Tshsh'with the same shape as p.
- laytracer.psv_rt_coefficients(p, vp1, vs1, rho1, vp2, vs2, rho2)[source]#
Compute all eight P-SV reflection/transmission coefficients.
Direct port of the Ammon MATLAB
PSVRTmatrixfunction (Lay & Wallace / Aki & Richards formulation).For an incident P-wave the system unknowns are \([R_{PP},\; R_{PS},\; T_{PP},\; T_{PS}]\). For an incident SV-wave the unknowns are \([R_{SP},\; R_{SS},\; T_{SP},\; T_{SS}]\).
- Parameters:
- pfloat or array_like
Ray parameter (horizontal slowness, s/m). Scalar or 1-D array.
- vp1, vs1, rho1float
P-velocity, S-velocity, density of the incident medium.
- vp2, vs2, rho2float
Same for the transmitted medium.
- Returns:
- dict
Keys
'Rpp','Rps','Rss','Rsp','Tpp','Tps','Tss','Tsp'. Each value has the same shape as p (complex).
- laytracer.critical_angle(v_incident, v_outgoing)[source]#
Return the critical angle for a faster outgoing wave.
The critical angle exists only when
v_outgoing > v_incidentand is\[\theta_c = \arcsin\left(\frac{v_\mathrm{incident}}{v_\mathrm{outgoing}}\right)\]- Parameters:
- v_incidentfloat
Phase velocity of the incident wave.
- v_outgoingfloat
Phase velocity of the reflected or transmitted wave.
- Returns:
- float or None
Critical angle in degrees, or None when the outgoing wave remains propagating over the full 0–90 degree incidence range.
- laytracer.find_critical_angles(v_incident, velocities, labels=None, include_none=False)[source]#
Find critical angles for one or more outgoing wave speeds.
- Parameters:
- v_incidentfloat
Phase velocity of the incident wave.
- velocitiesdict or sequence of float
Candidate outgoing wave speeds. If a dictionary is provided, its keys are used as labels.
- labelslist of str, optional
Labels to use when velocities is not a dictionary.
- include_nonebool, optional
If True, keep entries without a critical angle as
None. Default False.
- Returns:
- dict[str, float or None]
Mapping from label to critical angle in degrees. Entries without a critical angle are omitted unless
include_none=True.
- laytracer.normalize_rt_coefficient(R_bar, p, v_in, rho_in, v_out, rho_out)[source]#
Apply Červený (2001) normalization to a displacement R/T coefficient.
Eq. 5.3.10:
\[R_{mn} = \bar{R}_{mn} \left( \frac{V(\tilde Q)\,\rho(\tilde Q)\,P(\tilde Q)} {V(Q)\,\rho(Q)\,P(Q)} \right)^{1/2}\]where \(P(Q) = (1 - V^2 p^2)^{1/2}\).
- Parameters:
- R_barcomplex or float
Standard (unnormalized) displacement coefficient.
- pfloat
Ray parameter (horizontal slowness, s/m).
- v_infloat
Phase velocity of the incident wave (m/s).
- rho_infloat
Density of the incident medium (kg/m³).
- v_outfloat
Phase velocity of the outgoing (reflected/transmitted) wave (m/s).
- rho_outfloat
Density of the outgoing medium (kg/m³).
- Returns:
- complex or float
Normalized displacement coefficient.
- laytracer.find_brewster_angles(rt_coefficients, angles, keys=None, threshold=0.05, order=20)[source]#
Find Brewster-like angles (deep minima) in R/T coefficient curves.
A Brewster angle (by analogy with optics) is an incidence angle at which a reflection or transmission coefficient passes through zero or a deep minimum. Unlike critical angles, which depend only on velocity ratios, Brewster angles depend on all six elastic parameters (Vp, Vs, ρ in both media) and arise from destructive interference between displacement potentials at the interface.
- Parameters:
- rt_coefficientsdict
Output of
psv_rt_coefficients— each value is a 1-D array of complex coefficients.- anglesarray_like
Incidence angles (degrees) corresponding to the ray-parameter samples used in rt_coefficients. Must have the same length as the coefficient arrays.
- keyslist of str, optional
Which coefficient keys to search (e.g.
['Rps', 'Rss']). By default all eight keys are searched.- thresholdfloat, optional
Only report minima whose absolute value is below this value. Default 0.05.
- orderint, optional
Half-window size passed to
scipy.signal.argrelminfor local-minimum detection. Default 20.
- Returns:
- dict[str, list[float]]
Mapping from coefficient key to a list of Brewster angles (degrees). Keys with no detected minima are omitted.
Visualisation#
- laytracer.plot.coefficient_panels(panels, shape, *, figsize=(12, 9), sharex=True, sharey=False, suptitle=None, suptitle_fontsize=11, default_x=None, default_xlim=None, default_ylim=None, default_xlabel=None, legend_fontsize=8, grid_alpha=0.3)[source]#
Plot coefficient curves in a configurable panel grid.
- Parameters:
- panelssequence of dict
One panel specification per subplot in row-major order. Each panel dictionary may contain:
xarray_like, optionalShared abscissa for all curves in the panel. If omitted, default_x is used.
curveslist of dict, optionalCurve specifications. Each curve dict must contain
yand may containlabelplusplot_kwargs. To style complex-valued coefficient regions, providecomplex_fromas the complex coefficient array used for detection. Samples satisfyingabs(imag(C)) > complex_tol * max(1, abs(C))are plotted withcomplex_plot_kwargs(default{'ls': '--'}). To style regions where the outgoing branch itself is evanescent, provideevanescent_mask; those samples are plotted withevanescent_plot_kwargs(default{'ls': '-.'}).markerslist of dict, optionalVertical-line marker specifications. Each marker dict must contain
angleand may containlabelplusline_kwargs.title,xlabel,ylabelstr, optionalPer-panel labels.
xlim,ylimtuple, optionalPer-panel axis limits.
legendbool, optionalWhether to draw a legend for this panel.
legend_locstr, optionalLegend location. Default
'upper right'.legend_fontsizefloat or str, optionalLegend font size override for this panel.
gridbool, optionalWhether to draw the grid. Default True.
grid_alphafloat, optionalGrid alpha override for this panel.
- shapetuple of int
Panel layout
(nrows, ncols).- figsizetuple of float, optional
Figure size passed to
matplotlib.pyplot.subplots.- sharex, shareybool, optional
Forwarded to
matplotlib.pyplot.subplots.- suptitlestr, optional
Figure title.
- suptitle_fontsizefloat, optional
Font size for suptitle.
- default_xarray_like, optional
Shared x-axis array used when a panel does not define
x.- default_xlim, default_ylimtuple, optional
Default axis limits for panels that do not override them.
- default_xlabelstr, optional
Default x-axis label for panels that do not define
xlabel.- legend_fontsizefloat or str, optional
Default legend font size.
- grid_alphafloat, optional
Default grid alpha.
- Returns:
- tuple
(fig, axes)from matplotlib.
- laytracer.plot.velocity_profile(vel_df, param='Vp', ax=None, color=None, label=None, xlim=None, ylim=None, unit='m', **kwargs)[source]#
Plot a 1-D model parameter–depth step profile.
- Parameters:
- vel_dfpandas.DataFrame
Velocity model.
- paramstr, optional
'Vp'(default),'Vs','Rho','Qp', or'Qs'.- axmatplotlib.axes.Axes, optional
Axes to plot on. Created if None.
- colorstr, optional
Line colour.
- labelstr, optional
Legend label.
- xlim, ylimtuple, optional
Axis limits
(min, max).- unitstr, optional
'm'(default) or'km'. Scales the vertical depth axis.
- Returns:
- matplotlib.axes.Axes
- laytracer.plot.rays_2d(vel_df, rays, vel_type='Vp', sources=None, receivers=None, ax=None, ray_color='k', ray_alpha=0.6, ray_linewidth=0.8, xlim=None, ylim=None, unit='m', plot_model=True, add_colorbar=False, discrete_colorbar=False, layer_colors=None, model_alpha=1.0, equal_scale=True, colorbar_orientation='vertical', **kwargs)[source]#
Plot ray paths over a 2-D layered velocity cross-section.
- Parameters:
- vel_dfpandas.DataFrame
Velocity model.
- rayslist of numpy.ndarray
Each element is shape
(M, 2)or(M, 3). If 3-D, the first two columns are treated as horizontal/depth.- vel_typestr
'Vp'or'Vs'— used for layer colouring.- sources, receiversnumpy.ndarray, optional
Coordinate arrays for plotting markers.
- axmatplotlib.axes.Axes, optional
- ray_colorstr
- ray_alphafloat
- ray_linewidthfloat
Ray line width.
- xlim, ylimtuple, optional
- plot_modelbool
If True (default), plot the velocity model background and set axis labels/titles. If False, only plot the rays and markers.
- unitstr
'm'(default) or'km'. Scales coordinates and labels.- add_colorbarbool
If True (default False), add a colorbar for the velocity model. Only applies if plot_model is True.
- discrete_colorbarbool
If True (default False), quantize the colormap to the unique velocity values in the model.
- layer_colorssequence of str, optional
Custom colors for the velocity model layers. If omitted,
viridisis used.- model_alphafloat
Opacity of the velocity model layers (0.0 to 1.0). Default 1.0.
- equal_scalebool
If True (default True), force equal scaling for x and y axes using
ax.set_aspect('equal').- colorbar_orientationstr
'vertical'(default) or'horizontal'.
- Returns:
- matplotlib.axes.Axes
- laytracer.plot.rays_3d(vel_df, rays, vel_type='Vp', sources=None, receivers=None, ray_color='red', opacity=0.3, **kwargs)[source]#
Interactive 3-D ray visualisation using Plotly.
- Parameters:
- vel_dfpandas.DataFrame
Velocity model.
- rayslist of numpy.ndarray
Each element is shape
(M, 3).- vel_typestr
'Vp'or'Vs'.- sources, receiversnumpy.ndarray, optional
Coordinate arrays for plotting markers.
- ray_colorstr
Ray trace colour.
- opacityfloat
Layer surface opacity.
- Returns:
- plotly.graph_objects.Figure