utils.py 23.4 KB
Newer Older
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
1
2
3
4
5
6
7
8
9
import io
import logging
import os
import re
import sys
import time
from difflib import SequenceMatcher
from datetime import datetime, timedelta

Jerome Touvier's avatar
Jerome Touvier committed
10
from flask import current_app, make_response, Response, request
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
11

Jerome Touvier's avatar
Jerome Touvier committed
12
import matplotlib.pyplot as plt
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from matplotlib.ticker import FuncFormatter, MaxNLocator

import numpy as np

from obspy.clients.fdsn import Client
from obspy.clients.fdsn.client import FDSNNoDataException
from obspy.core import read, UTCDateTime
from obspy.core.stream import Stream

import psycopg2

from scipy.signal import periodogram

from apps.extender import extend
from apps.globals import DATA_MOUNT_POINT
from apps.globals import DPI_MIN, DPI_MAX
from apps.globals import Error
from apps.globals import FDSN_CLIENT
from apps.globals import HEIGHT_MIN, HEIGHT_MAX
from apps.globals import HTTP
from apps.globals import IMAGE_FORMAT
from apps.globals import MAX_DATA_POINTS
from apps.globals import MAX_DATA_POINTS_FAST_MODE
from apps.globals import MAX_PLOTS
from apps.globals import STRING_FALSE
from apps.globals import STRING_TRUE
from apps.globals import TAPER_WINDOWS
from apps.globals import UNITS
from apps.globals import USER_AGENT_TIMESERIES
from apps.globals import WIDTH_MIN, WIDTH_MAX
from apps.globals import WL_MIN, WL_MAX
from apps.globals import XTICKS_ROTATION
from apps.timeseries.constants import VERSION


def is_valid_integer(dimension, mini=0, maxi=sys.maxsize):
Jerome Touvier's avatar
Jerome Touvier committed
49
    # by default valid for positive integers
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
50
51
52
53
54
55
56
57
    try:
        dimension = int(dimension)
        if mini <= dimension <= maxi:
            return True
    except Exception:
        return False


Jerome Touvier's avatar
Jerome Touvier committed
58
59
def is_valid_float(dimension, mini=sys.float_info.epsilon, maxi=sys.float_info.max):
    # by default valid for strictly positive floats
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    try:
        dimension = float(dimension)
        if mini <= dimension <= maxi:
            return True
    except Exception:
        return False


def is_valid_datetime(date):
    for df in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f"):
        try:
            return datetime.strptime(date, df)
        except (ValueError, TypeError):
            pass


def is_valid_starttime(date):
    return is_valid_datetime(date) or date == "currentutcday"


def is_valid_endtime(date):
    return is_valid_datetime(date) or date == "currentutcday" or is_valid_integer(date)


def is_valid_network(network):
    return re.match("[A-Za-z0-9*?]{1,2}$", network) if network else False


def is_valid_station(station):
    return re.match("[A-Za-z0-9*?]{1,5}$", station) if station else False


def is_valid_location(location):
    return re.match("([A-Za-z0-9*?-]{1,2})$", location) if location else False


def is_valid_channel(channel):
    return re.match("([A-Za-z0-9*?]{1,3})$", channel) if channel else False


def is_valid_quality(quality):
    return re.match("[DMQR*?]{1}$", quality) if quality else False


def is_valid_bool_string(string):
    if string is None:
        return False
    return True if string.lower() in (STRING_TRUE + STRING_FALSE) else False


def is_valid_output(output, allowed_output):
    return output.lower() in allowed_output if output else False


def is_valid_image_format(image):
    # None or empty are false
    return image.lower() in IMAGE_FORMAT if image else False


def is_valid_units(units):
    return units.upper() in UNITS if units else False


def is_valid_taper_window(taper):
    return is_valid_float(taper[0], 0.0, 0.5) and (
        len(taper) == 1 or (len(taper) == 2 and taper[1].upper() in TAPER_WINDOWS)
    )


def is_valid_bpfilter(bp):
    return len(bp) == 2 and all(is_valid_float(b) for b in bp)


def is_valid_freqlimits(freqs):
    return len(freqs) == 4 and all(is_valid_float(f, 0.0) for f in freqs)


