[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7C11Y53RW6YJ652HNB08S2Q":3,"skill-same:01M7C11Y53RW6YJ652HNB08S2Q":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7C11Y53RW6YJ652HNB08S2Q","seisbench-model-api",null,"An overview of the core model API of SeisBench, a Python framework for training and applying machine learning algorithms to seismic data. It is useful for annotating waveforms using pretrained SOTA ML models, for tasks like phase picking, earthquake detection, waveform denoising and depth estimation. For any waveform, you can manipulate it into an obspy stream object and it will work seamlessly with seisbench models.","linyouxue\u002Fskill-repair-benchmark","linyouxue","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F216151464?v=4","01M7BJEVCXKD74KH6FG9CBVSQB","林宥学","01M7BJEVE02NP217V93BKZFC0J",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002FSkillOpt-adapted-gpt52-n3L4R2-v25\u002Ftasks\u002Fseismic-phase-picking\u002Frepaired_skill\u002Fseisbench-model-api\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: seisbench-model-api\ndescription: An overview of the core model API of SeisBench, a Python framework for training and applying machine learning algorithms to seismic data. It is useful for annotating waveforms using pretrained SOTA ML models, for tasks like phase picking, earthquake detection, waveform denoising and depth estimation. For any waveform, you can manipulate it into an obspy stream object and it will work seamlessly with seisbench models.\n---\n\n# SeisBench Model API\n\n## Installing SeisBench\nThe recommended way is installation through pip. Simply run:\n```\npip install seisbench\n```\n\n## Overview\n\nSeisBench offers the abstract class `WaveformModel` that every SeisBench model should subclass. This class offers two core functions, `annotate` and `classify`. Both of the functions are automatically generated based on configurations and submethods implemented in the specific model.\n\nThe `SeisBenchModel` bridges the gap between the pytorch interface of the models and the obspy interface common in seismology. It automatically assembles obspy streams into pytorch tensors and reassembles the results into streams. It also takes care of batch processing. Computations can be run on GPU by simply moving the model to GPU.\n\nThe `annotate` function takes an obspy stream object as input and returns annotations as stream again. For example, for picking models the output would be the characteristic functions, i.e., the pick probabilities over time.\n\n```python\nstream = obspy.read(\"my_waveforms.mseed\")\nannotations = model.annotate(stream)  # Returns obspy stream object with annotations\n```\n\nThe `classify` function also takes an obspy stream as input, but in contrast to the `annotate` function returns discrete results. The structure of these results might be model dependent. For example, a pure picking model will return a list of picks, while a picking and detection model might return a list of picks and a list of detections.\n\n```python\nstream = obspy.read(\"my_waveforms.mseed\")\noutputs = model.classify(stream)  # Returns a list of picks\nprint(outputs)\n```\n\nBoth `annotate` and `classify` can be supplied with waveforms from multiple stations at once and will automatically handle the correct grouping of the traces. For details on how to build your own model with SeisBench, check the documentation of `WaveformModel`. For details on how to apply models, check out the Examples.\n\n## Loading Pretrained Models\n\nFor annotating waveforms in a meaningful way, trained model weights are required. SeisBench offers a range of pretrained model weights through a common interface. Model weights are downloaded on the first use and cached locally afterwards. For some model weights, multiple versions are available. For details on accessing these, check the documentation at `from_pretrained`.\n\n```python\nimport seisbench.models as sbm\n\nsbm.PhaseNet.list_pretrained()                  # Get available models\nmodel = sbm.PhaseNet.from_pretrained(\"original\")  # Load the original model weights released by PhaseNet authors\n```\n\nPretrained models can not only be used for annotating data, but also offer a great starting point for transfer learning.\n\n## Speeding Up Model Application\n\nWhen applying models to large datasets, run time is often a major concern. Here are a few tips to make your model run faster:\n\n- **Run on GPU.** Execution on GPU is usually faster, even though exact speed-ups vary between models. However, we note that running on GPU is not necessarily the most economic option. For example, in cloud applications it might be cheaper (and equally fast) to pay for a handful of CPU machines to annotate a large dataset than for a GPU machine.\n\n- **Use a large `batch_size`.** This parameter can be passed as an optional argument to all models. Especially on GPUs, larger batch sizes lead to faster annotations. As long as the batch fits into (GPU) memory, it might be worth increasing the batch size.\n\n- **Compile your model (torch 2.0+).** If you are using torch in version 2.0 or newer, compile your model. It's as simple as running `model = torch.compile(model)`. The compilation will take some time but if you are annotating large amounts of waveforms, it should pay off quickly. Note that there are many options for compile that might influence the performance gains considerably.\n\n- **Use asyncio interface.** Load data in parallel while executing the model using the asyncio interface, i.e., `annotate_asyncio` and `classify_asyncio`. This is usually substantially faster because data loading is IO-bound while the actual annotation is compute-bound.\n\n- **Manual resampling.** While SeisBench can automatically resample the waveforms, it can be faster to do the resampling manually beforehand. SeisBench uses obspy routines for resampling, which (as of 2023) are not parallelised. Check the required sampling rate with `model.sampling_rate`. Alternative routines are available, e.g., in the Pyrocko library.\n\n## Models Integrated into SeisBench\n\nYou don't have to build models from scratch if you don't want to. SeisBench integrates the following notable models from the literature for you to use. Again, as they inherit from the common SeisBench model interface, all these deep learning models are constructed through PyTorch. Where possible, the original trained weights are imported and made available. These can be accessed via the `from_pretrained` method.\n\n| Integrated Model | Task |\n|------------------|------|\n| `BasicPhaseAE` | Phase Picking |\n| `CRED` | Earthquake Detection |\n| `DPP` | Phase Picking |\n| `DepthPhaseNet` | Depth estimation from depth phases |\n| `DepthPhaseTEAM` | Depth estimation from depth phases |\n| `DeepDenoiser` | Denoising |\n| `SeisDAE` | Denoising |\n| `EQTransformer` | Earthquake Detection\u002FPhase Picking |\n| `GPD` | Phase Picking |\n| `LFEDetect` | Phase Picking (Low-frequency earthquakes) |\n| `OBSTransformer` | Earthquake Detection\u002FPhase Picking |\n| `PhaseNet` | Phase Picking |\n| `PhaseNetLight` | Phase Picking |\n| `PickBlue` | Earthquake Detection\u002FPhase Picking |\n| `Skynet` | Phase Picking |\n| `VariableLengthPhaseNet` | Phase Picking |\n\nCurrently integrated models are capable of earthquake detection and phase picking, waveform denoising, depth estimation, and low-frequency earthquake phase picking. Furthermore, with SeisBench you can build ML models to perform general seismic tasks such as magnitude and source parameter estimation, hypocentre determination etc.\n\n## Best Practices\n- If the waveform data happen to be extremely small in scale (`\u003C=1e-10`), there might be risk of numerical instability. It is acceptable to increase the value first (by multiplying a large number like `1e10`) before normalization or passing to the model.\n\n- Although the seisbench model API will normalize the waveform for you, it is still highly suggested to apply normalization yourself. Since seisbench's normalization scheme uses an epsilon `(waveform - mean(waveform)) \u002F (std(waveform) + epsilon)`, for extremely small values (such as `\u003C=1e-10`), their normalization can destroy the signals in the waveform.\n\n- The seisbench model API can process a stream of waveform data of arbitrary length. Hence, it is not necessary to segment the data yourself. In addition, you should not assume a stream of waveform can only contain one P-wave and one S-wave. It is the best to treat the stream like what it is: a stream of continuous data.\n\n\n\n## End-to-End Workflow for Custom NPZ Phase Picking\n\nFor each input NPZ, validate the required fields before invoking SeisBench and preserve the original sample coordinate system:\n\n```python\nimport numpy as np\n\n\ndef load_npz(path):\n    with np.load(path, allow_pickle=False) as z:\n        missing = {\"data\", \"dt\", \"channels\"} - set(z.files)\n        if missing:\n            raise ValueError(f\"{path}: missing {sorted(missing)}\")\n        x = np.asarray(z[\"data\"])\n        dt = float(np.asarray(z[\"dt\"]).reshape(()))\n        raw = np.asarray(z[\"channels\"]).reshape(()).item()\n        channels = [s.strip() for s in str(raw).split(\",\") if s.strip()]\n    if x.ndim != 2 or len(channels) != 3 or not np.isfinite(dt) or dt \u003C= 0:\n        raise ValueError(f\"{path}: expected finite 2-D three-component data and dt>0\")\n    if x.shape[1] == len(channels):\n        x = x.astype(np.float32, copy=False)       # samples x components\n    elif x.shape[0] == len(channels):\n        x = x.T.astype(np.float32, copy=False)\n    else:\n        raise ValueError(f\"{path}: data shape {x.shape} disagrees with channels\")\n    if not np.isfinite(x).all():\n        raise ValueError(f\"{path}: waveform contains NaN or infinity\")\n    return x, dt, channels\n```\n\nDo not silently guess an orientation, duplicate component, or invalid metadata; skip the file with a diagnostic or use the documented fallback. Keep `n_samples`, `dt`, and every preprocessing\u002Fwindow offset so a model time can later be converted back to the untrimmed source index.\n\n\n\n## Build and Verify the SeisBench Input Stream\n\nConstruct aligned ObsPy traces using the file-specific sampling rate. Channel labels must drive the component mapping; never assume that the columns are Z,N,E. A common three-component mapping is a code ending in `Z` for vertical and codes ending in `N`\u002F`1` and `E`\u002F`2` for horizontals, but reject ambiguous or duplicate mappings rather than inventing one.\n\n```python\nfrom obspy import Stream, Trace, UTCDateTime\n\n\ndef make_stream(x, dt, channels):\n    start = UTCDateTime(0)  # relative origin when the file has no acquisition time\n    return Stream([\n        Trace(data=x[:, j].copy(), header={\n            \"channel\": ch,\n            \"starttime\": start,\n            \"sampling_rate\": 1.0 \u002F dt,\n        }) for j, ch in enumerate(channels)\n    ])\n\n\ndef component_map(channels):\n    groups = {}\n    for j, ch in enumerate(channels):\n        c = ch.upper().split(\".\")[-1]\n        suffix = c[-1:] if c else \"\"\n        groups.setdefault(suffix, []).append(j)\n    z = [j for j, ch in enumerate(channels) if ch.upper().split(\".\")[-1].endswith(\"Z\")]\n    h1 = [j for j, ch in enumerate(channels) if ch.upper().split(\".\")[-1].endswith((\"N\", \"1\"))]\n    h2 = [j for j, ch in enumerate(channels) if ch.upper().split(\".\")[-1].endswith((\"E\", \"2\"))]\n    if len(z) != 1 or len(h1) != 1 or len(h2) != 1 or len({z[0], h1[0], h2[0]}) != 3:\n        raise ValueError(f\"unsupported or ambiguous component layout: {channels}\")\n    return {\"Z\": z[0], \"H1\": h1[0], \"H2\": h2[0]}\n```\n\nBefore inference, inspect the installed model rather than assuming one release's API: use `getattr(model, \"sampling_rate\", None)` and any documented channel\u002Fcomponent metadata. If the model has a required sampling rate, resample a copy only when necessary and map the resulting pick time back using elapsed seconds and the original `dt`. Confirm that the selected pretrained model accepts three components and that its expected order is satisfied; otherwise choose a compatible model or use the fallback. `UTCDateTime(0)` is only a relative bookkeeping origin, not a fabricated acquisition timestamp.\n\n\n\n## CPU-Conscious, Version-Aware Inference and Pick Extraction\n\nModel downloads are optional: try a locally cached or explicitly selected pretrained model, catch download\u002Fload errors, and do not make network access a prerequisite. Run on CPU by default (`model.to(\"cpu\")` when supported), use `batch_size=1` or a small batch, and avoid assuming CUDA. For long records, infer overlapping windows and retain each window's source start sample. SeisBench can batch arbitrary streams, but explicit windows make memory use and coordinate conversion clear.\n\n```python\nimport inspect\nimport numpy as np\n\n\ndef call_api(model, stream):\n    # Signatures and return structures vary by SeisBench version.\n    try:\n        return model.classify(stream)\n    except (AttributeError, TypeError, NotImplementedError):\n        return model.annotate(stream)\n\n\ndef output_arrays(out):\n    \"\"\"Return (time arrays, P arrays, S arrays) for common annotation forms.\"\"\"\n    if out is None:\n        return None\n    if hasattr(out, \"traces\"):  # ObsPy Stream annotations\n        vals = {}\n        for tr in out:\n            name = tr.stats.channel.upper()\n            vals[name] = np.asarray(tr.data, dtype=float)\n        p = next((v for k, v in vals.items() if \"P\" in k), None)\n        s = next((v for k, v in vals.items() if \"S\" in k), None)\n        return p, s\n    if isinstance(out, dict):\n        p = out.get(\"P\", out.get(\"p\", out.get(\"P_probability\")))\n        s = out.get(\"S\", out.get(\"s\", out.get(\"S_probability\")))\n        return (None if p is None else np.asarray(p, float),\n                None if s is None else np.asarray(s, float))\n    return None\n```\n\nWhen `classify` returns discrete picks, inspect each pick's phase and time fields rather than treating the object as an annotation curve. When `annotate` returns curves, locate P\u002FS channels by their labels, reject empty, nonfinite, or all-zero outputs, and use `scipy.signal.find_peaks` (or a documented equivalent) with a phase-specific height\u002Fprominence and minimum-distance threshold. A probability peak's time may be represented by `trace.stats.starttime + i \u002F sampling_rate`; convert it to the source index with `round((pick_time - source_starttime) \u002F original_dt)`. For a window beginning at source sample `w0`, use `w0 + round(local_time \u002F original_dt)`, not merely the local peak index. Clip neither silently nor out of bounds: reject indices outside `[0, n_samples)` and retain confidence for diagnostics. Merge overlapping-window duplicates by phase and time, keeping the highest-confidence candidate.\n\n\n\n## Failure Handling and Classical Fallback\n\nTreat model failure as an expected operational case: catch pretrained-weight download errors, incompatible channel layouts, unsupported sampling rates, runtime\u002FOOM errors, malformed or empty `annotate`\u002F`classify` results, and absent P\u002FS outputs. Do not fabricate picks from a failed model. A CPU-only environment is normal; reduce window length\u002Fbatch size before abandoning inference.\n\nIf no usable model output is available, run a deterministic NumPy\u002FObsPy fallback on the validated original-rate array. Detrend or normalize copies without changing the sample grid; use vertical energy\u002Fonset or STA\u002FLTA for P and delayed horizontal energy\u002Fenvelope or STA\u002FLTA for S. Estimate noise from an early or robust low-amplitude region, require finite positive SNR\u002Fprominence, and allow no pick when evidence is insufficient. This fallback is a candidate generator, not a guarantee of a phase, and must return source indices directly. Do not force P-before-S or invent a missing phase.\n\nFinally write `\u002Froot\u002Fresults.csv` with exactly `file_name,phase,pick_idx`. Validate each row before writing: phase is exactly `P` or `S`, `pick_idx` is an integer in `[0, n_samples)`, and the filename is the actual input filename. Deduplicate identical phase\u002Findex rows, permit multiple or zero picks per file, and log skipped files and fallback use separately from the CSV.\n","# SeisBench Model API\n\n## Installing SeisBench\nThe recommended way is installation through pip. Simply run:\n```\npip install seisbench\n```\n\n## Overview\n\nSeisBench offers the abstract class `WaveformModel` that every SeisBench model should subclass. This class offers two core functions, `annotate` and `classify`. Both of the functions are automatically generated based on configurations and submethods implemented in the specific model.\n\nThe `SeisBenchModel` bridges the gap between the pytorch interface of the models and the obspy interface common in seismology. It automatically assembles obspy streams into pytorch tensors and reassembles the results into streams. It also takes care of batch processing. Computations can be run on GPU by simply moving the model to GPU.\n\nThe `annotate` function takes an obspy stream object as input and returns annotations as stream again. For example, for picking models the output would be the characteristic functions, i.e., the pick probabilities over time.\n\n```python\nstream = obspy.read(\"my_waveforms.mseed\")\nannotations = model.annotate(stream)  # Returns obspy stream object with annotations\n```\n\nThe `classify` function also takes an obspy stream as input, but in contrast to the `annotate` function returns discrete results. The structure of these results might be model dependent. For example, a pure picking model will return a list of picks, while a picking and detection model might return a list of picks and a list of detections.\n\n```python\nstream = obspy.read(\"my_waveforms.mseed\")\noutputs = model.classify(stream)  # Returns a list of picks\nprint(outputs)\n```\n\nBoth `annotate` and `classify` can be supplied with waveforms from multiple stations at once and will automatically handle the correct grouping of the traces. For details on how to build your own model with SeisBench, check the documentation of `WaveformModel`. For details on how to apply models, check out the Examples.\n\n## Loading Pretrained Models\n\nFor annotating waveforms in a meaningful way, trained model weights are required. SeisBench offers a range of pretrained model weights through a common interface. Model weights are downloaded on the first use and cached locally afterwards. For some model weights, multiple versions are available. For details on accessing these, check the documentation at `from_pretrained`.\n\n```python\nimport seisbench.models as sbm\n\nsbm.PhaseNet.list_pretrained()                  # Get available models\nmodel = sbm.PhaseNet.from_pretrained(\"original\")  # Load the original model weights released by PhaseNet authors\n```\n\nPretrained models can not only be used for annotating data, but also offer a great starting point for transfer learning.\n\n## Speeding Up Model Application\n\nWhen applying models to large datasets, run time is often a major concern. Here are a few tips to make your model run faster:\n\n- **Run on GPU.** Execution on GPU is usually faster, even though exact speed-ups vary between models. However, we note that running on GPU is not necessarily the most economic option. For example, in cloud applications it might be cheaper (and equally fast) to pay for a handful of CPU machines to annotate a large dataset than for a GPU machine.\n\n- **Use a large `batch_size`.** This parameter can be passed as an optional argument to all models. Especially on GPUs, larger batch sizes lead to faster annotations. As long as the batch fits into (GPU) memory, it might be worth increasing the batch size.\n\n- **Compile your model (torch 2.0+).** If you are using torch in version 2.0 or newer, compile your model. It's as simple as running `model = torch.compile(model)`. The compilation will take some time but if you are annotating large amounts of waveforms, it should pay off quickly. Note that there are many options for compile that might influence the performance gains considerably.\n\n- **Use asyncio interface.** Load data in parallel while executing the model using the asyncio interface, i.e., `annotate_asyncio` and `classify_asyncio`. This is usually substantially faster because data loading is IO-bound while the actual annotation is compute-bound.\n\n- **Manual resampling.** While SeisBench can automatically resample the waveforms, it can be faster to do the resampling manually beforehand. SeisBench uses obspy routines for resampling, which (as of 2023) are not parallelised. Check the required sampling rate with `model.sampling_rate`. Alternative routines are available, e.g., in the Pyrocko library.\n\n## Models Integrated into SeisBench\n\nYou don't have to build models from scratch if you don't want to. SeisBench integrates the following notable models from the literature for you to use. Again, as they inherit from the common SeisBench model interface, all these deep learning models are constructed through PyTorch. Where possible, the original trained weights are imported and made available. These can be accessed via the `from_pretrained` method.\n\n| Integrated Model | Task |\n|------------------|------|\n| `BasicPhaseAE` | Phase Picking |\n| `CRED` | Earthquake Detection |\n| `DPP` | Phase Picking |\n| `DepthPhaseNet` | Depth estimation from depth phases |\n| `DepthPhaseTEAM` | Depth estimation from depth phases |\n| `DeepDenoiser` | Denoising |\n| `SeisDAE` | Denoising |\n| `EQTransformer` | Earthquake Detection\u002FPhase Picking |\n| `GPD` | Phase Picking |\n| `LFEDetect` | Phase Picking (Low-frequency earthquakes) |\n| `OBSTransformer` | Earthquake Detection\u002FPhase Picking |\n| `PhaseNet` | Phase Picking |\n| `PhaseNetLight` | Phase Picking |\n| `PickBlue` | Earthquake Detection\u002FPhase Picking |\n| `Skynet` | Phase Picking |\n| `VariableLengthPhaseNet` | Phase Picking |\n\nCurrently integrated models are capable of earthquake detection and phase picking, waveform denoising, depth estimation, and low-frequency earthquake phase picking. Furthermore, with SeisBench you can build ML models to perform general seismic tasks such as magnitude and source parameter estimation, hypocentre determination etc.\n\n## Best Practices\n- If the waveform data happen to be extremely small in scale (`\u003C=1e-10`), there might be risk of numerical instability. It is acceptable to increase the value first (by multiplying a large number like `1e10`) before normalization or passing to the model.\n\n- Although the seisbench model API will normalize the waveform for you, it is still highly suggested to apply normalization yourself. Since seisbench's normalization scheme uses an epsilon `(waveform - mean(waveform)) \u002F (std(waveform) + epsilon)`, for extremely small values (such as `\u003C=1e-10`), their normalization can destroy the signals in the waveform.\n\n- The seisbench model API can process a stream of waveform data of arbitrary length. Hence, it is not necessary to segment the data yourself. In addition, you should not assume a stream of waveform can only contain one P-wave and one S-wave. It is the best to treat the stream like what it is: a stream of continuous data.\n\n\n\n## End-to-End Workflow for Custom NPZ Phase Picking\n\nFor each input NPZ, validate the required fields before invoking SeisBench and preserve the original sample coordinate system:\n\n```python\nimport numpy as np\n\n\ndef load_npz(path):\n    with np.load(path, allow_pickle=False) as z:\n        missing = {\"data\", \"dt\", \"channels\"} - set(z.files)\n        if missing:\n            raise ValueError(f\"{path}: missing {sorted(missing)}\")\n        x = np.asarray(z[\"data\"])\n        dt = float(np.asarray(z[\"dt\"]).reshape(()))\n        raw = np.asarray(z[\"channels\"]).reshape(()).item()\n        channels = [s.strip() for s in str(raw).split(\",\") if s.strip()]\n    if x.ndim != 2 or len(channels) != 3 or not np.isfinite(dt) or dt \u003C= 0:\n        raise ValueError(f\"{path}: expected finite 2-D three-component data and dt>0\")\n    if x.shape[1] == len(channels):\n        x = x.astype(np.float32, copy=False)       # samples x components\n    elif x.shape[0] == len(channels):\n        x = x.T.astype(np.float32, copy=False)\n    else:\n        raise ValueError(f\"{path}: data shape {x.shape} disagrees with channels\")\n    if not np.isfinite(x).all():\n        raise ValueError(f\"{path}: waveform contains NaN or infinity\")\n    return x, dt, channels\n```\n\nDo not silently guess an orientation, duplicate component, or invalid metadata; skip the file with a diagnostic or use the documented fallback. Keep `n_samples`, `dt`, and every preprocessing\u002Fwindow offset so a model time can later be converted back to the untrimmed source index.\n\n\n\n## Build and Verify the SeisBench Input Stream\n\nConstruct aligned ObsPy traces using the file-specific sampling rate. Channel labels must drive the component mapping; never assume that the columns are Z,N,E. A common three-component mapping is a code ending in `Z` for vertical and codes ending in `N`\u002F`1` and `E`\u002F`2` for horizontals, but reject ambiguous or duplicate mappings rather than inventing one.\n\n```python\nfrom obspy import Stream, Trace, UTCDateTime\n\n\ndef make_stream(x, dt, channels):\n    start = UTCDateTime(0)  # relative origin when the file has no acquisition time\n    return Stream([\n        Trace(data=x[:, j].copy(), header={\n            \"channel\": ch,\n            \"starttime\": start,\n            \"sampling_rate\": 1.0 \u002F dt,\n        }) for j, ch in enumerate(channels)\n    ])\n\n\ndef component_map(channels):\n    groups = {}\n    for j, ch in enumerate(channels):\n        c = ch.upper().split(\".\")[-1]\n        suffix = c[-1:] if c else \"\"\n        groups.setdefault(suffix, []).append(j)\n    z = [j for j, ch in enumerate(channels) if ch.upper().split(\".\")[-1].endswith(\"Z\")]\n    h1 = [j for j, ch in enumerate(channels) if ch.upper().split(\".\")[-1].endswith((\"N\", \"1\"))]\n    h2 = [j for j, ch in enumerate(channels) if ch.upper().split(\".\")[-1].endswith((\"E\", \"2\"))]\n    if len(z) != 1 or len(h1) != 1 or len(h2) != 1 or len({z[0], h1[0], h2[0]}) != 3:\n        raise ValueError(f\"unsupported or ambiguous component layout: {channels}\")\n    return {\"Z\": z[0], \"H1\": h1[0], \"H2\": h2[0]}\n```\n\nBefore inference, inspect the installed model rather than assuming one release's API: use `getattr(model, \"sampling_rate\", None)` and any documented channel\u002Fcomponent metadata. If the model has a required sampling rate, resample a copy only when necessary and map the resulting pick time back using elapsed seconds and the original `dt`. Confirm that the selected pretrained model accepts three components and that its expected order is satisfied; otherwise choose a compatible model or use the fallback. `UTCDateTime(0)` is only a relative bookkeeping origin, not a fabricated acquisition timestamp.\n\n\n\n## CPU-Conscious, Version-Aware Inference and Pick Extraction\n\nModel downloads are optional: try a locally cached or explicitly selected pretrained model, catch download\u002Fload errors, and do not make network access a prerequisite. Run on CPU by default (`model.to(\"cpu\")` when supported), use `batch_size=1` or a small batch, and avoid assuming CUDA. For long records, infer overlapping windows and retain each window's source start sample. SeisBench can batch arbitrary streams, but explicit windows make memory use and coordinate conversion clear.\n\n```python\nimport inspect\nimport numpy as np\n\n\ndef call_api(model, stream):\n    # Signatures and return structures vary by SeisBench version.\n    try:\n        return model.classify(stream)\n    except (AttributeError, TypeError, NotImplementedError):\n        return model.annotate(stream)\n\n\ndef output_arrays(out):\n    \"\"\"Return (time arrays, P arrays, S arrays) for common annotation forms.\"\"\"\n    if out is None:\n        return None\n    if hasattr(out, \"traces\"):  # ObsPy Stream annotations\n        vals = {}\n        for tr in out:\n            name = tr.stats.channel.upper()\n            vals[name] = np.asarray(tr.data, dtype=float)\n        p = next((v for k, v in vals.items() if \"P\" in k), None)\n        s = next((v for k, v in vals.items() if \"S\" in k), None)\n        return p, s\n    if isinstance(out, dict):\n        p = out.get(\"P\", out.get(\"p\", out.get(\"P_probability\")))\n        s = out.get(\"S\", out.get(\"s\", out.get(\"S_probability\")))\n        return (None if p is None else np.asarray(p, float),\n                None if s is None else np.asarray(s, float))\n    return None\n```\n\nWhen `classify` returns discrete picks, inspect each pick's phase and time fields rather than treating the object as an annotation curve. When `annotate` returns curves, locate P\u002FS channels by their labels, reject empty, nonfinite, or all-zero outputs, and use `scipy.signal.find_peaks` (or a documented equivalent) with a phase-specific height\u002Fprominence and minimum-distance threshold. A probability peak's time may be represented by `trace.stats.starttime + i \u002F sampling_rate`; convert it to the source index with `round((pick_time - source_starttime) \u002F original_dt)`. For a window beginning at source sample `w0`, use `w0 + round(local_time \u002F original_dt)`, not merely the local peak index. Clip neither silently nor out of bounds: reject indices outside `[0, n_samples)` and retain confidence for diagnostics. Merge overlapping-window duplicates by phase and time, keeping the highest-confidence candidate.\n\n\n\n## Failure Handling and Classical Fallback\n\nTreat model failure as an expected operational case: catch pretrained-weight download errors, incompatible channel layouts, unsupported sampling rates, runtime\u002FOOM errors, malformed or empty `annotate`\u002F`classify` results, and absent P\u002FS outputs. Do not fabricate picks from a failed model. A CPU-only environment is normal; reduce window length\u002Fbatch size before abandoning inference.\n\nIf no usable model output is available, run a deterministic NumPy\u002FObsPy fallback on the validated original-rate array. Detrend or normalize copies without changing the sample grid; use vertical energy\u002Fonset or STA\u002FLTA for P and delayed horizontal energy\u002Fenvelope or STA\u002FLTA for S. Estimate noise from an early or robust low-amplitude region, require finite positive SNR\u002Fprominence, and allow no pick when evidence is insufficient. This fallback is a candidate generator, not a guarantee of a phase, and must return source indices directly. Do not force P-before-S or invent a missing phase.\n\nFinally write `\u002Froot\u002Fresults.csv` with exactly `file_name,phase,pick_idx`. Validate each row before writing: phase is exactly `P` or `S`, `pick_idx` is an integer in `[0, n_samples)`, and the filename is the actual input filename. Deduplicate identical phase\u002Findex rows, permit multiple or zero picks per file, and log skipped files and fallback use separately from the CSV.\n",{"name":5,"description":7},"main","cdcb6d230f3b15c3c33f8a2bdd16439f43602cbe","evaluation\u002Fresults\u002FSkillOpt-adapted-gpt52-n3L4R2-v25\u002Ftasks\u002Fseismic-phase-picking\u002Frepaired_skill\u002Fseisbench-model-api",1,"https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark","https:\u002F\u002Fgithub.com\u002Flinyouxue","2026-11-14 20:28:35",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add linyouxue\u002Fskill-repair-benchmark --skill seisbench-model-api",{"tool":37,"command":38},"bunx","bunx skills add linyouxue\u002Fskill-repair-benchmark --skill seisbench-model-api",{"tool":40,"command":41},"pnpm","pnpm dlx skills add linyouxue\u002Fskill-repair-benchmark --skill seisbench-model-api","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002FSkillOpt-adapted-gpt52-n3L4R2-v25\u002Ftasks\u002Fseismic-phase-picking\u002Frepaired_skill\u002Fseisbench-model-api\u002FSKILL.md",true,[],[46,53,60,67,72,77],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M7E1HGVRY73NBJ022CJG13X6","video-frame-extraction","Extract frames from video files and save them as images using OpenCV","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7E1HAG5R7CJ9C8NYJS771MB","openai-vision","Analyze images and multi-frame sequences using OpenAI GPT vision models","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7E1H7DADKB6QBWKC2KQ63SZ","image-ocr","Extract text content from images using Tesseract OCR via Python, including structured field extraction from receipts and forms","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[],{"skillNo":68,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7E1H0WBNT43TENGQY7AVZHD","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":73,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7E1GTC7D4N4Q2EF03875J9E","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":78,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7E1GQ92CWFMGH53KSSE4WER","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[]]