def extract_detections(detections, templates, archive, arc_type,<EOL>extract_len=<NUM_LIT>, outdir=None, extract_Z=True,<EOL>additional_stations=[]):
<EOL>all_delays = []  <EOL>all_stachans = []<EOL>for template in templates:<EOL><INDENT>templatestream = template[<NUM_LIT:1>].sort(['<STR_LIT>'])<EOL>stachans = [(tr.stats.station, tr.stats.channel)<EOL>for tr in templatestream]<EOL>mintime = templatestream[<NUM_LIT:0>].stats.starttime<EOL>delays = [tr.stats.starttime - mintime for tr in templatestream]<EOL>all_delays.append((template[<NUM_LIT:0>], delays))<EOL>all_stachans.append((template[<NUM_LIT:0>], stachans))<EOL><DEDENT>detections.sort(key=lambda d: d.detect_time)<EOL>detection_days = [detection.detect_time.date<EOL>for detection in detections]<EOL>detection_days = list(set(detection_days))<EOL>detection_days.sort()<EOL>detection_days = [UTCDateTime(d) for d in detection_days]<EOL>detection_wavefiles = []<EOL>if extract_Z:<EOL><INDENT>new_all_stachans = []<EOL>new_all_delays = []<EOL>for t, template in enumerate(all_stachans):<EOL><INDENT>stachans = template[<NUM_LIT:1>]<EOL>delays = all_delays[t][<NUM_LIT:1>]<EOL>new_stachans = []<EOL>new_delays = []<EOL>j = <NUM_LIT:0><EOL>for i, stachan in enumerate(stachans):<EOL><INDENT>if j == <NUM_LIT:1>:<EOL><INDENT>new_stachans.append((stachan[<NUM_LIT:0>], stachan[<NUM_LIT:1>][<NUM_LIT:0>] + '<STR_LIT>'))<EOL>new_delays.append(delays[i])<EOL>new_stachans.append(stachan)<EOL>new_delays.append(delays[i])<EOL>j = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>new_stachans.append(stachan)<EOL>new_delays.append(delays[i])<EOL>j += <NUM_LIT:1><EOL><DEDENT><DEDENT>new_all_stachans.append((template[<NUM_LIT:0>], new_stachans))<EOL>new_all_delays.append((template[<NUM_LIT:0>], new_delays))<EOL><DEDENT>all_delays = new_all_delays<EOL>all_stachans = new_all_stachans<EOL><DEDENT>if not len(additional_stations) == <NUM_LIT:0>:<EOL><INDENT>print('<STR_LIT>')<EOL>for t, template in enumerate(all_stachans):<EOL><INDENT>av_delay = np.mean(all_delays[t][<NUM_LIT:1>])<EOL>for sta in additional_stations:<EOL><INDENT>if sta not in template[<NUM_LIT:1>]:<EOL><INDENT>print('<STR_LIT>' + '<STR_LIT:.>'.join(sta))<EOL>template[<NUM_LIT:1>].append(sta)<EOL>all_delays[t][<NUM_LIT:1>].append(av_delay)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>del stachans<EOL>for detection_day in detection_days:<EOL><INDENT>print('<STR_LIT>' + str(detection_day))<EOL>stachans = list(set([stachans[<NUM_LIT:1>] for stachans in all_stachans][<NUM_LIT:0>]))<EOL>st = read_data(archive=archive, arc_type=arc_type, day=detection_day,<EOL>stachans=stachans)<EOL>st.merge(fill_value='<STR_LIT>')<EOL>day_detections = [detection for detection in detections<EOL>if UTCDateTime(detection.detect_time.date) ==<EOL>detection_day]<EOL>del stachans, delays<EOL>for detection in day_detections:<EOL><INDENT>print('<STR_LIT>' +<EOL>detection.detect_time.strftime('<STR_LIT>'))<EOL>detect_wav = st.copy()<EOL>for tr in detect_wav:<EOL><INDENT>t1 = UTCDateTime(detection.detect_time) - extract_len / <NUM_LIT:2><EOL>t2 = UTCDateTime(detection.detect_time) + extract_len / <NUM_LIT:2><EOL>tr.trim(starttime=t1, endtime=t2)<EOL><DEDENT>if outdir:<EOL><INDENT>if not os.path.isdir(os.path.join(outdir,<EOL>detection.template_name)):<EOL><INDENT>os.makedirs(os.path.join(outdir, detection.template_name))<EOL><DEDENT>detect_wav.write(os.path.join(outdir, detection.template_name,<EOL>detection.detect_time.<EOL>strftime('<STR_LIT>') +<EOL>'<STR_LIT>'),<EOL>format='<STR_LIT>')<EOL>print('<STR_LIT>' %<EOL>'<STR_LIT:/>'.join([outdir, detection.template_name,<EOL>detection.detect_time.<EOL>strftime('<STR_LIT>') + '<STR_LIT>']))<EOL><DEDENT>if not outdir:<EOL><INDENT>detection_wavefiles.append(detect_wav)<EOL><DEDENT>del detect_wav<EOL><DEDENT>del st<EOL>if outdir:<EOL><INDENT>detection_wavefiles = []<EOL><DEDENT><DEDENT>if not outdir:<EOL><INDENT>return detection_wavefiles<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>
Extract waveforms associated with detections

   Takes a list of detections for the template, template.  Waveforms will be
   returned as a list of :class:`obspy.core.stream.Stream` containing
   segments of extract_len.  They will also be saved if outdir is set.
   The default is unset.  The  default extract_len is 90 seconds per channel.

   :type detections: list
   :param detections: List of :class:`eqcorrscan.core.match_filter.Detection`.
   :type templates: list
   :param templates:
       A list of tuples of the template name and the template Stream used
       to detect detections.
   :type archive: str
   :param archive:
       Either name of archive or path to continuous data, see
       :func:`eqcorrscan.utils.archive_read` for details
   :type arc_type: str
   :param arc_type: Type of archive, either seishub, FDSN, day_vols
   :type extract_len: float
   :param extract_len:
       Length to extract around the detection (will be equally cut around
       the detection time) in seconds.  Default is 90.0.
   :type outdir: str
   :param outdir:
       Default is None, with None set, no files will be saved,
       if set each detection will be saved into this directory with files
       named according to the detection time, NOT than the waveform
       start time. Detections will be saved into template subdirectories.
       Files written will be multiplexed miniseed files, the encoding will
       be chosen automatically and will likely be float.
   :type extract_Z: bool
   :param extract_Z:
       Set to True to also extract Z channels for detections delays will be
       the same as horizontal channels, only applies if only horizontal
       channels were used in the template.
   :type additional_stations: list
   :param additional_stations:
       List of tuples of (station, channel) to also extract data
       for using an average delay.

   :returns: list of :class:`obspy.core.streams.Stream`
   :rtype: list

   .. rubric: Example

   >>> from eqcorrscan.utils.clustering import extract_detections
   >>> from eqcorrscan.core.match_filter import Detection
   >>> from obspy import read, UTCDateTime
   >>> # Get the path to the test data
   >>> import eqcorrscan
   >>> import os
   >>> TEST_PATH = os.path.dirname(eqcorrscan.__file__) + '/tests/test_data'
   >>> # Use some dummy detections, you would use real one
   >>> detections = [Detection(
   ...     template_name='temp1', detect_time=UTCDateTime(2012, 3, 26, 9, 15),
   ...     no_chans=2, chans=['WHYM', 'EORO'], detect_val=2, threshold=1.2,
   ...     typeofdet='corr', threshold_type='MAD', threshold_input=8.0),
   ...               Detection(
   ...     template_name='temp2', detect_time=UTCDateTime(2012, 3, 26, 18, 5),
   ...     no_chans=2, chans=['WHYM', 'EORO'], detect_val=2, threshold=1.2,
   ...     typeofdet='corr', threshold_type='MAD', threshold_input=8.0)]
   >>> archive = os.path.join(TEST_PATH, 'day_vols')
   >>> template_files = [os.path.join(TEST_PATH, 'temp1.ms'),
   ...                   os.path.join(TEST_PATH, 'temp2.ms')]
   >>> templates = [('temp' + str(i), read(filename))
   ...              for i, filename in enumerate(template_files)]
   >>> extracted = extract_detections(detections, templates,
   ...                                archive=archive, arc_type='day_vols')
   Working on detections for day: 2012-03-26T00:00:00.000000Z
   Cutting for detections at: 2012/03/26 09:15:00
   Cutting for detections at: 2012/03/26 18:05:00
   >>> print(extracted[0].sort())
   2 Trace(s) in Stream:
   AF.EORO..SHZ | 2012-03-26T09:14:15.000000Z - 2012-03-26T09:15:45.000000Z |\
