def brightness(stations, nodes, lags, stream, threshold, thresh_type,<EOL>template_length, template_saveloc, coherence_thresh,<EOL>coherence_stations=['<STR_LIT:all>'], coherence_clip=False,<EOL>gap=<NUM_LIT>, clip_level=<NUM_LIT:100>, instance=<NUM_LIT:0>, pre_pick=<NUM_LIT>,<EOL>plotvar=False, plotsave=True, cores=<NUM_LIT:1>, debug=<NUM_LIT:0>,<EOL>mem_issue=False):
if plotsave:<EOL><INDENT>import matplotlib<EOL>matplotlib.use('<STR_LIT>')<EOL>import matplotlib.pyplot as plt<EOL>plt.ioff()<EOL><DEDENT>from eqcorrscan.utils import plotting<EOL>from eqcorrscan.utils.debug_log import debug_print<EOL>realstations = []<EOL>for station in stations:<EOL><INDENT>st = stream.select(station=station)<EOL>if st:<EOL><INDENT>realstations += station<EOL><DEDENT><DEDENT>del st<EOL>stream_copy = stream.copy()<EOL>for tr in stream_copy:<EOL><INDENT>if max(abs(tr.data)) > <NUM_LIT>:<EOL><INDENT>tr.data = <NUM_LIT> * (tr.data / max(abs(tr.data)))<EOL><DEDENT>tr.data = tr.data.astype(np.int16)<EOL><DEDENT>if len(stream_copy) > <NUM_LIT>:<EOL><INDENT>raise BrightnessError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>print('<STR_LIT>')<EOL>num_cores = cores<EOL>if num_cores > len(nodes):<EOL><INDENT>num_cores = len(nodes)<EOL><DEDENT>if num_cores > cpu_count():<EOL><INDENT>num_cores = cpu_count()<EOL><DEDENT>if mem_issue and not os.path.isdir('<STR_LIT>' + str(instance)):<EOL><INDENT>os.makedirs('<STR_LIT>' + str(instance))<EOL><DEDENT>pool = Pool(processes=num_cores)<EOL>results = [pool.apply_async(_node_loop, (stations,),<EOL>{'<STR_LIT>': lags[:, i], '<STR_LIT>': stream, '<STR_LIT:i>': i,<EOL>'<STR_LIT>': clip_level,<EOL>'<STR_LIT>': mem_issue, '<STR_LIT>': instance})<EOL>for i in range(len(nodes))]<EOL>pool.close()<EOL>if not mem_issue:<EOL><INDENT>print('<STR_LIT>')<EOL>try:<EOL><INDENT>energy = [p.get() for p in results]<EOL><DEDENT>except KeyboardInterrupt as e:  <EOL><INDENT>pool.terminate()<EOL>raise e<EOL><DEDENT>pool.join()<EOL>energy.sort(key=lambda tup: tup[<NUM_LIT:0>])<EOL>energy = [node[<NUM_LIT:1>] for node in energy]<EOL>energy = np.concatenate(energy, axis=<NUM_LIT:0>)<EOL>print(energy.shape)<EOL><DEDENT>else:<EOL><INDENT>pool.join()<EOL>del results<EOL><DEDENT>if not mem_issue:<EOL><INDENT>print(energy.shape)<EOL>indices = np.argmax(energy, axis=<NUM_LIT:0>)  <EOL>print(indices.shape)<EOL>cum_net_resp = np.array([np.nan] * len(indices))<EOL>cum_net_resp[<NUM_LIT:0>] = energy[indices[<NUM_LIT:0>]][<NUM_LIT:0>]<EOL>peak_nodes = [nodes[indices[<NUM_LIT:0>]]]<EOL>for i in range(<NUM_LIT:1>, len(indices)):<EOL><INDENT>cum_net_resp[i] = energy[indices[i]][i]<EOL>peak_nodes.append(nodes[indices[i]])<EOL><DEDENT>del energy, indices<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>')<EOL>node_splits = int(len(nodes) // num_cores)<EOL>print(node_splits)<EOL>indices = []<EOL>for i in range(num_cores):<EOL><INDENT>indices.append(list(np.arange(node_splits * i,<EOL>node_splits * (i + <NUM_LIT:1>))))<EOL><DEDENT>indices[-<NUM_LIT:1>] += list(np.arange(node_splits * (i + <NUM_LIT:1>), len(nodes)))<EOL>pool = Pool(processes=num_cores)<EOL>results = [pool.apply_async(_cum_net_resp, args=(indices[i], instance))<EOL>for i in range(num_cores)]<EOL>pool.close()<EOL>try:<EOL><INDENT>results = [p.get() for p in results]<EOL><DEDENT>except KeyboardInterrupt as e:  <EOL><INDENT>pool.terminate()<EOL>raise e<EOL><DEDENT>pool.join()<EOL>responses = [result[<NUM_LIT:0>] for result in results]<EOL>print(np.shape(responses))<EOL>node_indices = [result[<NUM_LIT:1>] for result in results]<EOL>cum_net_resp = np.array(responses)<EOL>indices = np.argmax(cum_net_resp, axis=<NUM_LIT:0>)<EOL>print(indices.shape)<EOL>print(cum_net_resp.shape)<EOL>cum_net_resp = np.array([cum_net_resp[indices[i]][i]<EOL>for i in range(len(indices))])<EOL>peak_nodes = [nodes[node_indices[indices[i]][i]]<EOL>for i in range(len(indices))]<EOL>del indices, node_indices<EOL><DEDENT>if plotvar:<EOL><INDENT>cum_net_trace = Stream(Trace(<EOL>data=cum_net_resp, header=Stats(<EOL>{'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:location>': '<STR_LIT>', '<STR_LIT>': stream[<NUM_LIT:0>].stats.starttime,<EOL>'<STR_LIT>': stream[<NUM_LIT:0>].stats.sampling_rate})))<EOL>cum_net_trace += stream.select(channel='<STR_LIT>')<EOL>cum_net_trace += stream.select(channel='<STR_LIT>')<EOL>cum_net_trace.sort(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL><DEDENT>print('<STR_LIT>')<EOL>detections = _find_detections(cum_net_resp, peak_nodes, threshold,<EOL>thresh_type, stream[<NUM_LIT:0>].stats.sampling_rate,<EOL>realstations, gap)<EOL>del cum_net_resp<EOL>templates = []<EOL>nodesout = []<EOL>good_detections = []<EOL>if detections:<EOL><INDENT>print('<STR_LIT>')<EOL>for j, detection in enumerate(detections):<EOL><INDENT>debug_print('<STR_LIT>'<EOL>% (j, len(detections)), <NUM_LIT:3>, debug)<EOL>event = Event()<EOL>event.event_descriptions.append(EventDescription())<EOL>event.event_descriptions[<NUM_LIT:0>].text = '<STR_LIT>'<EOL>event.creation_info = CreationInfo(agency_id='<STR_LIT>')<EOL>copy_of_stream = deepcopy(stream_copy)<EOL>node = (detection.template_name.split('<STR_LIT:_>')[<NUM_LIT:0>],<EOL>detection.template_name.split('<STR_LIT:_>')[<NUM_LIT:1>],<EOL>detection.template_name.split('<STR_LIT:_>')[<NUM_LIT:2>])<EOL>index = nodes.index((float(node[<NUM_LIT:0>]), float(node[<NUM_LIT:1>]),<EOL>float(node[<NUM_LIT:2>])))<EOL>detect_lags = lags[:, index]<EOL>ksta = Comment(text='<STR_LIT>' + str(len(detect_lags)))<EOL>event.origins.append(Origin())<EOL>event.origins[<NUM_LIT:0>].comments.append(ksta)<EOL>event.origins[<NUM_LIT:0>].time = copy_of_stream[<NUM_LIT:0>].stats.starttime +detect_lags[<NUM_LIT:0>] + detection.detect_time<EOL>event.origins[<NUM_LIT:0>].latitude = node[<NUM_LIT:0>]<EOL>event.origins[<NUM_LIT:0>].longitude = node[<NUM_LIT:1>]<EOL>event.origins[<NUM_LIT:0>].depth = node[<NUM_LIT:2>]<EOL>for i, detect_lag in enumerate(detect_lags):<EOL><INDENT>station = stations[i]<EOL>st = copy_of_stream.select(station=station)<EOL>if len(st) != <NUM_LIT:0>:<EOL><INDENT>for tr in st:<EOL><INDENT>_waveform_id = WaveformStreamID(<EOL>station_code=tr.stats.station,<EOL>channel_code=tr.stats.channel,<EOL>network_code=tr.stats.network)<EOL>event.picks.append(Pick(<EOL>waveform_id=_waveform_id,<EOL>time=tr.stats.starttime + detect_lag +<EOL>detection.detect_time + pre_pick,<EOL>onset='<STR_LIT>', evalutation_mode='<STR_LIT>'))<EOL><DEDENT><DEDENT><DEDENT>debug_print('<STR_LIT>' % j, <NUM_LIT:0>, debug)<EOL>template = _template_gen(<EOL>picks=event.picks, st=copy_of_stream, length=template_length,<EOL>swin='<STR_LIT:all>')<EOL>template_name = template_saveloc + '<STR_LIT:/>' +str(template[<NUM_LIT:0>].stats.starttime) + '<STR_LIT>'<EOL>temp_coher, kchan = coherence(template, coherence_stations,<EOL>coherence_clip)<EOL>coh_thresh = float(coherence_thresh[<NUM_LIT:0>]) - kchan /float(coherence_thresh[<NUM_LIT:1>])<EOL>coherent = False<EOL>if temp_coher > coh_thresh:<EOL><INDENT>template.write(template_name, format="<STR_LIT>")<EOL>print('<STR_LIT>' + template_name)<EOL>print('<STR_LIT>' +<EOL>str(temp_coher))<EOL>coherent = True<EOL>debug_print('<STR_LIT>' +<EOL>str(temp_coher), <NUM_LIT:0>, debug)<EOL>coherent = False<EOL><DEDENT>del copy_of_stream, tr, template<EOL>if coherent:<EOL><INDENT>templates.append(obsread(template_name))<EOL>nodesout += [node]<EOL>good_detections.append(detection)<EOL><DEDENT>debug_print('<STR_LIT>', <NUM_LIT:0>, debug)<EOL><DEDENT><DEDENT>if plotvar:<EOL><INDENT>good_detections = [(cum_net_trace[-<NUM_LIT:1>].stats.starttime +<EOL>detection.detect_time).datetime<EOL>for detection in good_detections]<EOL>if not plotsave:<EOL><INDENT>plotting.NR_plot(cum_net_trace[<NUM_LIT:0>:-<NUM_LIT:1>],<EOL>Stream(cum_net_trace[-<NUM_LIT:1>]),<EOL>detections=good_detections,<EOL>size=(<NUM_LIT>, <NUM_LIT:10>),<EOL>title='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>savefile = '<STR_LIT>' +cum_net_trace[<NUM_LIT:0>].stats.starttime.datetime.strftime('<STR_LIT>') +'<STR_LIT>'<EOL>plotting.NR_plot(cum_net_trace[<NUM_LIT:0>:-<NUM_LIT:1>],<EOL>Stream(cum_net_trace[-<NUM_LIT:1>]),<EOL>detections=good_detections,<EOL>size=(<NUM_LIT>, <NUM_LIT:10>), save=True, savefile=savefile,<EOL>title='<STR_LIT>')<EOL><DEDENT><DEDENT>nodesout = list(set(nodesout))<EOL>return templates, nodesout<EOL>
Calculate the brightness function for a single day.

