-
Notifications
You must be signed in to change notification settings - Fork 80
/
api.py
2541 lines (2179 loc) · 89.7 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
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
49
50
51
52
53
54
55
56
57
58
59
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
157
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
189
190
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
368
369
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
571
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import copy
import datetime
import itertools
import logging
import os
import glob
import traceback
try:
import cPickle
except:
import pickle as cPickle
import math
import sys
from logbook import Logger, StreamHandler
import sys
from sqlalchemy import create_engine, func, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from sqlalchemy.sql.expression import func
import numpy as np
import pandas as pd
import xarray as xr
from . import DBConfigNotFoundError
from .msnoise_table_def import Filter, Job, Station, Config, DataAvailability
def get_logger(name, loglevel=None, with_pid=False):
"""
Returns the current configured logger or configure a new one.
"""
# if with_pid:
# log_fmt='%(asctime)s msnoise [pid %(process)d] '\
# '[%(levelname)s] %(message)s'
# else:
# log_fmt='%(asctime)s msnoise [%(levelname)s] %(message)s'
# logger = logging.getLogger(name)
# # Remove any inherited StreamHandler to avoid duplicate lines
# for h in logger.handlers:
# if isinstance(h, logging.StreamHandler):
# logger.removeHandler(h)
# handler = logging.StreamHandler(sys.stderr)
# handler.setFormatter(
# logging.Formatter(fmt=log_fmt, datefmt='%Y-%m-%d %H:%M:%S'))
# logger.addHandler(handler)
# logger.setLevel(loglevel)
# logger.propagate = False
if with_pid:
log_fmt="{record.time} msnoise [pid {record.process}]" \
"[{record.level_name}]: {record.message}"
else:
log_fmt="{record.time} msnoise [{record.level_name}]: {record.message}"
StreamHandler(sys.stdout, format_string=log_fmt,
level=loglevel).push_application()
logger = Logger(name)
return logger
def get_engine(inifile=None):
"""Returns the a SQLAlchemy Engine
:type inifile: str
:param inifile: The path to the db.ini file to use. Defaults to os.cwd() +
db.ini
:rtype: :class:`sqlalchemy.engine.Engine`
:returns: An :class:`~sqlalchemy.engine.Engine` Object
"""
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
dbini = read_db_inifile(inifile)
if dbini.tech == 1:
engine = create_engine('sqlite:///%s' % dbini.hostname, echo=False,
connect_args={'check_same_thread': False})
elif dbini.tech == 2:
engine = create_engine('mysql+pymysql://%s:%s@%s/%s'
% (dbini.username, dbini.password,
dbini.hostname, dbini.database),
echo=False, poolclass=NullPool,
connect_args={'connect_timeout': 15})
elif dbini.tech == 3:
engine = create_engine('postgresql+psycopg2://%s:%s@%s/%s'
% (dbini.username, dbini.password,
dbini.hostname, dbini.database),
echo=False, poolclass=NullPool,
connect_args={'connect_timeout': 15})
return engine
def connect(inifile=None):
"""Establishes a connection to the database and returns a Session object.
:type inifile: string
:param inifile: The path to the db.ini file to use. Defaults to os.cwd() +
db.ini
:rtype: :class:`sqlalchemy.orm.session.Session`
:returns: A :class:`~sqlalchemy.orm.session.Session` object, needed for
many of the other API methods.
"""
from sqlalchemy.orm import sessionmaker
if not inifile:
inifile = os.path.join(os.getcwd(), 'db.ini')
engine = get_engine(inifile)
Session = sessionmaker(bind=engine)
return Session()
def create_database_inifile(tech, hostname, database, username, password,
prefix=""):
"""Creates the db.ini file based on supplied parameters.
:type tech: int
:param tech: The database technology used: 1=sqlite 2=mysql
:type hostname: string
:param hostname: The hostname of the server (if tech=2) or the name of the
sqlite file if tech=1)
:type database: string
:param database: The database name
:type username: string
:param username: The user name
:type password: string
:param prefix: The prefix to use for all tables
:type prefix: string
:param password: The password of `user`
:return: None
"""
f = open(os.path.join(os.getcwd(), 'db.ini'), 'wb')
cPickle.dump([tech, hostname, database, username, password, prefix], f,
protocol=2)
f.close()
def read_db_inifile(inifile=None):
"""Reads the parameters from the db.ini file.
:type inifile: string
:param inifile: The path to the db.ini file to use. Defaults to os.cwd() +
db.ini
:rtype: tuple
:returns: tech, hostname, database, username, password
"""
IniFile = collections.namedtuple('IniFile', ['tech', 'hostname',
'database', 'username', 'password', 'prefix'])
if not inifile:
inifile = os.path.join(os.getcwd(), 'db.ini')
try:
f = open(inifile, 'rb')
#except FileNotFoundError: # This is better but only for python3
except IOError:
raise DBConfigNotFoundError(
"No db.ini file in this directory, please run "
"'msnoise db init' in this folder to initialize it as "
"an MSNoise project folder.")
try:
# New ini file with prefix support
tech, hostname, database, username, password, prefix = cPickle.load(f)
except:
# Old ini file without prefix
tech, hostname, database, username, password = cPickle.load(f)
prefix = ""
f.close()
return IniFile(tech, hostname, database, username, password, prefix)
# CONFIG
def get_config(session, name=None, isbool=False, plugin=None):
"""Get the value of one or all config bits from the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type name: str
:param name: The name of the config bit to get. If omitted, a dictionnary
with all config items will be returned
:type isbool: bool
:param isbool: if True, returns True/False for config `name`. Defaults to
False
:type plugin: str
:param plugin: if provided, gives the name of the Plugin config to use. E.g.
if "Amazing" is provided, MSNoise will try to load the "AmazingConfig"
entry point. See :doc:`plugins` for details.
:rtype: str, bool or dict
:returns: the value for `name` or a dict of all config values
"""
if plugin:
import pkg_resources
for ep in pkg_resources.iter_entry_points(
group='msnoise.plugins.table_def'):
if ep.name.replace("Config", "") == plugin:
table = ep.load()
else:
table = Config
if name:
config = session.query(table).filter(table.name == name).first()
if config is not None:
if isbool:
if config.value in [True, 'True', 'true', 'Y', 'y', '1', 1]:
config = True
else:
config = False
else:
config = config.value
else:
config = ''
else:
config = {}
configs = session.query(Config).all()
for c in configs:
config[c.name] = c.value
return config
def update_config(session, name, value, plugin=None):
"""Update one config bit in the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type name: str
:param name: The name of the config bit to set.
:type value: str
:param value: The value of parameter `name`. Can also be NULL if you don't
want to use this particular parameter.
:type plugin: str
:param plugin: if provided, gives the name of the Plugin config to use. E.g.
if "Amazing" is provided, MSNoise will try to load the "AmazingConfig"
entry point. See :doc:`plugins` for details.
"""
if plugin:
import pkg_resources
for ep in pkg_resources.iter_entry_points(
group='msnoise.plugins.table_def'):
if ep.name.replace("Config", "") == plugin:
table = ep.load()
else:
table = Config
config = session.query(table).filter(table.name == name).first()
if "NULL" in value:
config.value = None
else:
config.value = value
session.commit()
return
def get_params(session):
"""Get config parameters from the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:returns: a Param class containing the parameters
"""
# TODO: this could be populated automatically from defauts iff defaults
# would mention types
from obspy.core.util.attribdict import AttribDict
from .default import default
s = session
params = AttribDict()
for name in default.keys():
itemtype = default[name].type
if itemtype is bool:
params[name] = get_config(s, name, isbool=True)
else:
params[name] = itemtype(get_config(s, name))
# TODO remove reference to goal_sampling_rate
params.goal_sampling_rate = params.cc_sampling_rate
params.min30 = params.corr_duration * params.goal_sampling_rate
params.components_to_compute = get_components_to_compute(s)
params.components_to_compute_single_station = get_components_to_compute_single_station(s)
params.all_components = np.unique(params.components_to_compute_single_station + \
params.components_to_compute)
if params.mov_stack.count(',') == 1:
params.mov_stack = [params.mov_stack, ]
else:
params.mov_stack = params.mov_stack
return params
# FILTERS PART
def get_filters(session, all=False, ref=None):
"""Get Filters from the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type all: bool
:param all: Returns all filters from the database if True, or only filters
where `used` = 1 if False (default)
:rtype: list of :class:`~msnoise.msnoise_table_def.declare_tables.Filter`
:returns: a list of Filter
"""
if ref:
filter = session.query(Filter).filter(Filter.ref == ref).first()
return filter
if all:
filters = session.query(Filter).all()
else:
filters = session.query(Filter).filter(Filter.used == True).all()
return filters
def update_filter(session, ref, low, mwcs_low, high, mwcs_high,
mwcs_wlen, mwcs_step, used):
"""Updates or Insert a new Filter in the database.
.. seealso:: :class:`msnoise.msnoise_table_def.declare_tables.Filter`
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type ref: int
:param ref: The id of the Filter in the database
:type low: float
:param low: The lower frequency bound of the Whiten function (in Hz)
:type high: float
:param high: The upper frequency bound of the Whiten function (in Hz)
:type mwcs_low: float
:type mwcs_low: The lower frequency bound of the linear regression done in
MWCS (in Hz)
:type mwcs_high: float
:type mwcs_high: The upper frequency bound of the linear regression done in
WCS (in Hz)
:type mwcs_wlen: float
:param mwcs_wlen: Window length (in seconds) to perform MWCS
:type mwcs_step: float
:param mwcs_step: Step (in seconds) of the windowing procedure in MWCS
:type used: bool
:param used: Is the filter activated for the processing
"""
filter = session.query(Filter).filter(Filter.ref == ref).first()
if filter is None:
filter = Filter()
filter.low = low
filter.high = high
filter.mwcs_low = mwcs_low
filter.mwcs_high = mwcs_high
filter.mwcs_wlen = mwcs_wlen
filter.mwcs_step = mwcs_step
filter.used = used
session.add(filter)
else:
filter.low = low
filter.high = high
filter.mwcs_low = mwcs_low
filter.mwcs_high = mwcs_high
filter.mwcs_wlen = mwcs_wlen
filter.mwcs_step = mwcs_step
filter.used = used
session.commit()
return
# NETWORK AND STATION
def get_networks(session, all=False):
"""Get Networks from the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type all: bool
:param all: Returns all networks from the database if True, or only
networks at least one station has `used` = 1 if False (default)
:rtype: list of str
:returns: a list of network codes
"""
if all:
networks = session.query(Station).group_by(Station.net).all()
else:
networks = session.query(Station).filter(Station.used == True).\
group_by(Station.net)
return [net.net for net in networks]
def get_stations(session, all=False, net=None, format="raw"):
"""Get Stations from the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type all: bool
:param all: Returns all stations from the database if True, or only
stations where `used` = 1 if False (default)
:type net: str
:param net: if set, limits the stations returned to this network
:rtype: list of :class:`msnoise.msnoise_table_def.declare_tables.Station`
:returns: list of :class:`~msnoise.msnoise_table_def.declare_tables.Station`
"""
q = session.query(Station)
if all:
if net is not None:
stations = q.filter(Station.net == net).order_by(Station.net).\
order_by(Station.sta)
else:
stations = q.order_by(Station.net).order_by(Station.sta).all()
else:
stations = q.filter(Station.used == True).order_by(Station.net).\
order_by(Station.sta)
if net is not None:
stations = stations.filter(Station.net == net).\
order_by(Station.net).order_by(Station.sta)
if format == "raw":
return stations
if format == "seed_id":
output = []
for sta in stations:
if sta.used_location_codes is None:
location_codes = []
else:
location_codes = sta.used_location_codes.split(",")
if sta.used_channel_names is None:
channels = []
else:
channels = []
for i, chan in enumerate(sta.used_channel_names.split(",")):
if chan.count("?"):
for comp in ["Z", "N", "E", "1", "2"]:
channels.append(chan.replace("?", comp))
else:
channels.append(chan)
for loc in location_codes:
for chan in channels:
output.append("%s.%s.%s.%s" % (sta.net, sta.sta, loc, chan))
return output
def get_station(session, net, sta):
"""Get one Station from the database.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type net: str
:param net: the network code
:type sta: str
:param sta: the station code
:rtype: :class:`msnoise.msnoise_table_def.declare_tables.Station`
:returns: a :class:`~msnoise.msnoise_table_def.declare_tables.Station` Object
"""
station = session.query(Station).filter(Station.net == net).\
filter(Station.sta == sta).first()
return station
def update_station(session, net, sta, X, Y, altitude, coordinates='UTM',
instrument='N/A', used=1):
"""Updates or Insert a new Station in the database.
.. seealso :: :class:`msnoise.msnoise_table_def.declare_tables.Station`
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type net: str
:param net: The network code of the Station
:type sta: str
:param sta: The station code
:type X: float
:param X: The X coordinate of the station
:type Y: float
:param Y: The Y coordinate of the station
:type altitude: float
:param altitude: The altitude of the station
:type coordinates: str
:param coordinates: The coordinates system. "DEG" is WGS84 latitude/
longitude in degrees. "UTM" is expressed in meters.
:type instrument: str
:param instrument: The instrument code, useful with PAZ correction
:type used: bool
:param used: Whether this station must be used in the computations.
"""
station = session.query(Station).filter(Station.net == net).\
filter(Station.sta == sta).first()
if station is None:
station = Station(net, sta, X, Y, altitude, coordinates, instrument,
used)
session.add(station)
else:
station.X = X
station.Y = Y
station.altitude = altitude
station.coordinates = coordinates
station.instrument = instrument
station.used = used
session.commit()
return True
def get_station_pairs(session, used=None, net=None):
"""Returns an iterator over all possible station pairs.
If auto-correlation is configured in the database, returns N*N pairs,
otherwise returns N*(N-1)/2 pairs.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type used: bool, int
:param used: Select only stations marked used if False (default) or all
stations present in the database if True
:type net: str
:param net: Network code to filter for the pairs.
:rtype: iterable
:returns: An iterable of :class:`~msnoise.msnoise_table_def.declare_tables.Station` object
pairs
"""
stations = get_stations(session, all=False, net=net)
if len(get_config(session, name="components_to_compute_single_station")):
return itertools.combinations_with_replacement(stations, 2)
else:
return itertools.combinations(stations, 2)
def check_stations_uniqueness(session, station):
"""
:param session:
:param station:
:return:
"""
# if the station is net.sta.loc, nothing to do
if station.count(".") == 2:
return station
logging.info("It seems you're voluntarily missing the location code for"
" \"%s\". We'll handle this automatically, if there are no "
"conflicts." % station)
net, sta = station.split(".")
locs = get_station(session, net, sta).locs()
if len(locs) != 1:
logging.info("There are more than 1 location codes for this station: "
"%s" % locs)
return station
station += ".%s" % locs[0]
logging.info("Found %s to be the unique solution for this station" % station)
return station
def get_interstation_distance(station1, station2, coordinates="DEG"):
"""Returns the distance in km between `station1` and `station2`.
.. warning:: Currently the stations coordinates system have to be the same!
:type station1: :class:`~msnoise.msnoise_table_def.declare_tables.Station`
:param station1: A Station object
:type station2: :class:`~msnoise.msnoise_table_def.declare_tables.Station`
:param station2: A Station object
:type coordinates: str
:param coordinates: The coordinates system. "DEG" is WGS84 latitude/
longitude in degrees. "UTM" is expressed in meters.
:rtype: float
:returns: The interstation distance in km
"""
from obspy.geodetics import gps2dist_azimuth
if coordinates == "DEG":
dist, azim, bazim = gps2dist_azimuth(station1.Y, station1.X,
station2.Y, station2.X)
return dist / 1.e3
else:
dist = np.hypot(float(station1.X - station2.X),
float(station1.Y - station2.Y)) / 1.e3
return dist
# DATA AVAILABILITY
def update_data_availability(session, net, sta, loc, chan, path, file, starttime,
endtime, data_duration, gaps_duration,
samplerate):
"""
Updates a DataAvailability object in the database
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type net: str
:param net: The network code of the Station
:type sta: str
:param sta: The station code
:type chan: str
:param chan: The component (channel)
:type path: str
:param path: The full path to the folder containing the file
:type file: str
:param file: The name of the file
:type starttime: datetime.datetime
:param starttime: Start time of the file
:type endtime: datetime.datetime
:param endtime: End time of the file
:type data_duration: float
:param data_duration: Cumulative duration of available data in the file
:type gaps_duration: float
:param gaps_duration: Cumulative duration of gaps in the file
:type samplerate: float
:param samplerate: Sample rate of the data in the file (in Hz)
"""
data = session.query(DataAvailability).\
filter(DataAvailability.path == path). \
filter(DataAvailability.file == file).\
filter(DataAvailability.net == net).\
filter(DataAvailability.sta == sta). \
filter(DataAvailability.loc == loc). \
filter(DataAvailability.chan == chan).first()
if data is None:
flag = "N"
data = DataAvailability(net, sta, loc, chan, path, file, starttime, endtime,
data_duration, gaps_duration, samplerate, flag)
session.add(data)
toreturn = 1
else:
modified = False
for item in ['net', 'sta', 'loc', 'chan', 'path', 'starttime',
'endtime', 'data_duration', 'gaps_duration', 'samplerate']:
if eval("data.%s != %s" % (item, item)):
modified = True
break
if modified:
data.net = net
data.sta = sta
data.loc = loc
data.chan = chan
data.path = path
data.starttime = starttime
data.endtime = endtime
data.data_duration = data_duration
data.gaps_duration = gaps_duration
data.samplerate = samplerate
data.flag = "M"
toreturn = -1
else:
toreturn = 0
session.commit()
return toreturn
def get_new_files(session):
"""
Returns the files marked "N"ew or "M"odified in the database
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:rtype: list
:returns: list of :class:`~msnoise.msnoise_table_def.declare_tables.DataAvailability`
"""
files = session.query(DataAvailability).\
filter(DataAvailability.flag != 'A').\
order_by(DataAvailability.starttime).all()
return files
def get_data_availability(session, net=None, sta=None, loc=None, chan=None,
starttime=None, endtime=None):
"""
Returns the :class:`~msnoise.msnoise_table_def.declare_tables.DataAvailability` objects
for specific `net`, `sta`, `starttime` or `endtime`
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type net: str
:param net: Network code
:type sta: str
:param sta: Station code
:type starttime: datetime.datetime, datetime.date
:param starttime: Start time of the search
:type endtime: datetime.datetime, datetime.date
:param endtime: End time of the search
:rtype: list
:returns: list of :class:`~msnoise.msnoise_table_def.declare_tables.DataAvailability`
"""
from sqlalchemy.sql.expression import func
if not starttime:
data = session.query(DataAvailability).\
filter(DataAvailability.net == net).\
filter(DataAvailability.sta == sta). \
filter(DataAvailability.loc == loc). \
filter(DataAvailability.chan == chan).all()
elif not net:
data = session.query(DataAvailability).\
filter(DataAvailability.starttime <= endtime).\
filter(DataAvailability.endtime >= starttime).all()
else:
data = session.query(DataAvailability).\
filter(DataAvailability.net == net).\
filter(DataAvailability.sta == sta). \
filter(DataAvailability.loc == loc). \
filter(func.DATE(DataAvailability.starttime) <= endtime.date()).\
filter(func.DATE(DataAvailability.endtime) >= starttime.date()).all()
if not len(data):
data = session.query(DataAvailability). \
filter(DataAvailability.sta == "MULTIPLEX"). \
filter(func.DATE(DataAvailability.starttime) <= endtime.date()).\
filter(
func.DATE(DataAvailability.endtime) >= starttime.date()).all()
return data
def mark_data_availability(session, net, sta, flag):
"""
Updates the flag of all
:class:`~msnoise.msnoise_table_def.declare_tables.DataAvailability` objects matching
`net.sta` in the database
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type net: str
:param net: Network code
:type sta: str
:param sta: Station code
:type flag: str
:param flag: Status of the DataAvailability object: New, Modified or
Archive. Values accepted are {'N', 'M', 'A'}
"""
logging.debug("Updating: %s %s to flag=%s" %(net, sta, flag))
da = DataAvailability.__table__
stmt = da.update().where(da.c.sta==sta).where(da.c.net==net).\
values(flag=flag)
session.execute(stmt)
session.commit()
def count_data_availability_flags(session):
"""
Count the number of :class:`~msnoise.msnoise_table_def.declare_tables.DataAvailability`,
grouped by `flag`
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:rtype: list
:returns: list of [count, flag] pairs
"""
from sqlalchemy.sql.expression import func
return session.query(func.count(DataAvailability.flag),
DataAvailability.flag).\
group_by(DataAvailability.flag).all()
# Jobs
# TODO bad doing this here!
import time
def update_job(session, day, pair, jobtype, flag, commit=True, returnjob=True,
ref=None):
"""
Updates or Inserts a new :class:`~msnoise.msnoise_table_def.declare_tables.Job` in the
database.
:type day: str
:param day: The day in YYYY-MM-DD format
:type pair: str
:param pair: the name of the pair (EXAMPLE?)
:type jobtype: str
:param jobtype: CrossCorrelation (CC) or dt/t (DTT) Job?
:type flag: str
:param flag: Status of the Job: "T"odo, "I"n Progress, "D"one.
:type commit: bool
:param commit: Whether to directly commit (True, default) or not (False)
:type returnjob: bool
:param returnjob: Return the modified/inserted Job (True, default) or not
(False)
:rtype: :class:`~msnoise.msnoise_table_def.declare_tables.Job` or None
:returns: If returnjob is True, returns the modified/inserted Job.
"""
from sqlalchemy import text
if ref:
job = session.query(Job).filter(text("ref=:ref")).params(ref=ref).first()
else:
job = session.query(Job)\
.filter(text("day=:day"))\
.filter(text("pair=:pair"))\
.filter(text("jobtype=:jobtype"))\
.params(day=day, pair=pair, jobtype=jobtype).first()
if job is None:
job = Job(day, pair, jobtype, 'T')
session.add(job)
else:
job.flag = flag
job.lastmod = datetime.datetime.utcnow()
if commit:
session.commit()
if returnjob:
return job
def massive_insert_job(jobs):
"""
Routine to use a low level function to insert much faster a list of
:class:`~msnoise.msnoise_table_def.declare_tables.Job`. This method uses the Engine
directly, no need to pass a Session object.
:type jobs: list
:param jobs: a list of :class:`~msnoise.msnoise_table_def.declare_tables.Job` to insert.
"""
engine = get_engine()
with engine.connect() as conn:
conn.execute(
Job.__table__.insert(),
jobs)
try:
conn.commit()
except:
pass
def massive_update_job(session, jobs, flag="D"):
"""
Routine to use a low level function to update much faster a list of
:class:`~msnoise.msnoise_table_def.declare_tables.Job`. This method uses the Job.ref
which is unique.
:type session: Session
:param session: the database connection object
:type jobs: list or tuple
:param jobs: a list of :class:`~msnoise.msnoise_table_def.declare_tables.Job` to update.
:type flag: str
:param flag: The destination flag.
"""
updated = False
mappings = [{'ref': job.ref, 'flag': flag} for job in jobs]
while not updated:
try:
session.bulk_update_mappings(Job, mappings)
session.commit()
updated = True
except:
time.sleep(np.random.random())
pass
return
def is_next_job(session, flag='T', jobtype='CC'):
"""
Are there any :class:`~msnoise.msnoise_table_def.declare_tables.Job` in the database,
with flag=`flag` and jobtype=`type`
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type jobtype: str
:param jobtype: CrossCorrelation (CC) or dt/t (DTT) Job?
:type flag: str
:param flag: Status of the Job: "T"odo, "I"n Progress, "D"one.
:rtype: bool
:returns: True if at least one :class:`~msnoise.msnoise_table_def.declare_tables.Job`
matches, False otherwise.
"""
job = session.query(Job).\
filter(Job.jobtype == jobtype).\
filter(Job.flag == flag).first()
if job is None:
return False
else:
return True
def get_next_job(session, flag='T', jobtype='CC', limit=99999):
"""
Get the next :class:`~msnoise.msnoise_table_def.declare_tables.Job` in the database,
with flag=`flag` and jobtype=`jobtype`. Jobs of the same `type` are grouped
per day. This function also sets the flag of all selected Jobs to "I"n
progress.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type jobtype: str
:param jobtype: CrossCorrelation (CC) or dt/t (DTT) Job?
:type flag: str
:param flag: Status of the Job: "T"odo, "I"n Progress, "D"one.
:rtype: list
:returns: list of :class:`~msnoise.msnoise_table_def.declare_tables.Job`
"""
from sqlalchemy import update
tmp = []
while not len(tmp):
jobs = session.query(Job).filter(Job.jobtype == jobtype).\
filter(Job.flag == flag).\
filter(Job.day == session.query(Job).
filter(Job.jobtype == jobtype).
filter(Job.flag == flag).first().day).\
limit(limit).with_for_update()
tmp = jobs.all()
refs = [_.ref for _ in tmp]
q = update(Job).values({"flag":"I"}).where(Job.ref.in_(refs))
session.execute(q)
# jobs.update({Job.flag: 'I'})
session.commit()
return tmp
def get_dvv_jobs(session, flag='T', jobtype='DVV', limit=99999):
from sqlalchemy import update
tmp = []
while not len(tmp):
jobs = session.query(Job).filter(Job.jobtype == jobtype). \
filter(Job.flag == flag). \
limit(limit).with_for_update()
tmp = jobs.all()
refs = [_.ref for _ in tmp]
q = update(Job).values({"flag": "I"}).where(Job.ref.in_(refs))
session.execute(q)
# jobs.update({Job.flag: 'I'})
session.commit()
return tmp
def is_dtt_next_job(session, flag='T', jobtype='DTT', ref=False):
"""
Are there any DTT :class:`~msnoise.msnoise_table_def.declare_tables.Job` in the database,
with flag=`flag` and jobtype=`jobtype`. If `ref` is provided, checks if a
DTT "REF" job is present.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type jobtype: str
:param jobtype: CrossCorrelation (CC) or dt/t (DTT) Job?
:type flag: str
:param flag: Status of the Job: "T"odo, "I"n Progress, "D"one.
:type ref: bool
:param ref: Whether to check for a REF job (True) or not (False, default)
:rtype: bool
:returns: True if at least one Job matches, False otherwise.
"""
q = session.query(Job.ref).\
filter(Job.flag == flag).\
filter(Job.jobtype == jobtype)
if ref:
job = q.filter(Job.pair == ref).filter(Job.day == 'REF').count()
else:
job = q.filter(Job.day != 'REF').count()
if job == 0:
return False
else:
return True
def get_dtt_next_job(session, flag='T', jobtype='DTT'):
"""
Get the next DTT :class:`~msnoise.msnoise_table_def.declare_tables.Job` in the database,
with flag=`flag` and jobtype=`jobtype`. Jobs are then grouped per station
pair. This function also sets the flag of all selected Jobs to "I"n
progress.
:type session: :class:`sqlalchemy.orm.session.Session`
:param session: A :class:`~sqlalchemy.orm.session.Session` object, as
obtained by :func:`connect`
:type jobtype: str
:param jobtype: CrossCorrelation (CC) or dt/t (DTT) Job?
:type flag: str
:param flag: Status of the Job: "T"odo, "I"n Progress, "D"one.