Usage Examples

Hack to get CSS to work This is a bad hack to get CSS styles to work within the SNL template

In the usage_examples directory in the source code package, there is one example program for each of the languages supported by RSTT.

LanguageFile
C++cpp_example.cc
Cc_example.c
Fortranfortran_example.f90
Javajava_example.java
Pythonpython_example.py

Each example program performs the same set of tasks and is written to be as simple as possible with extensive commenting. These programs are meant to be a starting point from which users may explore the documentation and write their own code.

To view these code examples online, click to expand one of the sections below

C++

// include statements
#include "SlbmInterface.h"  // RSTT library
#include "SLBMException.h"  // RSTT error catching
#include <iostream>         // print to terminal
#include <string>           // strings
#include <cmath>            // math functions and constants

// define some constants for converting between degrees<-->radians
double DEG_PER_RAD = 180.0 / M_PI;
double RAD_PER_DEG = M_PI / 180.0;

// declare namespace (for convenience)
using namespace slbm;

// main program
int main()
{
    // wrap everything in a `try-catch` block
    try
    {
        // declare the relative path to the model file we're going to be using
        string modelPath = "../models/pdu202009Du.geotess";

        // choose an arbitrary phase (Pn, Pg, Sn, or Lg)
        string phase = "Pn";

        // arbitrary source (Meteor Crater, AZ)
        double srcLatDeg =   35.0274;  // latitude (degrees)
        double srcLonDeg = -111.0228;  // longitude (degrees)
        double srcDepKm  =    1.2345;  // depth (km)

        // arbitrary receiver (Albuquerque, NM)
        double rcvLatDeg =   35.1053;  // latitude (degrees)
        double rcvLonDeg = -106.6294;  // longitude (degrees)
        double rcvDepKm  =   -1.6000;  // depth (km)

        // convert lat/lon from degrees to radians
        double srcLatRad = srcLatDeg * RAD_PER_DEG;
        double srcLonRad = srcLonDeg * RAD_PER_DEG;
        double rcvLatRad = rcvLatDeg * RAD_PER_DEG;
        double rcvLonRad = rcvLonDeg * RAD_PER_DEG;

        // instantiate an RSTT object
        SlbmInterface slbm;

        // load the velocity model
        slbm.loadVelocityModel(modelPath);

        // create a great circle from source to the receiver
        slbm.createGreatCircle(phase,
            srcLatRad, srcLonRad, srcDepKm,
            rcvLatRad, rcvLonRad, rcvDepKm);

        // get the distance and travel time from source --> receiver
        double distRad, distDeg, travelTimeSec;  // instantiate variables
        slbm.getDistance(distRad);               // compute distance (rad) and store its value
        slbm.getTravelTime(travelTimeSec);       // compute travel time (sec) and store its value
        distDeg = distRad * DEG_PER_RAD;         // convert radians --> degrees

        // get the travel time uncertainty
        double travelTimeUncertSec,    // path-dependent travel time uncertainty (sec)
               travelTime1DUncertSec;  // old-style 1D travel time uncertainty (sec)
        slbm.getTravelTimeUncertainty(travelTimeUncertSec);      // compute uncertainty
        slbm.getTravelTimeUncertainty1D(travelTime1DUncertSec);  // compute 1D uncertainty

        // print our results
        cout << fixed << setprecision(4) << endl
             << "C++ Example:" << endl
             << "--------------------------------" << endl
             << "Distance:          " << setw(9) << distDeg << " deg" << endl
             << "Travel Time:       " << setw(9) << travelTimeSec << " sec" << endl
             << "Uncertainty:       " << setw(9) << travelTimeUncertSec << " sec" << endl
             << "Uncertainty (1D):  " << setw(9) << travelTime1DUncertSec << " sec" << endl
             << endl;

    }

    // catch possible exceptions
    catch (const SLBMException& e)
    {
        // print the exception
        cout << __FILE__ << ":" << __LINE__ << endl
             << e.emessage << endl;

        // return with error
        cout << "Exited with error code " << 1 << endl;
        return e.ecode;

    }
    catch (const GeoTessException& e)
    {
        // print the exception
        cout << __FILE__ << ":" << __LINE__ << endl
             << e.emessage << endl;

        // return with error
        cout << "Exited with error code " << e.ecode << endl;
        return e.ecode;

    }
    catch (...)
    {
        // print the exception
        cout << __FILE__ << ":" << __LINE__ << endl
             << "ERROR: An unidentified error has occurred." << endl;

        // return with error
        cout << "Exited with error code " << 1 << endl;
        return 1;
    }

    // return successfully
    return 0;

}
C