Written to calculate the brightness function for a single day of data,
using moveouts from a 3D travel-time grid.

.. Note::
    Data in stream must be all of the same length and have the same
    sampling rates, see :func:`eqcorrscan.utils.pre_processing.dayproc`

:type stations: list
:param stations:
    List of station names from in the form where stations[i] refers to
    nodes[i][:] and lags[i][:]
:type nodes: list
:param nodes:
    List of node points where nodes[i] refers to stations[i] and
    nodes[:][:][0] is latitude in degrees, nodes[:][:][1] is longitude in
    degrees, nodes[:][:][2] is depth in km.
:type lags: numpy.ndarray
:param lags:
    Array of arrays where lags[i][:] refers to stations[i]. lags[i][j]
    should be the delay to the nodes[i][j] for stations[i] in seconds.
:type stream: obspy.core.stream.Stream
:param stream: Data through which to look for detections.
:type threshold: float
:param threshold:
    Threshold value for detection of template within the brightness
    function.
:type thresh_type: str
:param thresh_type:
    Either MAD or abs where MAD is the Median Absolute Deviation and abs
    is an absolute brightness.
:type template_length: float
:param template_length: Length of template to extract in seconds
:type template_saveloc: str
:param template_saveloc: Path of where to save the templates.
:type coherence_thresh: tuple
:param coherence_thresh:
        Threshold for removing incoherent peaks in the network response,
        those below this will not be used as templates. Must be in the
        form of (a,b) where the coherence is given by: :math:`a-kchan/b`
        where kchan is the number of channels used to compute the
        coherence.