def is_valid_color(color):
    return re.match(r"^(?:[0-9a-fA-F]{2}){3}$", color) if color else False


def currentutcday():
    return datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)


def tictac(tic):
    return round(time.time() - tic, 2)


# Result HTTP code 400 shortcut function
def error_param(params, dmesg):
    return (params, {"msg": HTTP._400_, "details": dmesg, "code": 400})


# Error request function
def error_request(msg=" ", details=" ", code=" "):
    request_date = datetime.utcnow().strftime("%Y-%b-%d %H:%M:%S UTC")
Jerome Touvier's avatar
Jerome Touvier committed
157
    message_error = f"Error {code}: {msg} Please mention your request URL when asking for support\n\n\
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    More Details: {details}\n\n\
    Request: {request.url}\n\
    Request Submitted: {request_date} \n\
    Service version: version {VERSION}"
    return Response(message_error, status=code, mimetype="*/*")


# Error 202 response alias
def nodata_error(dmesg):
    return error_request(msg=HTTP._202_, details=dmesg, code=202)


# Error 413 response alias
def overflow_error(dmesg):
    return error_request(msg=HTTP._413_, details=dmesg, code=413)


# Error 500 response alias
def error_500(dmesg):
    return error_request(msg=HTTP._500_, details=dmesg, code=500)


# check request
def check_request(request, params, alias):
    for key, val in request.args.items():
        if key not in params:
            ratios = [SequenceMatcher(None, key, p).ratio() for p in params]
            guess = max([(v, params[ind]) for ind, v in enumerate(ratios)])
            hint = ". Did you mean " + guess[1] + " ?" if guess[0] > 0.7 else ""
            return error_param(params, Error.UNKNOWN_PARAM + key + hint)

Jerome Touvier's avatar
Jerome Touvier committed
189
190
        # find nonword chars except :
        # "," for lists "*?" for wildcards and ".:-" for date
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
        if re.search(r"[^a-zA-Z0-9_,*?.:-]", val):
            return error_param(params, Error.CHAR + key)

    for key in params:
        if len(request.args.getlist(key)) > 1:
            return error_param(params, Error.MULTI_PARAM + str(key))

    for key in alias:
        if len([v for v in key if v in request.args]) > 1:
            return error_param(params, Error.MULTI_PARAM + str(key))

    return (params, {"msg": HTTP._200_, "details": Error.VALID_PARAM, "code": 200})


def check_base_parameters(
    params, max_days=None, not_none=None, booleans=None, floats=None
):

    if max_days is None:
        max_days = 10 ** 9 - 1

    # Search for missing mandatory parameters
    if not_none is not None:
        for key in not_none:
            if params[key] is None:
                return error_param(params, Error.MISSING + key)

    # Boolean parameter validations
    if booleans is not None:
        for key in booleans:
            val = params[key]
            if not is_valid_bool_string(val):
                return error_param(params, f"Invalid {key} value: {val} {Error.BOOL}.")
            params[key] = True if val.lower() in STRING_TRUE else False

    # Float parameter validations
    if floats is not None:
        for key in floats:
            val = params[key]
            if is_valid_float(val):
                params[key] = float(val)
            elif val is not None:
                return error_param(params, f"Invalid {key} value: {val}")

    # Station validations
    network = params["network"].split(",")
    station = params["station"].split(",")
    location = params["location"].split(",")
    channel = params["channel"].split(",")

    for n in network:
        if not is_valid_network(n):
            return error_param(params, Error.NETWORK + n)
    for s in station:
        if not is_valid_station(s):
            return error_param(params, Error.STATION + s)
    for l in location:
        if not is_valid_location(l):
            return error_param(params, Error.LOCATION + l)
    for c in channel:
        if not is_valid_channel(c):
            return error_param(params, Error.CHANNEL + c)

    # Start time and end time validations
    if params["start"] is not None:
        if not is_valid_starttime(params["start"]):
            return error_param(params, Error.TIME + str(params["start"]))

        if is_valid_datetime(params["start"]):
            params["start"] = is_valid_datetime(params["start"])
        elif params["start"] == "currentutcday":
            params["start"] = currentutcday()

    if params["end"] is not None:
        if not is_valid_endtime(params["end"]):
            return error_param(params, Error.TIME + str(params["end"]))

        if is_valid_datetime(params["end"]):
            params["end"] = is_valid_datetime(params["end"])
        elif params["end"] == "currentutcday":
            params["end"] = currentutcday()

    if params["start"] is not None and params["end"] is not None:
        if is_valid_integer(params["start"]) and is_valid_integer(params["end"]):
            params["start"] = currentutcday() - timedelta(seconds=int(params["start"]))
            params["end"] = currentutcday() + timedelta(seconds=int(params["end"]))

        if is_valid_integer(params["end"]):
            params["end"] = params["start"] + timedelta(seconds=int(params["end"]))

        if params["start"] > params["end"]:
            start = str(params["start"])
            end = str(params["end"])
            return error_param(params, Error.START_LATER + start + " > " + end)

        if params["end"] - params["start"] > timedelta(days=max_days):
            return error_param(params, Error.TOO_LONG_DURATION + f"{max_days} days).")

    # Search for empty selection
    if params["network"] == params["station"] == params["channel"] == "*":
        return error_param(params, Error.NO_SELECTION)

    return (params, {"msg": HTTP._200_, "details": Error.VALID_PARAM, "code": 200})