// include statements
#include "slbm_C_shell.h"  // RSTT C library
#include <stdio.h>         // print to terminal
#include <math.h>          // math functions and constants
#include <stdlib.h>        // needed for exit codes

// define some constants for converting between degrees<-->radians
double DEG_PER_RAD = 180.0 / M_PI;
double RAD_PER_DEG = M_PI / 180.0;


// error catching function
void try(int errorCode)
{
    // if there is an error code (i.e., function returns anything other than 0)
    if (errorCode != 0)
    {
        // initialize a character array to hold error messages
        char errorMsg[1000];

        // get the error message
        slbm_shell_getErrorMessage(errorMsg);

        // print the error message
        printf("ERROR %d:%s\n", errorCode, errorMsg);

        // exit with the error code
        exit(errorCode);

    }

}


// main program
int main()
{
    // declare the relative path to the model file we're going to be using
    char* modelPath = "../models/pdu202009Du.geotess";

    // choose an arbitrary phase (Pn, Pg, Sn, or Lg)
    char* phase = "Pn";

    // arbitrary source (Meteor Crater, AZ)
    double srcLatDeg =   35.0274;  // latitude (degrees)
    double srcLonDeg = -111.0228;  // longitude (degrees)
    double srcDepKm  =    1.2345;  // depth (km)

    // arbitrary receiver (Albuquerque, NM)
    double rcvLatDeg =   35.1053;  // latitude (degrees)
    double rcvLonDeg = -106.6294;  // longitude (degrees)
    double rcvDepKm  =   -1.6000;  // depth (km)

    // convert lat/lon from degrees to radians
    double srcLatRad = srcLatDeg * RAD_PER_DEG;
    double srcLonRad = srcLonDeg * RAD_PER_DEG;
    double rcvLatRad = rcvLatDeg * RAD_PER_DEG;
    double rcvLonRad = rcvLonDeg * RAD_PER_DEG;

    // instantiate an RSTT object
    try(slbm_shell_create());

    // load the velocity model
    try(slbm_shell_loadVelocityModel(modelPath));

    // create a great circle from source to the receiver
    try(slbm_shell_createGreatCircle(phase,
        &srcLatRad, &srcLonRad, &srcDepKm,
        &rcvLatRad, &rcvLonRad, &rcvDepKm));

    // get the distance and travel time from source --> receiver
    double distRad, distDeg, travelTimeSec;         // instantiate variables
    try(slbm_shell_getDistance(&distRad));          // compute distance (rad) and store its value
    try(slbm_shell_getTravelTime(&travelTimeSec));  // compute travel time (sec) and store its value
    distDeg = distRad * DEG_PER_RAD;                // convert radians --> degrees

    // get the travel time uncertainty
    double travelTimeUncertSec,    // path-dependent travel time uncertainty (sec)
           travelTime1DUncertSec;  // old-style 1D travel time uncertainty (sec)
    try(slbm_shell_getTTUncertainty(&travelTimeUncertSec));      // compute uncertainty
    try(slbm_shell_getTTUncertainty1D(&travelTime1DUncertSec));  // compute 1D uncertainty

    // print our results
    printf("\n"
           "C Example:\n"
           "--------------------------------\n"
           "Distance:          %9.4f deg\n"
           "Travel Time:       %9.4f sec\n"
           "Uncertainty:       %9.4f sec\n"
           "Uncertainty (1D):  %9.4f sec\n"
           "\n",
           distDeg, travelTimeSec, travelTimeUncertSec, travelTime1DUncertSec);

    // return successfully
    return 0;

}
Fortran