1.0 Hz, 91 samples
   AF.WHYM..SHZ | 2012-03-26T09:14:15.000000Z - 2012-03-26T09:15:45.000000Z |\
1.0 Hz, 91 samples
   >>> print(extracted[1].sort())
   2 Trace(s) in Stream:
   AF.EORO..SHZ | 2012-03-26T18:04:15.000000Z - 2012-03-26T18:05:45.000000Z |\
1.0 Hz, 91 samples
   AF.WHYM..SHZ | 2012-03-26T18:04:15.000000Z - 2012-03-26T18:05:45.000000Z |\
1.0 Hz, 91 samples
   >>> # Extract from stations not included in the detections
   >>> extracted = extract_detections(
   ...    detections, templates, archive=archive, arc_type='day_vols',
   ...    additional_stations=[('GOVA', 'SHZ')])
   Adding additional stations
   Added station GOVA.SHZ
   Added station GOVA.SHZ
   Working on detections for day: 2012-03-26T00:00:00.000000Z
   Cutting for detections at: 2012/03/26 09:15:00
   Cutting for detections at: 2012/03/26 18:05:00
   >>> print(extracted[0].sort())
   3 Trace(s) in Stream:
   AF.EORO..SHZ | 2012-03-26T09:14:15.000000Z - 2012-03-26T09:15:45.000000Z |\
1.0 Hz, 91 samples
   AF.GOVA..SHZ | 2012-03-26T09:14:15.000000Z - 2012-03-26T09:15:45.000000Z |\
1.0 Hz, 91 samples
   AF.WHYM..SHZ | 2012-03-26T09:14:15.000000Z - 2012-03-26T09:15:45.000000Z |\
1.0 Hz, 91 samples
   >>> # The detections can be saved to a file:
   >>> extract_detections(detections, templates, archive=archive,
   ...                    arc_type='day_vols',
   ...                    additional_stations=[('GOVA', 'SHZ')], outdir='.')
   Adding additional stations
   Added station GOVA.SHZ
   Added station GOVA.SHZ
   Working on detections for day: 2012-03-26T00:00:00.000000Z
   Cutting for detections at: 2012/03/26 09:15:00
   Written file: ./temp1/2012-03-26_09-15-00.ms
   Cutting for detections at: 2012/03/26 18:05:00
   Written file: ./temp2/2012-03-26_18-05-00.ms