def check_timeseriesplots_parameters(params):
    # Plot parameter validations
    if not is_valid_integer(params["width"], WIDTH_MIN, WIDTH_MAX):
        return error_param(params, Error.WIDTH + str(params["width"]))
    if not is_valid_integer(params["height"], HEIGHT_MIN, HEIGHT_MAX):
        return error_param(params, Error.HEIGHT + str(params["height"]))
    if not is_valid_integer(params["dpi"], DPI_MIN, DPI_MAX):
        return error_param(params, Error.DPI + str(params["dpi"]))
    if not is_valid_color(params["color"]):
        return error_param(params, Error.COLOR + str(params["color"]))

    params["width"] = int(params["width"])
    params["height"] = int(params["height"])
    params["dpi"] = int(params["dpi"])

    # Water level parameter validation
    if params["waterlevel"] is not None and not params["earthunits"]:
        return error_param(params, Error.WATER_EARTHUNITS)

    if params["waterlevel"] is None:
        params["waterlevel"] = 1.0
    elif is_valid_float(params["waterlevel"], WL_MIN, WL_MAX):
        params["waterlevel"] = float(params["waterlevel"])
    elif params["waterlevel"].lower() == "none":
        params["waterlevel"] = None
    else:
        return error_param(params, Error.WATERLEVEL + str(params["waterlevel"]))

    # Freqlimits validation (deconvolution prefilter)
    if params["freqlimits"] is not None:
        params["freqlimits"] = tuple(re.split("[/,;-]", params["freqlimits"]))
        if not is_valid_freqlimits(params["freqlimits"]):
            return error_param(params, Error.FREQLIMITS + str(params["freqlimits"]))
        params["freqlimits"] = [float(params["freqlimits"][i]) for i in range(4)]

    # Units validation
    if not is_valid_units(params["units"]):
        return error_param(params, Error.UNITS + str(params["units"]))
    params["units"] = params["units"].upper()

    # Image file extension validation
    if not is_valid_image_format(params["imageformat"]):
        return error_param(params, Error.FORMAT + str(params["imageformat"]))
    params["imageformat"] = params["imageformat"].lower()

    return (params, {"msg": HTTP._200_, "details": Error.VALID_PARAM, "code": 200})


def get_signal_from_client(params):
    """Get timeseries from FDSN client.

    :param params: Parameters object with url parameters (network, station, ...)
    :returns: a tuple (trace.time, trace.data, trace.stats)
    :raises FDSNNoDataException: raises value exception

    """

    start = UTCDateTime(params["start"])
    end = UTCDateTime(params["end"])

    try:
        logging.debug("Enter in get_signal_from_client function.")
        client = Client(FDSN_CLIENT, user_agent=USER_AGENT_TIMESERIES)
        st = client.get_waveforms(
            params["network"],
            params["station"],
            params["location"],
            params["channel"],
            start,
            end,
        )
        logging.debug("Transfer terminated.")