! module that contains some various useful constants and definitions
module constants

    ! import modern fortran kinds (real32/64, int8/16/32, etc.)
    use, intrinsic :: iso_fortran_env

    ! turn off f77 "feature" forcing counter variables (ijklmn) to be int
    implicit none

    ! define various variable types
    integer, parameter :: SP = real32  ! single-precision floating point
    integer, parameter :: DP = real64  ! double-precision floating point
    integer, parameter :: I1 = int8    !  8 bit (1 byte)  integer
    integer, parameter :: I2 = int16   ! 16 bit (2 bytes) integer
    integer, parameter :: I4 = int32   ! 32 bit (4 bytes) integer

    ! pi
    real(DP), parameter :: PI_DP = 4._DP * atan (1._DP)  ! double-precision

    ! define some constants for converting between degrees<-->radians    
    real(DP), parameter :: DEG_PER_RAD = 180._DP / PI_DP  ! degrees per radian
    real(DP), parameter :: RAD_PER_DEG = PI_DP / 180._DP  ! radians per degree


end module constants

! module that contains useful error checking code
module error_checking

    ! import the useful constants we've defined
    use constants

    ! turn off f77 "feature" forcing counter variables (ijklmn) to be int
    implicit none

    ! subroutine/function block
    contains

    ! error catching function
    subroutine catch(errorCode)

        ! define errorCode as an integer and is an input variable
        integer(I4), intent(in) :: errorCode

        ! declare a character array to hold our error message
        character(len=1024) :: errorMsg

        ! check if there is an error code (if it's not 0 or 1)
        if (errorCode /= 0 .AND. errorCode /= 1) then

            ! get the error message
            call slbm_get_error_message( errorMsg, sizeof(errorMsg) )

            ! print the error message
            print '(a,i0,a)', "ERROR ", errorCode, ":"
            print '(a)', errorMsg

            ! exit the program with error
            stop 1

        endif

    end subroutine catch
    
end module error_checking


! main progran
program main

    ! import statements
    use constants       ! some useful constants we've defined
    use error_checking  ! error checking functions

    ! turn off f77 "feature" forcing counter variables (ijklmn) to be int
    implicit none

    ! declare a whole bunch of variables
    integer(I4)        :: errorCode  ! integer error code
    character(len=80)  :: modelPath  ! /path/to/model_file
    integer(I4)        :: phase      ! phase id
    real(DP) :: srcLatDeg, srcLonDeg, srcDepKm,  &  ! source location
                rcvLatDeg, rcvLonDeg, rcvDepKm      ! receiver location
    real(DP) :: srcLatRad, srcLonRad,  &  ! source location (radians)
                rcvLatRad, rcvLonRad      ! source location (radians)
    real(DP) :: distDeg, distRad,      &  ! source <--> receiver distance
                travelTimeSec,         &  ! travel time (sec) from source --> receiver
                travelTimeUncertSec,   &  ! path-dependent travel time uncertainty (sec)
                travelTime1DUncertSec     ! old-style 1D travel time uncertainty (sec)

    ! declare the relative path to the model file we're going to be using
    modelPath = "../models/pdu202009Du.geotess"

    ! choose an arbitrary phase (Pn=0, Sn=1, Pg=2, or Lg=3)
    phase = 0

    ! arbitrary source (Meteor Crater, AZ)
    srcLatDeg =   35.0274_DP  ! latitude (degrees)
    srcLonDeg = -111.0228_DP  ! longitude (degrees)
    srcDepKm  =    1.2345_DP  ! depth (km)

    ! ! arbitrary receiver (Albuquerque, NM)
    rcvLatDeg =   35.1053_DP  ! latitude (degrees)
    rcvLonDeg = -106.6294_DP  ! longitude (degrees)
    rcvDepKm  =   -1.6000_DP  ! depth (km)

    ! convert lat/lon from degrees to radians
    srcLatRad = srcLatDeg * rad_per_deg
    srcLonRad = srcLonDeg * rad_per_deg
    rcvLatRad = rcvLatDeg * rad_per_deg
    rcvLonRad = rcvLonDeg * rad_per_deg

    ! instantiate an RSTT object
    call slbm_create(errorCode)
    call catch(errorCode)  ! check if the previous function returned an error

    ! load the velocity model
    call slbm_load_velocity_model(trim(modelPath), len_trim(modelPath), errorCode)
    call catch(errorCode)  ! check if the previous function returned an error

    ! create a great circle from source to the receiver
    call slbm_create_great_circle(phase,  &
        srcLatRad, srcLonRad, srcDepKm,   & 
        rcvLatRad, rcvLonRad, rcvDepKm,   &
        errorCode)
    call catch(errorCode)  ! check if the previous function returned an error

    ! get the distance and travel time from source --> receiver
    call slbm_get_distance(distRad, errorCode)           ! compute distance (rad) and store its value
    call catch(errorCode)  ! check if the previous function returned an error
    call slbm_get_travel_time(travelTimeSec, errorCode)  ! compute travel time (sec) and store its value
    call catch(errorCode)  ! check if the previous function returned an error
    distDeg = distRad * DEG_PER_RAD  ! convert radians --> degrees

    ! get the travel time uncertainty
    call slbm_get_tt_uncertainty(travelTimeUncertSec, errorCode)      ! compute uncertainty
    call catch(errorCode)  ! check if the previous function returned an error
    call slbm_get_tt_uncertainty1d(travelTime1DUncertSec, errorCode)  ! compute 1D uncertainty
    call catch(errorCode)  ! check if the previous function returned an error

    ! print our results
    print '(a)', ""
    print '(a)', "Fortran Example:"
    print '(a)', "--------------------------------"
    print '(a,f9.4,a)', "Distance:          ", distDeg, " deg"
    print '(a,f9.4,a)', "Travel Time:       ", travelTimeSec, " sec"
    print '(a,f9.4,a)', "Uncertainty:       ", travelTimeUncertSec, " sec"
    print '(a,f9.4,a)', "Uncertainty (1D):  ", travelTime1DUncertSec, " sec"
    print '(a)', ""

    ! return successfully
    return

end program main
Java

// import statements
import java.io.File;  // file, path, and environment variable stuff
import static java.lang.Math.*;  // mathematics (degrees<-->radians)
import gov.sandia.gnem.slbmjni.SlbmInterface;  // RSTT library
import gov.sandia.gnem.slbmjni.SLBMException;  // RSTT error catching


// main class
public class java_example
{
    // annoyingly long method which will run at startup and try to load slbmjni,
    // first from the system paths, then by searching environment variables
    // ($RSTT_ROOT, $RSTT_HOME, $SLBM_ROOT, $SLBM_HOME). this also has to take
    // into account multiple possible file extensions on MacOS (.dylib, .jnilib)
    static
    {
        // first we'll just try and load the library
        try
        {
            System.loadLibrary("slbmjni");
        }

        // if that didn't work, we'll start checking environmental variables
        catch (java.lang.UnsatisfiedLinkError e)
        {
            // get the filename of the library we're looking for
            String libName = System.mapLibraryName("slbmjni");  // e.g., "libslbmjni.so"
            String libBase = libName.split("\\.")[0];  // file basename
            String libExt  = libName.split("\\.")[1];  // file extension

            // make our list of env vars to search, in preferred order
            String envVars[] = {"RSTT_ROOT", "RSTT_HOME", "SLBM_ROOT", "SLBM_HOME"};

            // initialize a boolean for when the library has loaded. if we have
            // successfully loaded it, we'll end the whole method
            boolean jniLoaded = false;

            // loop through each environment variable and look for slbmjni
            for (String env : envVars)
            {
                // try and get the environment variable
                String rootDir = System.getenv(env);

                // move on if it wasn't set
                if (rootDir == null)
                    continue;

                // first check if libName exists
                if (new File(rootDir + "/lib/" + libBase + "." + libExt).exists())
                    System.load(rootDir + "/lib/" + libBase + "." + libExt);  // load it

                // if that file doesn't exist, look for libslbmjni.jnilib
                else if (new File(rootDir + "/lib/" + libBase + ".jnilib").exists())
                    System.load(rootDir + "/lib/" + libBase + ".jnilib");  // load it

                // if that doesn't exist, we'll move onto the next variable
                else
                    continue;

                // we made it this far, so we must have loaded the library!
                jniLoaded = true;  // set our boolean to true
                break;             // break out of the loop

            }

            // if, we still haven't loaded slbmjni, throw a helpful error message
            if (!jniLoaded)
            {
                // append some helpful info to the error message
                String errMsg = e.getMessage() + " or [$RSTT_ROOT/lib, $RSTT_HOME/lib, $SLBM_ROOT/lib, $SLBM_HOME/lib]";

                // make a new UnsatisfiedLinkError with our updated message
                UnsatisfiedLinkError ex = new UnsatisfiedLinkError(errMsg);

                // print out the stacktrace, some helpful info, and exit
                ex.printStackTrace();
                System.out.println("Did you try adding '-Djava.library.path=\"/path/to/rstt/lib\"' to your 'java' command?");
                System.out.println("Alternatively, set $RSTT_ROOT, $RSTT_HOME, $SLBM_ROOT, or $SLBM_HOME environment variables.");
                System.exit(1);
            }
        }
    }

    // main method
    public static void main(String args[])
    {
        // wrap everything in a `try-catch` block
        try
        {
            // declare the relative path to the model file we're going to be using
            String modelPath = "../models/pdu202009Du.geotess";

            // choose an arbitrary phase (Pn, Pg, Sn, or Lg)
            String phase = "Pn";

            // arbitrary source (Meteor Crater, AZ)
            double srcLatDeg =   35.0274;  // latitude (degrees)
            double srcLonDeg = -111.0228;  // longitude (degrees)
            double srcDepKm  =    1.2345;  // depth (km)

            // arbitrary receiver (Albuquerque, NM)
            double rcvLatDeg =   35.1053;  // latitude (degrees)
            double rcvLonDeg = -106.6294;  // longitude (degrees)
            double rcvDepKm  =   -1.6000;  // depth (km)

            // convert lat/lon from degrees to radians
            double srcLatRad = toRadians(srcLatDeg);
            double srcLonRad = toRadians(srcLonDeg);
            double rcvLatRad = toRadians(rcvLatDeg);
            double rcvLonRad = toRadians(rcvLonDeg);

            // instantiate an RSTT object
            SlbmInterface slbm = new SlbmInterface();

            // load velocity model
            slbm.loadVelocityModel(modelPath);

            // create a great circle from source to the receiver
            slbm.createGreatCircle(phase,
                srcLatRad, srcLonRad, srcDepKm,
                rcvLatRad, rcvLonRad, rcvDepKm);

            // get the distance and travel time from source --> receiver
            double distRad, distDeg, travelTimeSec;  // instantiate variables
            distRad       = slbm.getDistance();      // compute distance (rad) and store its value
            travelTimeSec = slbm.getTravelTime();    // compute travel time (sec) and store its value
            distDeg       = toDegrees(distRad);      // convert radians --> degrees

            // get the travel time uncertainty
            double travelTimeUncertSec,    // path-dependent travel time uncertainty (sec)
                   travelTime1DUncertSec;  // old-style 1D travel time uncertainty (sec)
            travelTimeUncertSec   = slbm.getTravelTimeUncertainty();    // compute uncertainty
            travelTime1DUncertSec = slbm.getTravelTimeUncertainty1D();  // compute 1D uncertainty

            // print our results
            System.out.format("\n");
            System.out.format("Java Example:\n");
            System.out.format("--------------------------------\n");
            System.out.format("Distance:          %9.4f deg\n", distDeg);
            System.out.format("Travel Time:       %9.4f sec\n", travelTimeSec);
            System.out.format("Uncertainty:       %9.4f sec\n", travelTimeUncertSec);
            System.out.format("Uncertainty (1D):  %9.4f sec\n", travelTime1DUncertSec);
            System.out.format("\n");

        }

        // catch possible exceptions
        catch (SLBMException e)
        {
            // print info about the exception and exit
            e.printStackTrace();
            System.exit(1);
        }

        // catch other exceptions
        catch (Exception e)
        {
            // print info about the exception and exit
            e.printStackTrace();
            System.exit(1);
        }

        // return successfully
        System.exit(0);

    }

}
Python

#!/usr/bin/env python3

# first try and import rstt. if that fails, search the environment variables
# for the appropriate path and try and import from there.
try:
    import rstt

# it looks like importing failed. try searching paths from environment variables for the module
except ModuleNotFoundError:
    import os, sys                                                  # import some required modules
    for d in ('RSTT_ROOT', 'RSTT_HOME', 'SLBM_ROOT', 'SLBM_HOME'):  # list of env vars to check, in order
        if os.getenv(d):                                            # if the environmental var is set
            sys.path.append(os.getenv(d) + "/lib")                  # add to the start of the module search path
    
    # try and import rstt again
    try:
        import rstt

    # if it still fails, raise an exception with a helpful error message
    except ModuleNotFoundError as e:
        e.msg += ". Have you set $RSTT_ROOT, $SLBM_ROOT, or installed RSTT with pip?"
        raise e from None


# main program
if __name__ == "__main__":

    # wrap everything in a try-except block
    try:

        # declare the relative path to the model file we're going to be using
        modelPath = "../models/pdu202009Du.geotess"

        # choose an arbitrary phase (Pn, Pg, Sn, or Lg)
        phase = "Pn"

        # arbitrary source (Meteor Crater, AZ)
        srcLatDeg =   35.0274  # latitude (degrees)
        srcLonDeg = -111.0228  # longitude (degrees)
        srcDepKm  =    1.2345  # depth (km)

        # arbitrary receiver (Albuquerque, NM)
        rcvLatDeg =   35.1053  # latitude (degrees)
        rcvLonDeg = -106.6294  # longitude (degrees)
        rcvDepKm  =   -1.6000  # depth (km)

        # convert lat/lon from degrees to radians
        srcLatRad = rstt.deg2rad(srcLatDeg)
        srcLonRad = rstt.deg2rad(srcLonDeg)
        rcvLatRad = rstt.deg2rad(rcvLatDeg)
        rcvLonRad = rstt.deg2rad(rcvLonDeg)

        # instantiate an RSTT object
        slbm = rstt.SlbmInterface()

        # load the velocity model
        slbm.loadVelocityModel(modelPath)

        # create a great circle from source to the receiver
        slbm.createGreatCircle(phase,
            srcLatRad, srcLonRad, srcDepKm,
            rcvLatRad, rcvLonRad, rcvDepKm)

        # get the distance and travel time from source --> receiver
        travelTimeSec = slbm.getTravelTime()   # compute travel time (sec)
        distRad       = slbm.getDistance()     # compute distance (rad)
        distDeg       = rstt.rad2deg(distRad)  # convert radians --> degrees

        # get the travel time uncertainty
        travelTimeUncertSec   = slbm.getTravelTimeUncertainty()    # compute uncertainty
        travelTime1DUncertSec = slbm.getTravelTimeUncertainty1D()  # compute 1D uncertainty

        # print our results
        print(
            "\n" +
            "Python Example\n" +
            "--------------------------------\n" +
            "Distance:            {:7.4f} deg\n".format(distDeg) +
            "Travel Time:         {:7.4f} sec\n".format(travelTimeSec) +
            "Uncertainty:         {:7.4f} sec\n".format(travelTimeUncertSec) +
            "Uncertainty (1D):    {:7.4f} sec\n".format(travelTime1DUncertSec) +
            "\n"
            )

    # catch possible exceptions
    except Exception as e:

        # raise the error we just caught
        raise(e)