detex package¶
Submodules¶
detex.construct module¶
Created on Thu Oct 29 18:39:50 2015
@author: derrick
-
detex.construct.createCluster(CCreq=0.5, fetch_arg=u'EventWaveForms', filt=[1, 10, 2, True], stationKey=u'StationKey.csv', templateKey=u'TemplateKey.csv', trim=[10, 120], saveclust=True, fileName=u'clust.pkl', decimate=None, dtype=u'double', eventsOnAllStations=False, enforceOrigin=False, fillZeros=False, phases=None)[source]¶ Function to create an instance of the ClusterStream class
Parameters: - CCreq (float, between 0 and 1) – The minimum correlation coefficient for grouping waveforms. 0.0 results in all waveforms grouping together and 1.0 will not form any groups.
- fetch_arg (str or detex.getdata.DataFetcher instance) – Fetch_arg of detex.getdata.quickFetch, see docs for details.
- filt (list) – A list of the required input parameters for the obspy bandpass filter [freqmin, freqmax, corners, zerophase].
- stationKey (str or pd.DataFrame) – Path to the station key or DataFrame of station key.
- templateKey (str or pd.DataFrame) – Path to the template key or loaded template key in DataFrame.
- trim (list) – A list with seconds to trim from events with respect to the origin time reported in the template key (or optionally a first arivial time, see phases param for details). The default value of [10, 120] means each event will be trimmed to only contain 10 seconds before its origin time and 120 seconds after. The larger the values of this argument the longer the computation time and chance of misalignment, but values that are too small may trim out desired phases of the waveform.
- saveClust (bool) – If true save the cluster object in the current working directory. The name is controlled by the fileName parameter.
- fileName (str) – Path (or name) to save the clustering instance, only used if saveClust is True.
- decimate (int or None) – A decimation factor to apply to all data in order to decrease run time. Can be very useful if the the data are oversampled. For example, if the data are sampled at 200 Hz but a 1 to 10 Hz bandpass filter is applied it may be appropriate to apply a decimation factor of 5 to bring the sampling rate down to 40 hz.
- dytpe (str) –
- An option to recast data type of the seismic data. Options are:
- double- numpy float 64 single- numpy float 32, much faster and amenable to cuda GPU processing, sacrifices precision.
- eventsOnAllStations (bool) – If True only use the events that occur on all stations, if false let each station have an independent event list.
- enforceOrigin (bool) – If True make sure each trace starts at the reported origin time in the template key. If not trim or merge with zeros. Required for lag times to be meaningful for hypoDD input.
- fillZeros (bool) – If True fill zeros from trim[0] to trim[1]. Suggested for older data or if only triggered data are available.
- phases (None, str, or instance of DataFrame) – If not None a path to phase picks or a DataFrame of phase picks that will be used for trim values rather than referencing the origin time of each event. See issue 25 on detex github page for why this might be useful.
Returns: Return type: An instance of the detex SSClustering class
-
detex.construct.createSubSpace(Pf=1e-12, clust=u'clust.pkl', minEvents=2, dtype=u'double', conDatFetcher=None)[source]¶ Function to create subspaces on all available stations based on the clusters in Clustering object which will either be passed directly as the keyword clust or will be loaded from the path in clustFile
Parameters: - Pf (float) – The probability of false detection as modeled by the statistical framework in Harris 2006 Theory (eq 20, not yet supported) Or by fitting a PDF to an empirical estimation of the null space (similar to Wiechecki-Vergara 2001). Thresholds are not set until calling the SVD function of the subspace stream class.
- clust (str or instance of detex.subspace.ClusterStream) – The path to a pickled instance of ClusterStream or an instance of ClusterStream. Used in defining the subspaces.
- minEvents (int) – The Min number of events that must be in a cluster in order for a subspace to be created from that cluster.
- dtype (str ('single' or 'double')) –
- The data type of the numpy arrays used in the detections. Options are:
- single- a np.float32, slightly faster (~30%) less precise double- a np.float64 (default)
- conDatFetcher (None, str, or instance of detex.getdata.DataFetcher) – Parameter to indicate how continuous data will be fetched in the newly created instance of SubSpace. Descriptions are the three accepted types are: 1. (None) If None is passed detex will try to deduce the appropriate type of DataFetcher from the event datafetcher attached to cluster instance. 2. (str) conDatFetcher is a string it will be passed to detex.getdata.quickFetch function which expects a path to the directory where the data are stored or a valid DataFetcher method. See the docs of the quickFetch function in detex.getdata for more info. 3. (instance of detex.getdata.DataFetcher) If an instance of detex.getdata.DataFetcher is passed then it will be used as the continuous data fetcher.
Returns: - An instance of the SubSpace class – Note
- ———-
- Most of the parameters that define how to fetch seismic data, which events
- and stations to use in the analysis, filter parameters, etc. are already
- defined in the cluster (ClusterStream) instance.
-
detex.construct.multiplex(st, Nc=None, trimTolerance=15, template=False, returnlist=False, retst=False)[source]¶ Multiplex an obspy stream object :param st: The stream containing the data to multiplex. :type st: instance of obspy stream :param Nc: if not None the number of channels in stream, else try to determine :type Nc: None or int :param trimTolerance: The number of samples each channel can vary before being rejected :type trimTolerance: int :param Template: If True st is a template waveform, therefore an exception will be
raised if trimeTolerance is exceededParameters: returnlist (bool) – If true also return np array of un-multiplexed data as a list Returns: Return type: list with multiplexed data and other desired waveforms
detex.getdata module¶
Created on Thu Nov 10 20:21:46 2015
@author: derrick
-
class
detex.getdata.DataFetcher(method, client=None, removeResponse=True, inventoryArg=None, directoryName=None, opType=u'VEL', prefilt=[0.05, 0.1, 15, 20], conDatDuration=3600, conBuff=120, timeBeforeOrigin=60, timeAfterOrigin=240, checkData=True, fillZeros=False)[source]¶ Bases:
objectClass to handle data acquisition
Parameters: - method (str or int) –
One of the approved methods for getting data as supported by detex Options are:
”dir” : A data directory as created by makeDataDirectories “client” : an obspy client can be passed to get data useful if using an in-network database “iris” : an iris client is initiated, also uses IRIS for inventory “uuss” : A client attached to the university of utah seismograph stations is initiated using CWB for waveforms and IRIS is used for station inventories - client (An obspy client object) – Client object used to get data, from obspy.clients
- removeResponse (bool) – If True remove response before returning stream.
- inventoryArg (None, obspy client object, or obspy Inventory object) – A seperate client for station inventories, only used if removeResponse == True, also supports keyword “iris” for iris client
- directoryName (str) – A path to the continuous waveforms directory or event waveforms directory. If None is passed default names are used (ContinuousWaveForms and EventWaveForms)
- opType (str) – Output type after removing instrument response. Choices are: “DISP” (m), “VEL” (m/s), or “ACC” (m/s**2)
- prefilt (list of real numbers) – Pre-filter parameters for removing instrument response.
- conDatDuration (int or float) – Duration for continuous data in seconds
- conBuff (int or float) – The amount of data, in seconds, to download at the end of the conDatDuration. Ideally should be equal to template length, important in order to avoid missing potential events at the end of a stream
- timeBeforeOrigin (int or float) – Seconds before origin of each event to fetch (used in getTemData)
- timeAfterOrigin (int or float) – Seconds after origin of each event to fetch (used in getTemData)
- checkData (bool) – If True apply some data checks before returning streams, can be useful for older data sets.
- fillZeros (bool) – If True fill data that are not available with 0s (provided some data are available)
Methods
getConData(self, stakey[, secBuff, …])Get continuous data defined by the stations and time range in the station key getStream(self, start, end, net, sta[, …])function for getting data. getTemData(self, temkey, stakey[, tb4, …])Take detex station keys and template keys and yield stream objects of all possible combinations -
getConData(self, stakey, secBuff=None, returnName=False, returnTimes=False, conDir=None, skipIfExists=False, utcstart=None, utcend=None, duration=None, randSamps=None)[source]¶ Get continuous data defined by the stations and time range in the station key
Parameters: - stakey (str or pd.DataFrame) – A path to the stationkey or a loaded DF of the stationkey
- secBuff (int) – A buffer in seconds to add to end of continuous data chunk so that consecutive files overlap by secBuf
- returnName (bool) – If True return the name of the file and expected path
- CondDir (str) – Path to Continuous data directory if it exists. Used to check if a file already exists so it can be skipped if skipIfExists
- skipIfExists (bool) – If True files already exists wont be downloaded again
- utcstart (None, int, str or obspy.UTCDateTime instance) – An object readable by obspy.UTCDateTime class which is the start time of continuous data to fetch. If None use time in station key
- utcend (None, int or str, or obspy.UTCDateTime instance) – An object readable by obspy.UTCDateTime class which is the end time of continuous data to fetch. If None use time in station key
- duration (None, int, or float) – The duration of each continuous data chunk to fetch, if None use conDataDuration attribute of DataFetcher instance
- randSamps (None or int) – If not None, return random number of traces rather than whole range
Yields: Obspy trace and other requested parameters
-
getStream(self, start, end, net, sta, chan=u'???', loc=u'??')[source]¶ function for getting data.
Parameters: - start (obspy.UTCDateTime object) – Start time to fetch
- end (obspy.UTCDateTime object) – End time to fetch
- net (str) – Network code, usually 2 letters
- sta (str) – Station code
- chan (str or list of str (should support wildcard)) – Channels to fetch
- loc (str) – Location code for station
Returns: - An instance of obspy.Stream populated with requested data, or None if
- not available.
-
getTemData(self, temkey, stakey, tb4=None, taft=None, returnName=True, temDir=None, skipIfExists=False, skipDict=None, returnTimes=False, phases=None)[source]¶ Take detex station keys and template keys and yield stream objects of all possible combinations
Parameters: - temkey (pd DataFrame) – Detex template key
- stakey (pd DataFrame) – Detex station key
- tb4 (None, or real number) – Time before origin (or first phase pick if phases is not None)
- taft (None or real number) – Time after origin (or first phase pick if phases is not None)
- returnName (bool) – If True return name of event as found in template key
- returnNames (bool) – If True return event names and template names
- temDir (str or None) – Name of template directory, used to check if exists
- skipIfExists (bool) – If True dont return if file is in temDir
- skipDict (dict) – Dictionary of stations (keys, net.sta) and events (values) to skip
- returnTimes (bool) – If True return times of data
- phases (None, str, or DataFrame) – If not None must be a path to a phasePick file, in the same format as detex.util.pickPhases, or a path to a saved csv of the same. tb4 and taft will be referenced to the first arrival for each event and station, or the origin if none are available.
Yields: - Stream objects of possible combination if data are fetchable and event
- names if returnName == True or times of data if returnTimes == True
-
supMethods= [u'dir', u'client', u'uuss', u'iris']¶
- method (str or int) –
-
detex.getdata.getAllData(templateKey=u'TemplateKey.csv', stationKey=u'StationKey.csv', fetch=u'IRIS', formatOut=u'mseed', templateDir=u'EventWaveForms', timeBeforeOrigin=60, timeAfterOrigin=240, conDir=u'ContinuousWaveForms', secBuf=120, conDatDuration=3600, multiPro=False, getContinuous=True, getTemplates=True, removeResponse=True, opType=u'VEL', prefilt=[0.05, 0.1, 15, 20])¶ Function designed to fetch data needed for detex and store them in local directories. StationKey.csv and TemplateKey.csv indicate which events to download and for which stations. Organizes ContinuousWaveForms and EventWaveForms directories.
Parameters: - template_key (str or pd DataFrame) – The path to the TemplateKey csv
- station_key (str or pd DataFrame) – The path to the station key
- fetch (str or FetchData instance) – String for method argument of FetchData class or FetchData instance
- formatOut (str) – Seismic data file format, most obspy formats acceptable, options are: ‘mseed’,’sac’,’GSE2’,’sacxy’,’q’,’sh_asc’,’ slist’, ‘tspair’,’segy’, ‘su’, ‘pickle’, ‘h5’ (h5 only if obspyh5 module installed)
- tempalateDir (str) – The name of the template directory. Using the default is recommended else the templateDir parameter will have to be set in calling most other detex functions
- timeBeforeOrigin (real number) – The time in seconds before the reported origin of each template that is downloaded.
- timeAfterOrigin (real number(int, float, etc.)) – The time in seconds to download after the origin time of each template.
- conDir (str) – The name of the continuous waveform directory. Using the default is recommended
- secBuf (real number (int, float, etc.)) – The number of seconds to download after each hour of continuous data. This might be non-zero in order to capture some detections that would normally be overlooked if data did not overlap somewhat.
- conDatDuration (real number (int, float, etc.)) – The duration of the continuous data to download in seconds.
- multiPro (bool) – If True fork several processes to get data at once, potentially much faster but a bit inconsiderate on the server hosting the data
- getContinuous (bool) – If True fetch continuous data with station and date ranges listed in the station key
- getTemplates (bool) – If True get template data with stations listed in the station key and events listed in the template key
- removeResponse (bool) – If true remove instrument response
- opType (str) – Output type after removing instrument response. Choices are: “DISP” (m), “VEL” (m/s), or “ACC” (m/s**2)
- prefilt (list 4 real numbers) – Pre-filter parameters for removing instrument response, response is flat from corners 2 to 3.
-
detex.getdata.indexDirectory(dirPath)[source]¶ Create an index (.index.db) for a directory with stored waveform files which also contains quality info of each file
Parameters: dirPath (str) – The path to the directory containing waveform data (any structure)
-
detex.getdata.makeDataDirectories(templateKey=u'TemplateKey.csv', stationKey=u'StationKey.csv', fetch=u'IRIS', formatOut=u'mseed', templateDir=u'EventWaveForms', timeBeforeOrigin=60, timeAfterOrigin=240, conDir=u'ContinuousWaveForms', secBuf=120, conDatDuration=3600, multiPro=False, getContinuous=True, getTemplates=True, removeResponse=True, opType=u'VEL', prefilt=[0.05, 0.1, 15, 20])[source]¶ Function designed to fetch data needed for detex and store them in local directories. StationKey.csv and TemplateKey.csv indicate which events to download and for which stations. Organizes ContinuousWaveForms and EventWaveForms directories.
Parameters: - template_key (str or pd DataFrame) – The path to the TemplateKey csv
- station_key (str or pd DataFrame) – The path to the station key
- fetch (str or FetchData instance) – String for method argument of FetchData class or FetchData instance
- formatOut (str) – Seismic data file format, most obspy formats acceptable, options are: ‘mseed’,’sac’,’GSE2’,’sacxy’,’q’,’sh_asc’,’ slist’, ‘tspair’,’segy’, ‘su’, ‘pickle’, ‘h5’ (h5 only if obspyh5 module installed)
- tempalateDir (str) – The name of the template directory. Using the default is recommended else the templateDir parameter will have to be set in calling most other detex functions
- timeBeforeOrigin (real number) – The time in seconds before the reported origin of each template that is downloaded.
- timeAfterOrigin (real number(int, float, etc.)) – The time in seconds to download after the origin time of each template.
- conDir (str) – The name of the continuous waveform directory. Using the default is recommended
- secBuf (real number (int, float, etc.)) – The number of seconds to download after each hour of continuous data. This might be non-zero in order to capture some detections that would normally be overlooked if data did not overlap somewhat.
- conDatDuration (real number (int, float, etc.)) – The duration of the continuous data to download in seconds.
- multiPro (bool) – If True fork several processes to get data at once, potentially much faster but a bit inconsiderate on the server hosting the data
- getContinuous (bool) – If True fetch continuous data with station and date ranges listed in the station key
- getTemplates (bool) – If True get template data with stations listed in the station key and events listed in the template key
- removeResponse (bool) – If true remove instrument response
- opType (str) – Output type after removing instrument response. Choices are: “DISP” (m), “VEL” (m/s), or “ACC” (m/s**2)
- prefilt (list 4 real numbers) – Pre-filter parameters for removing instrument response, response is flat from corners 2 to 3.
-
detex.getdata.quickFetch(fetch_arg, **kwargs)[source]¶ Instantiate a DataFetcher using as little information as possible.
Parameters: - fetch_arg (str or DataFetcher instance) – fetch_arg can be one of three things: 1. An instance of DataFetcher 2. A valid DataFetcher Method other than dir 3. A path to a directory containing waveform data fetch_arg is checked in that order, so if you are trying to use a data directory make sure it does not share names with a valid DataFetcher method
- are passed to the DataFetcher class, see DataFetcher (kwargs) –
- for details (docs) –
Returns: Return type: An instance of DataFetcher
Notes
For client methods (eg ‘uuss’, ‘iris’) remove response is assumed True with the default prelim. filter. If you don’t want this make a custom instance of DataFetcher.
detex.results module¶
Created on Fri May 23 17:55:01 2014
@author: Derrick
-
class
detex.results.SSResults(Dets, Autos, Vers, ss_info, ss_filt, temkey, stakey, templateKey, fetcher)[source]¶ Bases:
objectMethods
writeDetections(self[, onlyVerified, minDS, …])Function to make all of the eligable new detections templates. -
writeDetections(self, onlyVerified=None, minDS=None, minMag=None, eventDir=u'EventWaveForms', updateTemKey=True, temkeyPath=None, timeBeforeOrigin=60, timeAfterOrigin=240, waveFormat=u'mseed')[source]¶ Function to make all of the eligable new detections templates. New event directories will be added to eventDir and the template key will be updated with detected events having a lower case “d” before the name
Parameters: - onlyVerified (boolean) – If true only use detections that are verified
- minDS (None or float between 0.0 and 1.0) – If float only use detections with average detection statistics above minDSave
- minMag (false or float) – If float only use detections with estimated magnitudes above minMag
- eventDir (None or str) – If None new waveforms of detections are stored in default event directory (usually EventWaveForms). If str then the str must be path to new directory in which detected event waveforms will be stored. If it does not exist it will be created
- updateTemKey (boolean) – If true update the template key with the new detections
- temkeyPath (None or str) – if None use the default path to the template key, else new path to templatekey, if it does not exist it will be created
- timeBeforeOrigin (real number (float or int)) – Seconds before predicted origin to get (default is the same as the getData.getAllData defaults)
- timeAfterOrigin (real number (float or int)) – Seconds after predicted origin to get
- = str (waveFormat) – Format to save files, “mseed”, “pickle”, “sac”, and “Q” supported
-
-
detex.results.detResults(trigCon=0, trigParameter=0, associateReq=0, ss_associateBuffer=1, sg_associateBuffer=2.5, requiredNumStations=4, veriBuffer=1, ssDB=u'SubSpace.db', templateKey=u'TemplateKey.csv', stationKey=u'StationKey.csv', veriFile=None, includeAllVeriColumns=True, reduceDets=True, Pf=False, stations=None, starttime=None, endtime=None, fetch=u'ContinuousWaveForms', exceptionalThreshold=None)[source]¶ Function to create an instance of the CorResults class. Used to associate detections across multiple stations into coherent events. CorResults class also has some useful methods for creating input files for location programs such as hypoDD and hypoInverse
Parameters: - trigCon (int 0 or 1) – trigCon is used for filtering the events in the corDB. Currently only options are 0, raw detection statistic value or 1, STA/LTA value of DS as reported in the corDB. This parameter might be useful if there are a large number of detections in corDB with low STA/LTA or correlation coeficient values.
- trigParameter (number) – if trigCon==0 trigParameter is the minimum correlation for a detection to be loaded from the CorDB if trigCon==1 trigParameter is the minimum STA/LTA value for a detection to be loaded from the CorDB. Regardless of trigCon if trigParameter == 0 all detections in CorDB will be loaded and processed
- associateReq (int) – The association requirement which is the minimum number of events that must be shared by subspaces in order to permit event association. For example, subspace 0 (SS0) on station 1 was created using events A,B,C. subspace 0 (SS0) on station 2 was created using events C, D. If both subspace share a detection and associateReq=0 or 1 the detections will be associated into a coherent event. If assiciateReq == 2, however, the detections will not be associated.
- ss_associateBuffer (real number (int or float)) – The buffertime applied to subspace event assocaition in seconds
- sg_associateBuffer (real number (int or float)) – The buffertime applied to singleton event assocaition in seconds
- requiredNumStations (int) – The required number of a stations on which a detection must occur in order to be classified as an event
- veriBuffer (real number (int, float)) – Same as associate buffer but for associating detections with events in the verification file
- ssDB (str) – Path the the database created by detex.xcorr.correlate function
- templateKey (str) – Path to the template key
- stationKey (str) – Path to template key
- veriFile (None (not used) or str (optional)) – Path to a file in the TemplateKey format for verifying the detection by origin time association. veriFile can either be an sqlite database with table name ‘verify’, a CSV, or a pickled pandas dataframe. The following fields must be present: ‘TIME’,’NAME’,’LAT’,’LON’,’MAG’. Any additional columns may be present with any name that will be included in the verification dataframe depending on includeAllVeriColumns
- includeAllVeriColumns (bool) – If true include all columns that are in the veriFile in the verify dataframe that will be part of the SSResults object.
- reduceDets (bool) – If true loop over each station and delete detections of the same event that don’t have the highest detection Stat value. It is recommended this be left as True unless there a specific reason lower DS detections are wanted
- Pf (float or False) – The probability of false detection accepted. Uses the pickled subspace object to get teh FAS class and corresponding fitted beta in order to only keep detections with thresholds above some Pf, defiend for each subspace station pair. If used values of 10**-8 and greater generally work well
- stations (list of str or None) – If not None, a list or tuple of stations to be used in the associations. All others will be discarded
- starttime (None or obspy.UTCDateTime readable object) – If not None, then sets a lower bound on the MSTAMPmin column loaded from the dataframe
- endtime (None or obspy.UTCDateTime readable object) – If not None, then sets a lower bound on the MSTAMPmin column loaded from the dataframe
- fetch (str or instance of detex.getdata.DataFetcher) – Used to determine where to get waveforms, fed into detex.getdata.quickfetch
- exceptionalThreshold (None, float, or dict) – If float the threshold required for a detection to be considered legit regardless of the number of stations. Can also be a dict where the keys are the stations (net.station) and the values are the thresholds to consider exceptional for that station.
detex.subspace module¶
Created on Tue Jul 08 21:24:18 2014
@author: Derrick Module containing import detex classes
-
class
detex.subspace.Cluster(clustStream, station, temkey, eventList, link, ccReq, filt, decimate, trim, DFcc)[source]¶ Bases:
objectMethods
dendro(self[, hideEventLabels, show, …])Function to plot dendrograms of the clusters plotEvents(self[, projection, plotSingles])Plot the event locations for each station using basemap. simMatrix(self[, groupClusts, savename, …])Function to create basic similarity matrix of the values in the cluster object updateReqCC(self, newccReq)Function to update the required correlation coeficient for this station :param newccReq: Required correlation coef :type newccReq: float (between 0 and 1) printAtr write -
dendro(self, hideEventLabels=True, show=True, saveName=False, legend=True, **kwargs)[source]¶ Function to plot dendrograms of the clusters
Parameters: - hideEventLabels (bool) – turns x axis labeling on/off. Better set to false if many events are in event pool
- show (bool) – If true call plt.show
- saveName (str or False) – path to save figure. Extention denotes format. See plt.savefig for details
- legend (bool) – If true plot a legend on the side of the dendrogram
Note
kwargs are passed to scipy.cluster.hierarchy.dendrogram, see docs for acceptable arguments and descriptions
-
plotEvents(self, projection=u'merc', plotSingles=True, **kwargs)[source]¶ Plot the event locations for each station using basemap. Calls the plotEvents method of the Cluster class, see its docs for accepted kwargs.
Parameters: - projection (str) – The pojection type to pass to basemap
- plotSingles (bool) – If True also plot the singletons (events that dont cluster)
Notes
kwargs are passed to basemap If no working installation of basemap is found an ImportError will be raised. See the following URL for tips on installing it: http://matplotlib.org/basemap/users/installing.html, good luck!
-
simMatrix(self, groupClusts=False, savename=False, returnMat=False, **kwargs)[source]¶ Function to create basic similarity matrix of the values in the cluster object
Parameters: - groupClusts (boolean) – If True order by clusters on the simmatrix with the singletons coming last
- savename (str or False) – If not False, a path used by plt.savefig to save the current figure. The extension is necesary for specifying format. See plt.savefig for details
- returnMat (boolean) – If true return the similarity matrix
-
-
class
detex.subspace.ClusterStream(trdf, temkey, stakey, fetcher, eventList, ccReq, filt, decimate, trim, fileName, eventsOnAllStations, enforceOrigin)[source]¶ Bases:
objectA container for multiple cluster objects, should only be called with detex.construct.createCluster
Methods
dendro(self, \*\*kwargs)Create dendrograms for each station plotEvents(self[, projection, plotSingles])Plot the event locations for each station using basemap. simMatrix(self[, groupClusts, savename, …])Function to create similarity matrix of each event pair updateReqCC(self, reqCC)Updates the required correlation coefficient for clusters to form on all stations or individual stations. write(self)Write instance to file (name is the filename attribute) writeSimpleHypoDDInput(self[, fileName, …])Create a hypoDD cross correlation file (EG dt.cc), assuming the lag times are pure S times (should be true if S amplitude is dominant) printAtr -
plotEvents(self, projection=u'merc', plotSingles=True, **kwargs)[source]¶ Plot the event locations for each station using basemap. Calls the plotEvents method of the Cluster class, see its docs for accepted kwargs.
Parameters: - projection (str) – The pojection type to pass to basemap
- plotSingles (bool) – If True also plot the singletons (events that dont cluster)
Notes
kwargs are passed to basemap
If no working installation of basemap is found an ImportError will be raised. See the following URL for tips on installing it: http://matplotlib.org/basemap/users/installing.html, good luck!
-
simMatrix(self, groupClusts=False, savename=False, returnMat=False, **kwargs)[source]¶ Function to create similarity matrix of each event pair
Parameters: - groupClusts (bool) – If True order by clusters on the simmatrix with the singletons coming last
- savename (str or False) – If not False, a path used by plt.savefig to save the current figure. The extension is necesary for specifying format. See plt.savefig for details
- returnMat (bool) – If true return the similarity matrix
-
updateReqCC(self, reqCC)[source]¶ Updates the required correlation coefficient for clusters to form on all stations or individual stations. :param reqCC: if reqCC is a float the required correlation coeficient for
clusters to form will be set to reqCC on all stations. If dict keys must be indicies for each cluster object (IE net.sta, sta, or int index) and values are the reqCC for that station.Notes
The Cluster class also have a similar method that can be more intuitive to use, as in the tutorial
-
writeSimpleHypoDDInput(self, fileName=u'dt.cc', coef=1, minCC=0.35)[source]¶ Create a hypoDD cross correlation file (EG dt.cc), assuming the lag times are pure S times (should be true if S amplitude is dominant)
Parameters: - fileName (str) – THe path to the new file to be created
- coef (float or int) – The exponential coeficient to apply to the correlation coeficient when creating file, usefull to downweight lower cc values
-
-
class
detex.subspace.SubSpace(singlesDict, subSpaceDict, cl, dtype, Pf, cfetcher)[source]¶ Bases:
objectClass used to hold subspaces for detector Holds both subspaces (as defined from the SScluster object) and single event clusters, or singles
Methods
SVD(self[, selectCriteria, selectValue, …])Function to perform SVD on the alligned waveforms and select which of the SVD basis are to be used in event detection. attachPickTimes(self[, pksFile, function, …])Rather than picking times manually attach a file (either csv or pkl of pandas dataframe) with pick times. detex(self[, utcStart, utcEnd, subspaceDB, …])function to run subspace detection over continuous data and store results in SQL database subspaceDB getFAS(self, conDatNum[, LTATime, STATime, …])Function to initialize a FAS (false alarm statistic) instance, used primarily for sampling and characterizing the null space of the subspaces and singletons. pickTimes(self[, duration, traceLimit, …])Calls a modified version of obspyck (https://github.com/megies/obspyck) , a GUI for picking phases, so user can manually select start times (trim) of unclustered and clustered events. plotAlignedEvents(self)Plots the aligned events for each station in each cluster. plotBasisVectors(self[, onlyused])Plots the basis vectors selected after performing the SVD If SVD has not been called will throw error plotFracEnergy(self)Method to plot the fractional energy captured of by the subspace for various dimensions of rep. plotOffsetTimes(self)Function to loop through each station/subspace pair and make histograms of offset times plotThresholds(self, conDatNum[, xlim])Function to sample the continuous data and plot the thresholds calculated with the SVD call with a histogram of detex’s best estimate of the null space (see getFAS for more details) printOffsets(self)Function to print out the offset min max and ranges for each station/subpace pair setSinglesThresholds(self[, conDatNum, …])Set thresholds for the singletons (unclustered events) by fitting a beta distribution to estimation of null space validateClusters(self)Method to check for misaligned waveforms and discard those that no longer meet the required correlation coeficient for each cluster. write(self[, filename])pickle the subspace class :param filename: Path of the file to be created :type filename: str -
SVD(self, selectCriteria=2, selectValue=0.9, conDatNum=100, threshold=None, normalize=False, useSingles=True, validateWaveforms=True, backupThreshold=None, **kwargs)[source]¶ Function to perform SVD on the alligned waveforms and select which of the SVD basis are to be used in event detection. Also assigns a detection threshold to each subspace-station pair.
Parameters: - selctionCriteria (int, selectValue : number) –
selectCriteria is the method for selecting which basis vectors will be used as detectors. selectValue depends on selectCriteria Valid options are:
0 - using the given Pf, find number of dimensions to maximize detection probability !!! NOT YET IMPLIMENTED!!!
selectValue - Not used (Need to find a way to use the doubly-non central F distribution in python)1 - Failed implementation, not supported
2 - select basis number based on an average fractional signal energy captured (see Figure 8 of Harris 2006). Then calculate an empirical distribution of the detection statistic by running each subspace over random continuous data with no high amplitude signals (see getFAS method). A beta distribution is then fit to the data and the DS value that sets the probability of false detection to the Pf defined in the subspace instance is selected as the threshold.
selectValue - Average fractional energy captured, can range from 0 (use no basis vectors) to 1 (use all basis vectors). A value between 0.75 and 0.95 is recommended.3 - select basis number based on an average fractional signal energy captured (see Figure 8 of Harris 2006). Then set detection threshold to a percentage of the minimum fractional energy captured. This method is a bit quick and dirty but ensures all events in the waveform pool will be detected.
select value is a fraction representing the fraction of the minum fractional energy captured (between 0 and 1).4 - use a user defined number of basis vectors, beginning with the most significant (Barrett and Beroza 2014 use first two basis vectors as an “empirical” subspace detector). Then use the same technique in method one to set threshold
selectValue - can range from 0 to number of events in subspace, if selectValue is greater than number of events all events are used - conDatNum (int) – The number of continuous data chunks to use to estimate the effective dimension of the signal space or to estimate the null distribution. Used if selectCriteria == 1,2,4
- threshold (float or None) – Used to set each subspace at a user defined threshold. If any value is set it overrides any of the previously defined methods and avoids estimating the effective dimension of representation or distribution of the null space. Can be useful if problems arise in the false alarm statistic calculation
- normalize (bool) – If true normalize the amplitude of all the training events before preforming the SVD. Keeps higher amplitude events from dominating the SVD vectors but can over emphasize noise. Haris 2006 recomends using normalization but the personal experience of the author has found normalization can increase the detector’s propensity to return false detections.
- useSingles (bool) – If True also calculate the thresholds for singles
- validateWaveforms (bool) – If True call the validateClusters method before the performing SVD to make sure each trimed aligned waveform still meets the required correlation coeficient. Any waveforms that do not will be discarded.
- backupThreshold (None or float) – A backup threshold to use if approximation fails. Typically, using the default detex settings, a reasonable value would be 0.25
- are passed to the getFAS call (if used) (kwargs) –
- selctionCriteria (int, selectValue : number) –
-
attachPickTimes(self, pksFile=u'PhasePicks.csv', function=u'median', defaultDuration=30)[source]¶ Rather than picking times manually attach a file (either csv or pkl of pandas dataframe) with pick times. Pick time file must have the following fields: TimeStamp, Station, Event, Phase. This file can be created by detex.util.pickPhases. If trims are already defined attachPickTimes will not override. ———- pksFile : str
Path to the input file (either csv or pickle)- function : str (‘Average’,’Max’, or ‘Min’)
Describes how to handle selecting a common pick time for subspace groups (each event in a subspace cannot be treated independently as the entire group is aligned to maximize similarity). Does not apply for singles. mean - Trims the group to the sample corresponding to the
average of the first arriving phase- median - Trims the group to the sample corresponding to the
- median of the first arriving phase
max - trim to max value of start times for group min - trim to min value of end times for group
- defaultDuration : int or None
- if Int, the default duration (in seconds) to trim the signal to starting from the first arrival in pksFile for each event or subspace group. If None, then durations are defined by first arriving phase (start) and last arriving phase (stop) for each event
-
detex(self, utcStart=None, utcEnd=None, subspaceDB=u'SubSpace.db', trigCon=0, triggerLTATime=5, triggerSTATime=0, multiprocess=False, delOldCorrs=True, calcHist=True, useSubSpaces=True, useSingles=False, estimateMags=True, classifyEvents=None, eventCorFile=u'EventCors', utcSaves=None, fillZeros=False)[source]¶ function to run subspace detection over continuous data and store results in SQL database subspaceDB
Parameters: - utcStart (str or num) – An obspy.core.UTCDateTime readable object defining the start time of the correlations if not all avaliable data are to be used
- utcEnd (str num) – An obspy.core.UTCDateTime readable object defining the end time of the correlations
- subspaceDB (str) – Path to the SQLite database to store detections in. If it already exists delOldCorrs parameters governs if it will be deleted before running new detections, or appended to.
- is the condition for which detections should trigger. (trigCon) –
- Once the condition is set the variable minCoef is used:
- 0 is based on the detection statistic threshold 1 is based on the STA/LTA of the detection statistic threshold (Only 0 is currently supported)
- triggerLTATime (number) – The long term average for the STA/LTA calculations in seconds.
- triggerSTATime (number) – The short term average for the STA/LTA calculations in seconds. If ==0 then one sample is used.
- multiprocess (bool) – Determine if each station should be forked into its own process for potential speed ups. Currently not implemented.
- delOldCorrs (bool) – Determines if subspaceDB should be deleted before performing detections. If False old database is appended to.
- calcHist (boolean) – If True calculates the histagram for every point of the detection statistic vectors (all hours, stations and subspaces) by keeping a a cumulative bin count. Only slows the detections down slightly and can be useful for threshold sanity checks. The histograms are then returned to the main DataFrame in the SubSpace instance as the column histSubSpaces, and saved in the subspaceDB under the ss_hist and sg_hists tables for subspacs and singletons.
- useSubspace (bool) – If True the subspaces will be used as detectors to scan continuous data
- useSingles (bool) – If True the singles (events that did not cluster) will be used as detectors to scan continuous data
- estimateMags (bool) – If True, magnitudes will be estimated for each detection by using two methods. The first is using standard deviation ratios, and the second uses projected energy ratios (see chambers et al. 2015 for details).
- classifyEvents (None, str, or DataFrame) – If None subspace detectors will be run over continuous data. Else, detex will be run over event waveforms in order to classify events into groups bassed on which subspace they are most similar to. In the latter case the classifyEvents argument must be a str (path to template key like csv) or DataFrame (loaded template key file). The same event DataFetcher attached to the cluster object will be used to get the data. This feature is Experimental.
- eventCorFile (str) – A path to a new pickled DataFrame created when the eventDir option is used. Records the highest detection statistic in the file for each event, station, and subspace. Useful when trying to characterize events.
- utcSaves (None or list of obspy DateTime readable objects) – Either none (not used) or an iterrable of objects readable by obspy.UTCDateTime. When the detections are run if the continous data cover a time indicated in UTCSaves then the continuous data and detection statistic vectors,are saved to a pickled dataframe of the name “UTCsaves.pkl”. This can be useful for debugging, or extracting the DS vector for a time of interest.
- fillZeros (bool) – If true fill the gaps in continuous data with 0s. If True STA/LTA of detection statistic cannot be calculated in order to avoid dividing by 0.
Notes
The same filter and decimation parameters that were used in the ClusterStream instance will be applied.
-
getFAS(self, conDatNum, LTATime=5, STATime=0.5, staltalimit=8.0, useSubSpaces=True, useSingles=False, numBins=401, recalc=False, **kwargs)[source]¶ Function to initialize a FAS (false alarm statistic) instance, used primarily for sampling and characterizing the null space of the subspaces and singletons. Random samples of the continuous data are loaded, examined for high amplitude signals with a basic STA/LTA method, and any traces with STA/LTA ratios higher than the staltalimit parameter are rejected. The continuous DataFetcher already attached to the SubSpace instance will be used to get the continuous data. :param ConDatNum: The number of continuous data files (by default in hour chunks)
to use.Parameters: - LTATime (float) – The long term average time window in seconds used for checking continuous data
- STATime (float) – The short term average time window in seconds for checking continuous data
- staltalimit (int or float) – The value at which continuous data gets rejected as too noisey (IE transient signals are present)
- useSubSpaces (bool) – If True calculate FAS for subspaces
- useSingles (bool) – If True calculate FAS for singles
- numBins (int) – Number of bins for binning distributions (so distribution can be loaded and plotted later)
Note
The results are stored in a DataFrame for each subspace/singleton under the “FAS” column of the main DataFrame
-
pickTimes(self, duration=30, traceLimit=15, repick=False, subspace=True, singles=True)[source]¶ Calls a modified version of obspyck (https://github.com/megies/obspyck) , a GUI for picking phases, so user can manually select start times (trim) of unclustered and clustered events. Triming down each waveform group to only include event phases, and not pre and post event noise, will significantly decrease the runtime for the subspace detection (called with detex method). Trimming is required for singletons as any singletons without trim times will not be used as detectors). :param duration: the time after the first pick (in seconds) to trim waveforms.
The fact that the streams are multiplexed is taken into account. If None is passed then the last pick will be used as the end time for truncating waveforms.Parameters: - traceLimit (int) – Limits the number of traces that will show up to be manually picked to traceLimit events. Avoids bogging down and/or killing the GUI with too many events.
- repick (boolean) – If true repick times that already have sample trim times, else only pick those that do not.
- subspace (boolean) – If true pick subspaces
- singles (boolean) – If true pick singletons
-
plotAlignedEvents(self)[source]¶ Plots the aligned events for each station in each cluster. Will trim waveforms if trim times (by pickTimes or attachPickTimes) are defined.
-
plotBasisVectors(self, onlyused=False)[source]¶ Plots the basis vectors selected after performing the SVD If SVD has not been called will throw error
Parameters: onlyUsed (bool) – If true only the selected basis vectors will be plotted. See SVD for how detex selects basis vectors. If false all will be plotted (used in blue, unused in red)
-
plotFracEnergy(self)[source]¶ Method to plot the fractional energy captured of by the subspace for various dimensions of rep. Each event is plotted as a grey dotted line, the average as a red solid line, and the chosen degree of rep. is plotted as a solid green vertical line. Similar to Harris 2006 Fig 8
-
plotOffsetTimes(self)[source]¶ Function to loop through each station/subspace pair and make histograms of offset times
-
plotThresholds(self, conDatNum, xlim=[-0.01, 0.5], **kwargs)[source]¶ Function to sample the continuous data and plot the thresholds calculated with the SVD call with a histogram of detex’s best estimate of the null space (see getFAS for more details)
Parameters: - conDatNum (int) – The number of continuous data chunks to use in the sampling, duration of chunks defined in data fetcher
- xlim (list (number, number)) – The x limits on the plot (often it is useful to zoom in around 0)
- are passed to the getFAS call (**kwargs) –
-
printOffsets(self)[source]¶ Function to print out the offset min max and ranges for each station/subpace pair
-
setSinglesThresholds(self, conDatNum=50, recalc=False, threshold=None, backupThreshold=None, **kwargs)[source]¶ Set thresholds for the singletons (unclustered events) by fitting a beta distribution to estimation of null space
Parameters: - condatNum (int) – The number of continuous data chunks to use to fit PDF
- recalc (boolean) – If true recalculate the the False Alarm Statistics
- threshold (None or float between 0 and 1) – If number, don’t call getFAS simply use given threshold
- backupThreshold (None or float) – If approximate a threshold fails then use backupThreshold. If None then raise.
Note
Any singles without pick times will not be used. In this way singles can be rejected
-
detex.util module¶
Created on Thu May 29 16:41:48 2014
@author: Derrick
-
detex.util.EQSearch2TemplateKey(eq=u'eqsrchsum', oname=u'eqTemplateKey.csv')[source]¶ Write a template key from the eqsearch sum file (produced by the University of Utah seismograph stations code EQsearch)
Parameters: - eq (str) – eqsearch sum. file
- oname (str) – name of the template key
Notes
Code assimes any year code above 50 belongs to 1900, and any year code less than 50 belongs to 2000 (since eqsrchsum is not y2k compliant)
-
detex.util.catalog2Templatekey(cat, fileName=None)[source]¶ Function to get build the Detex required file TemplateKey.csv from an obspy catalog object
Parameters: - catalog (instance of obspy.core.event.Catalog) – The catalog to use in the template key creation
- filename (str or None) – If None no file is saved, if str then path to the template key to save. Default is StationKey.csv.
Returns: - A pandas DataFrame of the template key information found in the
- catalog object
Notes
obspy catalog object docs at: http://docs.obspy.org/packages/autogen/obspy.fdsn.client.Client.get_events .html#obspy.fdsn.client.Client.get_events
-
detex.util.get_number_channels(st)[source]¶ Take an obspy stream and get the number of unique channels in stream (stream must have only one station)
-
detex.util.inventory2StationKey(inv, starttime, endtime, fileName=None)[source]¶ Function to create a station key from an obspy station inventory
Parameters: - inv (an obspy.core.inventory.Inventory instance) – The inventory to use to create the station key, level of inventory must be at least “channel”
- starttime (obspy.UTCDateTime instance) – The start time to be written to station key
- endtime (obspy.UTCDateTime instance) – The end time to be written to the station key
- fileName (None or str) – If str then path to file to save (as csv), default name is StationKey.csv
Returns: Return type: A pandas DataFrame of the station key
-
detex.util.loadClusters(filename=u'clust.pkl')[source]¶ Function that uses pandas.read_pickle to load a pickled cluster (instance of detex.subspace.ClusterStream) :param filename: Path to the saved cluster isntance :type filename: str
Returns: Return type: An instance of detex.subspace.ClusterStream
-
detex.util.loadSQLite(corDB, tableName, sql=None, readExcpetion=False, silent=True, convertNumeric=True)[source]¶ Function to load sqlite database
Parameters: - corDB (str) – Path to the database
- tablename (str) – Table to load from sqlite database
- sql (str) – sql arguments to pass directly to database query
Returns: Return type: A pandas dataframe with loaded table or None if DB or table does not exist
-
detex.util.loadSubSpace(filename=u'subspace.pkl')[source]¶ Function that uses pandas.read_pickle to load a pickled subspace (instance of detex.subspace.SubSpaceStream) :param filename: Path to the saved subspace instance :type filename: str
Returns: Return type: An instance of detex.subspace.SubSpaceStream
-
detex.util.makeHypoInversePhaseFile(phases, evekey, outname, fix=0, usePhases=[u'P'], fixFirstStation=False)[source]¶ Write a hypoinverse phase file used by hypoinverse, format defined on page 113 of the manual for version 1.39, using the phase file created by detex.util.pickPhases. Format for this file is free csv with the following fields: TimeStamp (epoch time in seconds), Station (net.sta), Event (unique event id, usually datestring, must be the same in templatekey), Phase (phase identifier, generally only P or S)
Parameters: - phases (pandas dataframe or path to csv) – Phase input from AssociatePhases script
- evekey (pandas dataframe or csv) – Event info
- outname (str) – File name (path) to write
- fix (int) – if fix==0 nothing is fixed, fix==1 depths are fixed, fix==2 hypocenters fixed, fix==3 hypocenters and origin time fixed
- usePhases (list) – List of phases to use, all other phases will be skipped
- fixFirstStation (bool) – If True do not set any lat, lon, or depth on each terminator line. HypoInverse will then use the first hit station as the starting location with some reasonable depth (a few kilometers)
Note
Assumes the channel to be ZENZ for writing file.
-
detex.util.makeHypoInverseStationFile(stationKey, outname)[source]¶ Make a hypoinverse station file as defined in station data format #2, p. 30 of hyp1.41 user’s manual
Parameters: - stationKey (str or DataFrame) – Path to station key csv or loaded dataframe with required columns
- outname (str) – The file to write
-
detex.util.pickPhases(fetch=u'EventWaveForms', templatekey=u'TemplateKey.csv', stationkey=u'StationKey.csv', pickFile=u'PhasePicks.csv', skipIfExists=True, **kwargs)[source]¶ Uses streamPicks to parse the templates and allow user to manually pick phases for events. Only P,S, Pend, and Send are supported phases under the current GUI, but other phases can be manually input to this format.
Parameters: - EveDir (str) – Input to detex.getdata.quickFetch, defaults to using the default directory structure for
- templatekey (str or pandas DataFrame) – Path to the template key or template key loaded in DataFrame
- stationkey (str or pandas DataFrame) – Path to the station key or station key loaded in DataFrame
- pickFile (str) – Path to newly created csv containing phase times. If the file already exists it will be read so that picks already made do not have to be re-picked
- skipIfExists (bool) – If True skip any events/stations that already have any phase picks
- passed to quickFetch, see detex.getdata.quickFetch for details (kwargs) –
Notes
Required columns are : TimeStamp, Station, Event, Phase Station field is net.sta (eg TA.M17A)
-
detex.util.readHypo2000Sum(sumfile)[source]¶ read a sum file from hyp2000 and return DataFrame with info loaded into, you guessed it, a DataFrame
Parameters: - sumfile (str) – Path to the summary file to read
- a sum file from hyp2000 and return lat, long, depth, mag, and RMS and (Read) –
- as pd dataframe (TSTMP) –
- WARNING (Assumes western hemisphere) –
-
detex.util.readHypo71Sum(sumfile)[source]¶ Read a summary file from hypoinverse in the y2k compliant hypo71 format
Parameters: sumfile (str) – Path the the sum file Returns: Return type: DataFrame populated with sumfile info
-
detex.util.readKey(dfkey, key_type=u'template')[source]¶ Read a template key csv and perform checks for required columns :param dfkey: A path to the template key csv or the DataFrame itself :type dfkey: str or pandas DataFrame :param key_type: “template” for template key or “station” for station key :type key_type: str
Returns: Return type: A pandas DataFrame if required columns exist, else raise Exception
-
detex.util.readLog(logpath=u'detex_log.log')[source]¶ Read the standard detex log into a dataframe. Columns are: Time, Mod, Level, and Msg.
Parameters: logpath (str) – Path the the log file Returns: Return type: DataFrame with log info
-
detex.util.saveSQLite(DF, CorDB, Tablename, silent=True)[source]¶ Basic function to save pandas dataframe to SQL
Parameters: - DF (pandas DataFrame) – The data frame instance to save
- CorDB (str) – Path to the database
- Tablename (str) – Name of the table to which DF will be saved
- silent (bool) – If True will suppress the any messages from database writing
-
detex.util.seeWaveFroms(fetch=u'ContinuousWaveForms', templatekey=u'TemplateKey.csv', outFile=u'PhasePicks.csv')[source]¶ Uses streamPicks to parse the templates and allow user to manually pick phases for events. Only P,S, Pend, and Send are supported phases under the current GUI, but other phases can be manually input to this format.
Parameters: - fetch (str or instance of detex.getdata.DataFetcher) – Input to detex.getdata.quickFetch, defaults to using the default directory structure
- templatekey (str or pandas DataFrame) – Path to the template key or template key loaded in DataFrame
- outFile (str) – Path to newly created csv containing events (in df) as index and stations as columns
- ---------- –
- columns are (Required) –
- field is net.sta (eg TA.M17A) (Station) –
-
detex.util.templateKey2Catalog(temkey=u'TemplateKey.csv', picks=None)[source]¶ Function to convert a templatekey and optionally a phase picks file to an obspy catalog instance
Parameters: - temeky (str, pd.DataFrame) – The standard template key (or path to it)
- picks (str, pd.DataFrame) – A picks file in same format as created by pickPhases
Returns: Return type: An Obspy.Catalog object
-
detex.util.writeHypoDDEventInput(temkey, fileName=u'event.dat')[source]¶ Write a hypoDD event file (event.dat) :param temkey: If str then path to template key, else loaded template key :type temkey: str or pandas DataFrame
-
detex.util.writeHypoDDStationInput(stakey, fileName=u'station.dat', useElevations=True, inFt=False)[source]¶ Write the station input file for hypoDD (station.dat)
Parameters: - stakey (str or DataFrame) – Path to station key or instance of DataFrame with station key loaded
- fileName (str) – Path to the output file
- useElevations (boolean) – If true also print elevations
- inFt (boolean) – If true elevations in station key are in ft, convert to meters
-
detex.util.writeKMLFromDF(DF, outname=u'map.kml')[source]¶ Write a KML file from a pandas data frame with the same format as readSum output
-
detex.util.writeKMLFromEQSearchSum(eqsum=u'eqsrchsum', outname=u'eqsearch.kml')[source]¶ Write a KML from the eqsearch sum file (produced by the University of Utah seismograph stations code EQsearch)
Parameters: - eqsum (str) – eqsearch sum. file
- outname (str) – name of the kml file
Notes
Code assimes any year code above 50 belongs to 1900, and any year code less than 50 belongs to 2000 (since eqsrchsum is not y2k compliant)
-
detex.util.writeKMLFromHypDD(hypreloc=u'hypoDD.reloc', outname=u'hypo.kml')[source]¶ Uses simplekml to create a KML file (used by Google Earth, Google Maps, etc) of the results from hypoDD
-
detex.util.writeKMLFromHypInv(hypout=u'sum2000', outname=u'hypoInv.kml')[source]¶ Uses simplekml to create a KML file (used by Google Earth, Google Maps, etc) of the results from hypoInverse 2000
-
detex.util.writeKMLFromStationKey(df=u'StationKey.csv', outname=u'stations.kml')[source]¶ Write a KML file from a station key
Parameters: - DF (str or pandas Dataframe) – If str then the path to the station key. If dataframe then station key loaded with readKey function with key_type=’template’
- outname (str) – name of the kml file
-
detex.util.writeKMLFromTemplateKey(df=u'TemplateKey.csv', outname=u'templates.kml')[source]¶ Write a KML file from a templateKey
Parameters: - DF (str or pandas Dataframe) – If str then the path to the template key csv. If dataframe then template key loaded with readKey function with key_type=’template’
- outname (str) – path of the kml file
-
detex.util.writePhaseNLL(phases, evekey, NLLoc_dir, useP=True, useS=True)[source]¶ Write a y2k complient phase file used by hypoinverse 2000, format defined on page 113 of the manual for version 1.39 :param phases: Phase input from AssociatePhases script :type phases: pandas dataframe or path to csv :param evekey: Event info :type evekey: pandas dataframe or csv :param outname: File name (path) to write :type outname: str :param useP: If true write P phases :type useP: bool :param useS: If true write S phases :type useS: bool
Module contents¶
deTex: A Python Toolbox for running subspace detections.¶
-
detex.log(name, msg, level=u'info', pri=False, close=False, e=None)[source]¶ Function to log important events as detex runs :param name: should always be set to __name__ from the log call. This will enable
inspect to trace back to where the call initially came from and record it in the logParameters: - msg (str) – A message to log
- level (str) – level of event (info, debug, warning, critical, or error)
- pri (bool) – If true print msg to screen without entire log info
- close (bool) – If true close the logger so the log file can be opened
- e (Exception class or None) – If level == “error” and Exception is raised, e is the type of exception