Jerome Touvier's avatar
Jerome Touvier committed
368
369
        st.trim(start, end)
        logging.debug("Trimming terminated.")
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
        return st
    except FDSNNoDataException as nodata:
        logging.debug(repr(nodata))
    except Exception as ex:
        logging.exception(str(ex))


def get_response(params):
    """Get instrumental response from FDSN client."""
    client = Client(FDSN_CLIENT, user_agent=USER_AGENT_TIMESERIES)
    return client.get_stations(
        network=params["network"],
        station=params["station"],
        location=params["location"],
        channel=params["channel"],
        level="response",
        format="xml",
    )


def is_open_file(paths):
    """Embargoed files are removed from the list of paths."""

    if not paths:
        return

Jerome Touvier's avatar
Jerome Touvier committed
396
397
398
399
400
401
402
403
    values = ", ".join(f"""('{j}', '{k}')""" for j, k in paths)
    select = f"""SELECT path, name
    FROM rbud, ( SELECT * FROM (VALUES {values}) AS t(path, name) ) AS t1
    WHERE source_file=t1.name AND channel_id !=0 UNION SELECT path, name
    FROM rall, ( SELECT * FROM (VALUES {values}) AS t(path, name) ) AS t1
    WHERE source_file=t1.name AND channel_id !=0;"""

    with psycopg2.connect(current_app.config["DATABASE_URI"]) as conn:
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
404
        logging.debug(conn.get_dsn_parameters())
Jerome Touvier's avatar
Jerome Touvier committed
405
406
407
408
409
        logging.debug(f"Postgres version : {conn.server_version}")
        with conn.cursor() as curs:
            curs.execute(select)
            logging.debug(curs.statusmessage)
            return curs.fetchall()
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423


def get_signal(params):
    """Get timeseries from summer.

    :param params: Parameters object with url parameters (network, station, ...)
    :returns: a tuple (trace.time, trace.data, trace.stats)
    :raises FDSNNoDataException: raises value exception

    """
    logging.debug("Enter in get_signal function.")

    net = f"-n={params['network']}"
    sta = f"-s={params['station']}"
Jerome Touvier's avatar
Jerome Touvier committed
424
    loc = "-l=_" if params["location"] == "--" else f"-l={params['location']}"
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
425
426
    cha = f"-c={params['channel']}"

Jerome Touvier's avatar
Jerome Touvier committed
427
    # Wildcards are extended into atomic quadruplets.
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
428
    res = extend(args=[net, sta, loc, cha, "--format=tuple"])
Jerome Touvier's avatar
Jerome Touvier committed
429
    logging.debug(res)
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    if not res:
        return

    filenames = list()
    delta = params["end"] - params["start"]
    start = UTCDateTime(params["start"])
    end = UTCDateTime(params["end"])

    # A filename is built for each selected channel and period (one day
    # before this period is added because some data near midnight may be there).
    for x in range(-1, delta.days + 1):
        date = (params["start"] + timedelta(days=x)).timetuple()
        year = date.tm_year
        day = str(date.tm_yday).rjust(3, "0")
        for net, sta, loc, cha in res:
            loc = "" if loc == "--" else loc
            filename = f"{net}.{sta}.{loc}.{cha}.D.{year}.{day}"
            finalpath = f"{year}/{net}/{sta}/{cha}.D/"
            filenames.append((finalpath, filename))

    paths = list()
    open_files = is_open_file(filenames)
    # We can now build the full path.
    if filenames:
        for path in open_files:
            finalpath = "".join(path)
            basedir = DATA_MOUNT_POINT
            validated = f"{basedir}/validated_seismic_data/{finalpath}"
            bud = f"{basedir}/bud_data/{finalpath}"
            if os.path.exists(validated):
                paths.append(validated)
            elif os.path.exists(bud):
                paths.append(bud)

    st = Stream()
    for fullname in paths:
        try:
            tmp = read(fullname, format="MSEED", starttime=start, endtime=end)
            if tmp:
                st += tmp
            if sum(len(tr) for tr in st) > MAX_DATA_POINTS:
                break
            if len(st) > MAX_PLOTS:
                break
        except Exception as ex:
            logging.exception(str(ex))
    st.merge()
    return st