:type coherence_stations: list
:param coherence_stations:
    List of stations to use in the coherence thresholding - defaults to
    `all` which uses all the stations.
:type coherence_clip: tuple
:param coherence_clip:
    Start and end in seconds of data to window around, defaults to False,
    which uses all the data given.
:type gap: float
:param gap: Minimum inter-event time in seconds for detections.
:type clip_level: float
:param clip_level:
    Multiplier applied to the mean deviation of the energy as an upper
    limit, used to remove spikes (earthquakes, lightning, electrical
    spikes) from the energy stack.
:type instance: int
:param instance:
    Optional, used for tracking when using a distributed computing system.
:type pre_pick: float
:param pre_pick: Seconds before the detection time to include in template
:type plotvar: bool
:param plotvar: Turn plotting on or off
:type plotsave: bool
:param plotsave:
    Save or show plots, if `False` will try and show the plots on screen -
    as this is designed for bulk use this is set to `True` to save any
    plots rather than show them if you create them - changes the backend
    of matplotlib, so if is set to `False` you will see NO PLOTS!
:type cores: int
:param cores: Number of cores to use, defaults to 1.
:type debug: int
:param debug: Debug level from 0-5, higher is more output.
:type mem_issue: bool
:param mem_issue:
    Set to True to write temporary variables to disk rather than store in
    memory, slow.

:return: list of templates as :class:`obspy.core.stream.Stream` objects
:rtype: list