Programmatic Access¶
TauP can be used as a library in addition to the command line tools. The web interface provides an alternative for non-JVM languages.
Java¶
As it is written in Java, TauP is most easily used by other Java programs. A very simple Java program to calculate arrival times is below. The general flow is that you start with a VelocityModel and convert to a TauModel, unless using one of the built in TauModels. Then create SeismicPhase objects for each phase of interest from the model. Lastly, use the phase to calculate Arrival objects for a distance.
Javadocs for the package are at available at javadoc.io.
While the TauP jar and its dependencies are included in the distribution, it is often easier to depend on the publication within the Maven Central repository as this facilitates download and updates and provides for automatic dependency resolution when using a build tool like maven or gradle.
Converting the initial model for a source depth is more costly than calculating arrivals at a distance, so it is usually more efficient to process all stations for each earthquake rather than all earthquakes for a station.
package edu.sc.seis.example;
import edu.sc.seis.TauP.*;
import java.io.IOException;
import java.util.List;
public class TimeExample {
public void calcTimes() throws TauPException, IOException {
// A standard model can be loaded by name
TauModel ak135Model = TauModelLoader.load("ak135");
// or a custom velocity model, from a file in current directory, can be
// loaded and then turned into a TauModel
VelocityModel vMod = TauModelLoader.loadVelocityModel("mymodel.nd");
TauModel tMod = TauModelLoader.createTauModel(vMod);
// A seismic phase for a phase name like 'P' can be created for that model
double sourceDepth = 100; // earthquake depth in kilometers
double receiverDepth = 0; // seismometer depth in kilometers if not at the surface
SeismicPhase P_phase = SeismicPhaseFactory.createPhase("P", tMod, sourceDepth);
//
List<Arrival> arrivalList = DistanceRay.ofDegrees(45).calculate(P_phase);
for (Arrival a : arrivalList) {
System.out.println(a.getName()+" "+a.getDistDeg()+" "+a.getTime());
}
}
public static void main(String[] args) throws Exception {
TimeExample ex = new TimeExample();
ex.calcTimes();
}
}
HTTP Access¶
While using Java, or perhaps another language that can run on the JVM, is the most computationally efficient way to access TauP, it does limit the languages available. For other languages, the simplest way is to make use of the built in web access within TauP to access the tools via an HTTP request returning JSON.
Running taup web
in the distribution will start up a web server
on port 7409 to allow this type of access, although only from connections on the
local machine.
An example in Python using the Requests library is below. Each of the normal command line tools are available via this web interface, and almost all command line arguments can be sent via a corresponding URL query parameter by removing leading dashes. For example to calculate the at a distance in kilometers, where the command line tool uses ‘–km 100’, the URL would include ‘km=100’ like:
http://localhost:7409/time?phase=P,S&km=100&format=json
Boolean command line flags, like ‘–amp’, can be given a true value as in ‘amp=true’. Many options have default values, just as in the command line tools. It may be helpful to experiment with the web gui at
http://localhost:7409/taup.html
to see how the URL is encoded and what the results are. Note that the web form does not yet include all possible parameters that the web tools support.
Python¶
A slightly less efficient, but perhaps good enough for most uses is to execute the command line tools within another script, and then parse output of the tool from json. This has the disadvantage that a new subprocess must start for each call to get times, and so can be slower, but has the advantage of access to all of the command line arguments available.
An example that gets travel times via Python show how this could be done.
#!/usr/bin/env python
import subprocess
import json
import sys
def getTauPAsJson(cmd):
"""
Gets results for a TauP command via json. The --json parameter is
automatically appended to the command.
"""
splitCmd = cmd.split(" ")
splitCmd.append("--json")
print(" ".join(splitCmd))
result = subprocess.run(splitCmd, capture_output=True)
result.check_returncode() # will raise CalledProcessError if not ok
out = result.stdout
with open("taup.out", "wb") as f:
f.write(out)
taupjson = json.loads(out)
return taupjson
def taup_time(degrees, phases, sourcedepth=0, model=None, amp=False):
"""
Calculates arrivals for the phases.
Parameters:
-----------
degrees - either a single distance or a list of distances
phases - comma separated list of phases, or list of phases
sourcedepth - optional source depth, defaults to zero
Returns dict parsed from the json containing 'arrivals' with a list of the
Arrival objects.
"""
if isinstance(degrees, list):
deg = ",".join(map(str, degrees))
else:
deg = degrees
if isinstance(phases, list):
ph = ",".join(phases)
else:
ph = phases
cmd = f"taup time --deg {deg} -p {ph} -h {sourcedepth}"
#cmd = f"{TAUP_PATH}/taup time --deg {deg} -p {ph} -h {sourcedepth}"
if model is not None:
cmd += f" --mod {model}"
if amp:
cmd += " --amp"
taupjson = getTauPAsJson(cmd)
return taupjson
def main():
# calculate travel times and parse the output json.
# Note that taup must be on your PATH env var
degrees = 35
depth = 100
phases = "P,S,SKKKS"
taupjson = taup_time(degrees, phases, depth)
print(f"Got {len(taupjson['arrivals'])} arrivals:")
for arr in taupjson["arrivals"]:
print(f" {arr['phase']} arrives at {arr['time']} and traveled {arr['puristdist']} deg.")
return 0
if __name__ == '__main__':
sys.exit(main())
Graalvm and Graalpy¶
It is also possible for python code to interact more directly with TauP’s Java code by using Graalvm and Graalpy. We are considering how best to leverage these tools.