def remove_response(tr, params):
    units = params["units"]
    if params["units"] == "AUTO":
        if tr.stats.channel[1] == "N":
            units = "ACC"
        else:
            units = "VEL"  # ?H? and others...

    water, demean, taper = params["waterlevel"], params["demean"], False
    freqs = params["freqlimits"]
    try:
        tr.remove_response(
            output=units,
            water_level=water,
            zero_mean=demean,
            taper=taper,
            pre_filt=freqs,
        )
        msg = f"Instrumental response removed : water_level={water}, zero_mean={demean}, taper={taper}"
        logging.debug(msg)
    except NotImplementedError as nierr:
        logging.debug(str(nierr) + ":" + str(tr.stats))
    except Exception as ex:
        logging.exception(str(ex))


def get_periodogram(x):
    """Estimate power spectral density of timeseries using a periodogram.

    :param x: timeseries values
    :returns: values in V**2/Hz if x is measured in V and fs is measured in Hz

    """
    f, Pxx_den = periodogram(
        x,
        fs=100,  # Sampling frequency of the x timeseries
        window=None,
        nfft=None,
        detrend="constant",
        return_onesided=True,
        scaling="density",  # where Pxx has units of V**2/Hz
    )
    # Pxx_den = [10*math.log10(n) for n in Pxx_den] # in dB
    return (f, Pxx_den)


def get_bounds(st):
    """Work out the minimum starttime and the maximum endtime.

    :param st: obspy stream
    :returns: a tuple with the bounds for all plots

    """
    min_starttime = min((tr.times("timestamp")[0] for tr in st))
    max_endtime = max((tr.times("timestamp")[-1] for tr in st))
    return (min_starttime, max_endtime)


def date_format_hours(x, pos=None):
    """See date_format_days function
       Only the first tick contains the full date.
    """
    fmt = "%D %H:%M:%S" if pos == 1 else "%H:%M:%S"
    return datetime.utcfromtimestamp(x).strftime(fmt)


def date_format_days(x, pos=None):
    """User-defined function for formatting a tick representing a date.

    :param x: a tick value
    :param pos: a tick position (Default value = None)
    :returns: a string containing the corresponding tick label

    """
    return datetime.utcfromtimestamp(x).strftime("%D %H:%M:%S")


def get_units(params, plot_channel):
    units = " counts"
    if params["earthunits"]:
        units = " m/s"
        if params["units"] == "ACC":
            units = " m/s²"
        elif params["units"] == "DISP":
            units = " m"
        elif params["units"] == "AUTO" and plot_channel[1] == "N":
            units = " m/s²"
    return units


def add_scale_bar(params, ax, plot_channel, tick_sz):
Jerome Touvier's avatar
Jerome Touvier committed
571
    """Builds a scale bar according to the current channel name.
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640

    :param ax: current Axes instance on the current figure
    :param params: Parameters object with url parameters (network, station, ...)
    :param plot_channel: current channel name

    """

    scale = (ax.get_ylim()[1] - ax.get_ylim()[0]) / 2
    ax.annotate(
        ("%.2e" % scale) + get_units(params, plot_channel),
        xy=(1.04, 0.50),
        xycoords="axes fraction",
        horizontalalignment="center",
        verticalalignment="center",
        rotation=90,
        fontsize=tick_sz - 1,
    )
    ax.annotate(
        "" % scale,
        xy=(1.05, 0.25),
        xytext=(1.05, 0.75),
        xycoords="axes fraction",
        horizontalalignment="center",
        verticalalignment="center",
        arrowprops=dict(arrowstyle="-"),
    )


# def static_plots(params, st):
#    """Create static timeseries plots with obspy plot function"""
#    tic = time.time()
#    img = st.plot(
#        color="#" + params["color"],
#        number_of_ticks=6,
#        tick_rotation=5,
#        tick_format="%I:%M %p",
#        linewidth=0.25,
#        block=False,
#        size=(params["width"], len(st) * params["height"]),
#        format="png",
#        equal_scale=False
#        # handle=True,
#    )

#    logging.debug(tictac(tic))
#    response = make_response(img)
#    response.mimetype = "image/" + params["imageformat"]
#    return response


def min_max_downsample(x, y, num_bins):
    # From https://stackoverflow.com/questions/54449631/improve-min-max-downsampling
    # Remaining (last) samples are ignored.
    pts_per_bin = x.size // num_bins

    x_view = x[: pts_per_bin * num_bins].reshape(num_bins, pts_per_bin)
    y_view = y[: pts_per_bin * num_bins].reshape(num_bins, pts_per_bin)
    i_min = np.argmin(y_view, axis=1)
    i_max = np.argmax(y_view, axis=1)

    r_index = np.repeat(np.arange(num_bins), 2)
    c_index = np.sort(np.stack((i_min, i_max), axis=1)).ravel()

    return x_view[r_index, c_index], y_view[r_index, c_index]


def static_plots(params, st):
    """Create static timeseries plots.

Jerome Touvier's avatar
Jerome Touvier committed
641
    This function return static timeseries plots builds with matplotlib and embedded
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
    into HTML via Flask renderer.

    :param params: Parameters object with url parameters (network, station, ...)
    :param st: obspy stream
    :returns: response_class flask object containing static timeseries plot(s)

    """

    tic = time.time()
    img = io.BytesIO()
    nplots = len(st)
    (left, right) = get_bounds(st)
    tick_sz = params["width"] // 100 - 2
    pcolor = "black" if params["monochrome"] else "#" + params["color"]

    if params["dpi"] != 100:
Jerome Touvier's avatar
Jerome Touvier committed
658
        fig = plt.figure(figsize=(12, 4 * nplots), dpi=params["dpi"])
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
659
660
661
    else:
        width = params["width"] // params["dpi"]
        height = params["height"] // params["dpi"]
Jerome Touvier's avatar
Jerome Touvier committed
662
        fig = plt.figure(figsize=(width, height * nplots), dpi=params["dpi"])
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708

    for n, tr in enumerate(st):
        n = n + 1
        logging.debug(f"Creation of plot {n}...")
        ax = fig.add_subplot(nplots, 1, n)

        if len(tr) <= MAX_DATA_POINTS_FAST_MODE:
            (x, y) = (tr.times("timestamp"), tr.data)
        else:
            (x, y) = min_max_downsample(tr.times("timestamp"), tr.data, params["width"])

        ax.plot(x, y, color=pcolor, linewidth=0.50)
        ax.grid(color="black", linestyle=":", linewidth=0.25)
        ax.xaxis.set_tick_params(rotation=XTICKS_ROTATION, labelsize=tick_sz)
        ax.xaxis.set_major_locator(MaxNLocator(5))
        ax.yaxis.set_tick_params(labelsize=tick_sz)
        ax.set_xlim(left, right)

        if not params["spectrum"]:
            ax.xaxis.set_major_formatter(FuncFormatter(date_format_hours))
            if params["end"].day - params["start"].day >= 1:
                ax.xaxis.set_major_formatter(FuncFormatter(date_format_days))

        if params["showtitle"]:
            text = (
                tr.stats.network,
                tr.stats.station,
                tr.stats.location,
                tr.stats.channel,
                tr.stats.starttime.isoformat(),
                tr.stats.endtime.isoformat(),
            )
            ax.annotate(
                "%s.%s.%s.%s %s %s UTC" % text,
                xy=(0.50, 1.10),
                xycoords="axes fraction",
                horizontalalignment="center",
                verticalalignment="top",
                fontsize=tick_sz,
                weight="bold",
            )

        if params["showscale"]:
            add_scale_bar(params, ax, tr.stats.channel, tick_sz)
    xaxis_name = "Freq" if params["spectrum"] else "Time"
    ax.set_xlabel(xaxis_name, fontsize=tick_sz, labelpad=20)
Jerome Touvier's avatar
Jerome Touvier committed
709
    plt.tight_layout(h_pad=tick_sz / 3.0)  # Adjust subplot + height padding
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
710
711

    logging.debug("Saving figure...")
Jerome Touvier's avatar
Jerome Touvier committed
712
713
    plt.savefig(img, format=params["imageformat"], transparent=False)
    plt.close()
Jerome Touvier's avatar
cleanup  
Jerome Touvier committed
714
715
716
717
    response = make_response(img.getvalue())
    response.mimetype = "image/" + params["imageformat"]
    logging.info(f"Response with plot created in {tictac(tic)} seconds.")
    return response