-
Notifications
You must be signed in to change notification settings - Fork 16
/
irisFetch.m
3044 lines (2707 loc) · 146 KB
/
irisFetch.m
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
classdef irisFetch
% IRISFETCH allows seamless access to data stored within the IRIS-DMC via FDSN services
%
% irisFetch Methods:
%
% irisFetch waveform retrieval Methods:
% Traces - retrieve sac-equivalent waveforms with channel metadata
% SACfiles - as Traces above, but saves directly to a SAC file.
%
% irisFetch FDSN station webservice Methods:
% Channels - retrieve metadata as an array of channels
% Stations - retrieve metadata as an array of stations
% Networks - retrieve metadata as an array of networks
%
% irisFetch FDSN event webservice Methods:
% Events - retrieve events parameters (such as origins and magnitudes) from a catalog
%
% irisFetch miscellaneous Methods:
% Resp - retrive RESP formatted response data from the irisws-resp service
% version - display the current version number
% connectToJar - attempt to connect to the required IRIS-WS JAR file
% runExamples - displays and runs some sample queries to the web service
% Trace2SAC - writes a trace structure to a SAC file
% SAC2Trace - reads one or more locally stored SAC files to a trace structure
%
% irisFetch requires version 2.0 or greater of the IRIS Web Services Library java jar
% for more details, click on 'connectToJar' above.
%
% For additional guidance, type help <method>, use irisFetch.runExamples, or check out
% the online manual http://www.iris.edu/dms/nodes/dmc/software/downloads/irisFetch.m/.
%
%see also JAVAADDPATH
% Celso Reyes, Rich Karstens
% IRIS-DMC
% February 2014
%{
*******************************************************************************
* Copyright (c) 2013 IRIS DMC supported by the National Science Foundation.
*
* This file is part of Iris Matlab Fetch (irisFetch).
*
* irisFetch is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* irisFetch is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* A copy of the GNU Lesser General Public License is available at
* <http://www.gnu.org/licenses/>.
******************************************************************************
%}
properties (Constant = true)
VERSION = '2.0.7'; % irisFetch version number
DATE_FORMATTER = 'yyyy-mm-dd HH:MM:SS.FFF'; %default data format, in ms
MIN_JAR_VERSION = '2.0.4'; % minimum version of IRIS-WS jar required for compatibility
VALID_QUALITIES = {'D','R','Q','M','B'}; % list of Qualities accepted by Traces
DEFAULT_QUALITY = 'B'; % default Quality for Traces
FETCHER_LIST = {'Traces','Stations','Events','Resp'}; % list of functions that fetch
forceDataAsDouble = true; %require that traces are returned as doubles regardless of original format
end %constant properties
properties (Constant = true, Hidden = true)
MS_IN_DAY = 86400000; % milliseconds in day
BASE_DATENUM = 719529; % Matlab startdate=0000-Jan-1 vs java's startdate=1970-Jan-1
SURROGATE_JAR = 'http://www.iris.edu/files/IRIS-WS/2/IRIS-WS-2.0-latest.jar';
M2J_MAP = containers.Map (...
{'java.util.Date',...
'java.lang.Double',...
'java.lang.Long',...
'java.lang.Integer',...
'java.lang.String',...
'boolean'},...
{@(x) java.util.Date(((datenum(x)-irisFetch.BASE_DATENUM) * irisFetch.MS_IN_DAY) + .5), ...%@(x) irisFetch.mdate2jdate(x) ,...
@(x) java.lang.Double(x),...
@(x) java.lang.Long(x),...
@(x) java.lang.Integer(x),...
@(x) x,...
@(x) x}...
); %details for MATLAB to JAVA conversions
appName = ['MATLAB:irisFetch/' irisFetch.VERSION]; %used as useragent of queries
recursionAssert = false; %check for recursions while parsing java into structs
FEDERATOR_TRIGGER = 'FEDERATED';
FEDERATOR_BASEURL = 'http://service.iris.edu/irisws/fedcatalog/1/';
FEDERATOR_LABELS = {'DATACENTER','RESPSERVICE','EVENTSERVICE','STATIONSERVICE','DATASELECTSERVICE','SACPZSERVICE'};
end %hidden constant properties
methods(Static)
function v = version()
v = irisFetch.VERSION;
end
function Trace2SAC(traces, writeDirectory, verbosity)
% irisFetch.Trace2SAC(traces, writeDirectory)
%
% Writes a trace structure to a SAC file within 'writeDirectory'
% All output SAC filenames are automatically generated.
%
% INPUTS
% traces: the Traces struct for writting to SAC file(s).
% writeDirectory: name of output directory
if ~exist('verbosity','var')
verbosity = false;
end
irisFetch.write_sac_out(writeDirectory, traces, verbosity);
end
function tr = SAC2Trace(file_dir_name)
% tr = irisFetch.SAC2Trace(file_dir_name)
%
% Reads in SAC file(s) into a Trace structure.
% NOTE: Only binary SAC files are supported at this time.
%
% INPUTS
% file_dir_name: Name of input file(s) or directory
% -If a directory is specified, then all files within that
% directory with the extension .sac or .SAC will be loaded.
% -Wildcard characters ('*' or '?') are valid.
%
% OUTPUTS
% tr: Trace structure, as returned by irisFetch.Traces
tr = irisFetch.read_sac_in(file_dir_name);
end
%% TRACE/DATASELECT related STATIC, PUBLIC routines
function SACfiles(network, station, location, channel, startDate, endDate, writeDirectory, varargin)
% irisFetch.SACfiles(network, station, location, channel, startDate, endDate, writeDirectory,...)
% As with irisFetch.Traces, but waveform data will be written out as SAC files
% to a directory specified by 'writeDirectory'
%
% The 'writeDirectory' parameter is mandatory. If 'writeDirectory' does not exist, then
% it will be created.
%
% NOTE: unlike the Traces method, no structures will be saved in your MATLAB workspace
% if this method is used.
%
% see irisFetch.Traces for more information on specifying channel identifier inputs
irisFetch.Traces(network, station, location, channel, startDate, endDate, ['WRITESAC:', writeDirectory], 'ASJAVA', varargin{:});
end
function ts = Traces(network, station, location, channel, startDate, endDate, varargin )
%irisFetch.Traces retrieves sac-equivalent waveform with channel metadata
% tr = irisFetch.Traces(network, station, location, channel, startDate, endDate)
% will use channel and date criteria to retrieve one or more seismic traces,
% which are stored as structures containing typical SAC-equivalent metadata.
%
% startDate and endDate must be formatted thusly:
% 'YYYY-MM-DD hh:mm:ss' or 'YYYY-MM-DD hh:mm:ss.sss'
%
% network, station, location, and channel all accept comma separated lists, as
% well as '*' and '?' wildcards.
%
% tr = irisFetch.Traces(..., quality) allows you to specify the data's quality,
% such as 'B' (which stands for "best"). This SEED quality code defines how data overlaps
% are processed by the dataselect service.
%
% tr = irisFetch.Traces(..., 'includePZ') will also retrieve poles and zeroes.
% These are the same poles/zeros as found from http://service.iris.edu/irisws/sacpz/1/
%
% tr = irisFetch.Traces(..., 'verbose') provides additional debugging information
%
% tr = irisFetch.Traces(..., usernameAndPassword ) allows authorized users to
% access restricted data. usernameAndPassword must be a cell containing the
% username and password.
% Sample:
% unamepwd = {'[email protected]', 'anonymous'}
%
% tr = irisFetch.Traces(...,'federated') first queries the
% fedcatalog service to determine the holdings from each
% datacenter that match the request. Then, irisFetch retrieves
% the traces from the datacenter. See additional FEDERATED note
% below.
%
% tr = irisFetch.Traces(..., urlbase) will allow traces to be read from an
% alternate data center. url base is only the first part of the web address. For
% example, the IRIS datacenter would be 'http://service.iris.edu/'. These
% settings are "sticky", so that all calls for waveform data or station metadata
% will go to that datacenter until a new one is specified.
%
% tr = irisFetch.Traces(..., 'WRITESAC:writeDir') will retrieve seismic traces
% and then write a SAC file to the directory specified by 'writeDir' for each
% trace structure. This method will also store the retrieved waveform data in
% the MATLAB workspace.
%
% ABOUT THE RETURNED TRACE
% The returned trace(s) will be a 1xN array of structs. Each struct contains
% fields with information pertaining to that specific trace, such as channel
% information, start & end times, units, etc.
%
% If the requested data does not exist, then an empty (1x0) trace struct will be
% returned. If the original data contains data gaps, then each continuous data
% segment will be returned as its own trace.
%
% ABOUT FEDERATED DATA
% When traces are received via the "federated" catalog, they
% are grouped by datacenter. The result will be a structure,
% containing fields with the name of the data center.
% Using a concrete example, if I request:
% tr = irisFetch.Traces('?R','A*','*','BHZ','2010-02-27 6:30:00', '2010-02-27 6:31:00','federated')
%
% irisFetch first queries the federator service located at:
% http://service.iris.edu/irisws/fedcatalog/1/
% which returns matches at three datacenters:
% 3 matches at BGR (http://eida.bgr.de)
% 9 matches at IRISDMC (http://ds.iris.edu)
% 4 matches at RESIF (http://www.resif.fr)
% it then retrieves each trace, one after the other. Placing
% them into a final structure which contains the data that was
% successfully retrieved:
% tr =
% BGR: [1x3 struct]
% IRISDMC: [1x7 struct]
% RESIF: [1x2 struct]
%
% * Side effect of retrieving data from other datacenters:
% The java library used by irisfetch remembers the last
% datacenter. So if you then try to retrieve data without the
% 'federated' method, it might search in the wrong center. To
% fix, either clear java or send a federated request that finds
% data at your specific datacenter.
%
% COMMON MANIPULATIONS:
%
% See a text representation of the start date to millisecond accuracy, from a trace tr:
% datestr(tr.startTime, 'yyyy-mm-dd HH:MM:SS.FFF')
%
% Scale the data, so that resulting values are in sensitivityUnits.
% tr.data = tr.data ./ tr.sensitivity; % this example works only for single trace
%
% EXAMPLES:
% Get 4 hours of data (timeseries + metdata) from a station:
% tr = irisFetch.Traces('IU','ANMO','10','BHZ','2010-02-27 06:30:00','2010-02-27 10:30:00')
%
% Get 3 channels (via wildcards), including response, for a 4-hour time period:
% ts = irisFetch.Traces('IU','ANMO','10','BH?','2010-02-27 06:30:00','2010-02-27 10:30:00','includePZ')
%
%
% Get data from all channels from a comma-separated list of stations:
% ts = irisFetch.Traces('IU','ANMO,ANTO,YSS','00','*','2010-02-27 06:30:00','2010-02-27 10:30:00')
%
% SEE ALSO datestr
if ~exist('edu.iris.dmc.extensions.fetch.TraceData','class')
irisFetch.connectToJar()
end
import edu.iris.dmc.*
safeLocation = @(x) strrep(x,' ','-');
str2webdate = @(x) strrep(x,' ', 'T'); % 'YYYY-MM-DD hh:mm:ss' -> 'YYYY-MM-DDThh:mm:ss'
web2strdate = @(x) strrep(x,'T',' ');
opts = setOptions(varargin);
dbPrint = irisFetch.getDBfprintf(opts.verbosity);
% startDateStr = irisFetch.makeDateStr(startDate);
% endDateStr = irisFetch.makeDateStr(endDate);
location = safeLocation(location);
tracedata = edu.iris.dmc.extensions.fetch.TraceData();
tracedata.setAppName(irisFetch.appName);
tracedata.setVerbosity(opts.verbosity);
tracedata = setBaseUrl(tracedata, opts.newbase);
if ~opts.useFederator
ts = getTheTraces(network, station, location, channel, startDate, endDate, opts);
else
ts = getResultsFromFederator(network, station, location, channel, startDate, endDate, opts);
end
return
% ---------------------------------------------------------------
% END TRACES: MAIN
% ===============================================================
function td = setBaseUrl(td, newbase)
if ~isempty(newbase)
if newbase(end) ~= '/'; newbase = [newbase, '/']; end
dbPrint ('Using services at base: %s\n', newbase);
end
end
function [svc, url, mykey] = parseFederatedHeaderLine(A)
[svc,A] = splitString(A,'=');
assert(ismember(svc, irisFetch.FEDERATOR_LABELS), '%s isn''t a known label\n',svc);
switch svc
case 'DATACENTER'
[mykey, url] = splitString(A,',');
otherwise
mykey = '';
url = A;
end
end
function [s1, s2] = splitString(s, tok)
[s1, s2] = strtok(s, tok);
if ~isempty(s2)
s2(1)='';
end
end
function tracesByDatacenter = getResultsFromFederator(network, station, location, channel, startDateStr, endDateStr, opts)
tracesByDatacenter = struct;
stD = str2webdate(irisFetch.makeDateStr(startDateStr));
edD = str2webdate(irisFetch.makeDateStr(endDateStr));
q = sprintf('net=%s&sta=%s&loc=%s&cha=%s&start=%s&end=%s',...
network, station, location, channel, stD, edD);
fullquery = [irisFetch.FEDERATOR_BASEURL, 'query?', q];
dbPrint('Fetching federator catalog results :: ');
fedResults = urlread(fullquery);
dbPrint('%d Bytes\n',numel(fedResults));
dbPrint(fedResults)
assignin('base','fedResults',fedResults);
a = textscan(fedResults, '%s %s %s %s %s %s');
nets = a{1}; stas = a{2}; locs = a{3}; chas = a{4};
stts = a{5}; edts = a{6};
isHeader = cellfun(@isempty, stas);
starttimer = tic;
dstic = [];
for row = 1 : numel(nets);
if isHeader(row)
[svc, url, newDataCenter] = parseFederatedHeaderLine(nets{row});
if newDataCenter
flush()
currDataCenter = newDataCenter;
fprintf('Fetching data from %s (%s)\n',...
newDataCenter, url)
end
switch svc
case 'DATASELECTSERVICE'
tracedata.setWAVEFORM_URL(url)
case 'SACPZSERVICE'
tracedata.setSACPZ_URL(url)
case 'STATIONSERVICE'
tracedata.setSTATION_URL(url)
end
dbPrint('[%s] : %-10s > %s\n',currDataCenter, svc, url');
else
network = nets{row};
station = stas{row};
location = locs{row};
channel = chas{row};
startDateStr = web2strdate(stts{row});
endDateStr = web2strdate(edts{row});
%q = sprintf('net=%s&sta=%s&loc=%s&cha=%s&start=%s&end=%s',...
% network, station, location, channel, startDateStr, endDateStr);
dbPrint('query : %s\n', q);
tmp = getTheTraces(network, station, location, channel, startDateStr, endDateStr, opts);
if exist('ts','var')
ts = [ts tmp];
else
ts = tmp;
end
end
end
flush()
fprintf('DONE at %s (Total time:%3.1f seconds)\n',datestr(now),toc(starttimer));
function flush()
if exist('ts','var')
tracesByDatacenter.(currDataCenter) = ts;
fprintf('Received %d channels in %3.1f seconds\n',...
numel(ts), toc(dstic) );
clear ts
end
dstic = tic;
end
end
function opts = getUserOptions(opts, argList)
% extracts getsacpz, verbosity, authorize, quality, username, and userpwd
% Parameters are handled "intelligently" so that [paramname, paramval] pairs
% aren't necessry
for n=1:numel(argList)
param = argList{n};
switch class(param)
case 'cell'
assert(numel(param)==2 && all(cellfun(@ischar, param)),...
'A cell parameter is assumed to contain credentials. eg. {''[email protected]'',''anonymous''}.');
[opts.username, opts.userpwd] = deal(param{:});
opts.authorize = true;
case 'char'
switch upper(param)
case irisFetch.VALID_QUALITIES
opts.quality = param;
case {'INCLUDEPZ'}
opts.getsacpz = true;
case {'VERBOSE'}
opts.verbosity = true;
case {'ASJAVA'}
opts.convertToMatlab = false;
case {'SACONLY'}
opts.convertToMatlab = false;
opts.getsacpz = false;
opts.saveSAC = true;
opts.writeDirectory = pwd;
case {irisFetch.FEDERATOR_TRIGGER}
opts.useFederator = true;
otherwise
if length(param)>7 && strcmpi(param(1:7),'http://')
% set the bases
opts.newbase = param;
elseif length(param) >= 8 && strcmpi(param(1:8),'WRITESAC')
% expecting 'WRITESAC' or
% 'WRITESAC:full/directory/path'
opts.saveSAC = true;
if length(param) <9
opts.writeDirectory = pwd;
else
opts.writeDirectory = param(10:end);
end
else
error('IRISFETCH:Trace:unrecognizedParameter',...
'The text you included as an optional parameter did not parse to either a qualitytype (D,R,Q,M,B) or ''INCLUDEPZ'' or ''VERBOSE'' or a service base URL');
end
end
otherwise
error('IRISFETCH:Trace:unrecognizedParameter',...
'The optional parameter wasn''t recognized. %s', class(param));
end
end
if opts.verbosity %cannot use dbPrint here, because this function gets called BEFORE dbPrint declared
disp({'spz:',opts.getsacpz,'vb:',opts.verbosity,...
'auth:',opts.authorize,'qual:',opts.quality,...
'un&pw:',opts.username,repmat('*',size(opts.userpwd))});
end
end % extractAdditionalArguments
function ts = getTheTraces(N, S, L, C, startDateStr, endDateStr, opts)
traces=[];
startDateStr = irisFetch.makeDateStr(startDateStr);
endDateStr = irisFetch.makeDateStr(endDateStr);
try
if opts.authorize
dbPrint('traces = tracedata.fetchTraces("%s", "%s", "%s", "%s", "%s", "%s", ''%s'', %d, "%s", "%s")\n',...
N, S, L, C, startDateStr, endDateStr, opts.quality, opts.getsacpz, opts.username, repmat('*',size(opts.userpwd)));
traces = tracedata.fetchTraces(N, S, L, C, ...
startDateStr, endDateStr, opts.quality, opts.getsacpz, opts.username, opts.userpwd);
else
dbPrint('traces = tracedata.fetchTraces("%s", "%s", "%s", "%s", "%s", "%s", ''%s'', %d)\n',...
N, S, L, C, startDateStr, endDateStr, opts.quality, opts.getsacpz);
traces = tracedata.fetchTraces(N, S, L, C, ...
startDateStr, endDateStr, opts.quality, opts.getsacpz); %db removed (;)
end
dbPrint('tracedata.fetchTraces successfully completed, resulting in %d traces before converting\n', numel(traces));
catch je
% Debug messages:
dbPrint('An [%s] exception occurred in irisFetch.getTheTraces() but was caught\n full text follows:\nmessage:\n%s\n\n', je.identifier,je.message) %db
%disp(je.cause); %db
%disp(je.stack); %db
switch je.identifier
case 'MATLAB:Java:GenericException'
if any(strfind(je.message,'URLNotFoundException'));
error('IRISFETCH:Trace:URLNotFoundException',...
'Trace found no requested data and returned the following error:\n%s',...
je.message);
end
if any(strfind(je.message,'java.io.IOException: edu.iris.dmc.service.UnauthorizedAccessException'));
error('IRISFETCH:Trace:UnauthorizedAccessException',...
'Invalid Username and Password combination\n');
end
if any(strfind(je.message,'NoDataFoundException'));
if opts.verbosity
warning('IRISFETCH:Trace:URLNotFoundException',...
'Trace found no requested data and returned the following error:\n%s',...
je.message);
end
end
otherwise
fprintf('Exception occured in IRIS Web Services Library: %s\n', je.message);
rethrow(je)
end
end
if opts.saveSAC
irisFetch.write_sac_out(opts.writeDirectory, traces, opts.verbosity);
end
if opts.convertToMatlab
ts = irisFetch.convertTraces(traces);
else
ts = traces;
warning('in-house experimental: returning the java traces instead of a matlab struct.');
end
clear traces
end %function getTheTraces
function opts = setOptions(args)
opts.getsacpz = false;
opts.verbosity = false;
opts.authorize = false;
opts.quality = irisFetch.DEFAULT_QUALITY;
opts.username = '';
opts.userpwd = '';
opts.newbase = '';
opts.useFederator = false;
opts.writeDirectory = '';
opts.convertToMatlab = true;
opts.saveSAC = false;
opts = getUserOptions(opts, args);
end
end % Traces
%% STATION related STATIC, PUBLIC routines
function [channelStructure, urlParams] = Channels(detailLevel, varargin)
%irisFetch.Channels retrieves station metadata from IRIS-DMC as an array of channels
% s = irisFetch.Channels(DETAIL,NETWORK,STATION,LOCATION,CHANNEL) retrieves
% station metadata from the IRIS-DMC into an array of channels. DETAIL is one of
% 'CHANNEL', or 'RESPONSE' and should be explicitly declared. DETAIL defaults to 'CHANNEL'
% Network, station, location, and channel parameters are passed directly to the
% java library, so both comma-separated lists and wildcards (? and *) are accepted.
%
% All five parameters are required for all queries, but may be wildcarded by
% using '' for their values.
%
% [s, myParams] = irisFetch.Channels( ... ) also returns the URL parameters that
% were used to make the query.
%
% irisFetch.Channels(..., 'BASEURL',alternateURL) specifies an alternate base URL
% to query. By default queries go to: http://service.iris.edu/fdsnws/station/1/
%
% s = irisFetch.Channels( ... , paramName, value [, ...]]) allows any number of
% parameter-value pairs to be included in the selection criteria. Valid
% parameter names are listed in help for irisFetch.Networks
%
% Example: to retrieve channel-level BHZ metadata from any station named ANMO:
% s = irisFetch.Channels('channel','*','ANMO','*','BHZ')
%
% Note: This function effectively deprecates irisFetch.flattenToChannel
%
%See also Networks, Stations
if isempty(detailLevel)
detailLevel = 'CHANNEL';
end
assert(ismember(upper(detailLevel),{'CHANNEL','RESPONSE'}),...
'To retrieve channels, the detailLevel must be either ''CHANNEL'' or ''RESPONSE''');
[channelStructure, urlParams] = irisFetch.Networks(detailLevel, varargin{:});
if ~isempty(channelStructure)
channelStructure = irisFetch.flattenToChannel(channelStructure);
end
end
function [stationStructure, urlParams] = Stations(detailLevel, varargin)
%irisFetch.Stations retrieves station metadata from IRIS-DMC as an array of stations
% s = irisFetch.Stations(DETAIL,NETWORK,STATION,LOCATION,CHANNEL) retrieves
% station metadata from the IRIS-DMC into an array of stations. DETAIL is one
% of 'STATION','CHANNEL', or 'RESPONSE' and should be explicitly declared.
% DETAIL defaults to 'STATION'
%
% Network, station, location, and channel parameters are passed directly to the
% java library, so both comma-separated lists and wildcards (? and *) are accepted.
%
% All five parameters are required for all queries, but may be wildcarded by
% using '' for their values.
%
% [s, myParams] = irisFetch.Stations( ... ) also returns the URL parameters that
% were used to make the query.
%
% irisFetch.Stations(..., 'BASEURL',alternateURL) specifies an alternate base URL
% to query. By default queries go to: http://service.iris.edu/fdsnws/station/1/
%
% s = irisFetch.Stations( ... , paramName, value [, ...]]) allows any number of
% parameter-value pairs to be included in the selection criteria. Valid
% parameter names are listed in help for irisFetch.Networks
%
% Example: to retrieve channel-level metadata, stored in an array of stations:
% s = irisFetch.Stations('channel','IU','A*','*','BHZ')
%
% Note: This function effectively deprecates the irisFetch.flattenToStation
%
%See also Networks, Channels
if isempty(detailLevel)
detailLevel = 'STATION';
end
assert(ismember(upper(detailLevel),{'STATION','CHANNEL','RESPONSE'}),...
'To retrieve stations, the detailLevel must be either ''STATION'', ''CHANNEL'', or ''RESPONSE''');
[stationStructure, urlParams] = irisFetch.Networks(detailLevel,varargin{:});
if ~isempty(stationStructure)
stationStructure = irisFetch.flattenToStation(stationStructure);
end
end
function [networkStructure, urlParams] = Networks(detailLevel, network, station, location, channel, varargin)
%irisFetch.Stations retrieves station metadata from IRIS-DMC as an array of networks
% s = irisFetch.Networks(DETAIL,NETWORK,STATION,LOCATION,CHANNEL), retrieves
% station metadata into an array of networks. These parameters are required for
% all queries, but may be wildcarded by using '' for their values. Network,
% station, location, and channel parameters are passed directly to the java
% library, so both comma-separated lists and wildcards (? and *) are accepted.
% Detail is one of 'NETWORK','STATION','CHANNEL', or 'RESPONSE' and should be
% explicitly declared. Defaults to 'NETWORK'
%
% [s, myParams] = irisFetch.Networks( ... ) also returns the URL parameters that
% were used to make the query.
%
% irisFetch.Networks(..., 'BASEURL',alternateURL) specifies an alternate base URL
% to query. By default queries go to: http://service.iris.edu/fdsnws/station/1/
%
% s = irisFetch.Networks( ... , paramName, value [, ...]]) allows any number of
% parameter-value pairs to be included in the selection criteria. See the list
% below.
%
% Valid parameters are listed below. For detailed descriptions of their effect
% and use, consult the station webservice webpage, available at:
% http://service.iris.edu/fdsnws/station/1/
%
% PARAMETER LIST (for IRIS-WS-2.0.0.jar)
% The following take time values, of the format 'yyyy-mm-dd HH:MM:SS'
% 'StartTime', 'EndTime', 'StartBefore', 'EndBefore'
% 'StartAfter', 'EndAfter' 'UpdatedAfter'
%
% The following take values in degrees and work together to define a search box
% 'MinimumLatitude', 'MaximumLatitude', 'MinimumLongitude','MaximumLongitude'
%
% These params take values in degrees to define a search disk / annular region
% 'Latitude', 'Longitude', 'MinimumRadius','MaximumRadius'
%
% Other params, that accept true or false (no quotes)
% 'IncludeAvailability','MatchTimeSeries', 'IncludeRestricted'
%
% CONVENIENCE PARAMETERS
% 'boxcoordinates' : [minLat, maxLat, minLon, maxLon]
% % use NaN as a wildcard
% 'radialcoordinates' : 1x4 double :
% [Lat, Lon, MaxRadius, MinRadius]
% % MinRadius is optional
%
% To retrieve similar information, but organize as an array of either channels
% or stations, use irisFetch.Channels or irisFetch.Stations respectively.
%
%SEE ALSO Channels, Stations
import edu.iris.dmc.*
outputLevel = '';
service = []; % will be a java service object
crit = []; % will be a java criteria object
j_networks = []; % will be the returned java networks
%if ~exist('edu.iris.dmc.criteria.StationCriteria','class')
if ~exist('criteria.StationCriteria','class')
irisFetch.connectToJar()
end
if isempty(detailLevel)
detailLevel = 'NETWORK';
end
verifyArguments(nargin);
setOutputLevel();
connectToStationService();
setCriteria();
fetchTheStations();
networkStructure=irisFetch.parser_for_IRIS_WS_2_0_0(j_networks);
if nargout == 2
urlParams = crit.toUrlParams;
end
return
% -------------------------------------------------------------
% END STATIONS: MAIN
% =============================================================
function verifyArguments(nArgs)
if nArgs==1 && strcmpi(detailLevel,'help')
disp('HELP request recognized, but not implemented');
return
elseif nArgs < 5
error('not enough arguments.%d',nArgs);
end
end %verifyArguments
function setOutputLevel()
try
outputLevel = edu.iris.dmc.criteria.OutputLevel.(upper(detailLevel));
catch je
switch je.identifier
case 'MATLAB:undefinedVarOrClass'
error('IRISFETCH:NoIrisWSJarInstalled',...
['The necessary IRIS-WS java library was not recognized or found. ',...
'Please ensure it is on your javaclasspath']);
case 'MATLAB:subscripting:classHasNoPropertyOrMethod'
error('IRISFETCH:invalidOutputLevel',...
'The selected outputLevel [''%s''] was not recognized.',...
upper(detailLevel));
otherwise
rethrow(je);
end
end
end % setOutputLevel
function connectToStationService()
serviceManager = edu.iris.dmc.service.ServiceUtil.getInstance();
serviceManager.setAppName(['MATLAB:irisFetch/' irisFetch.version()])
setBaseUrlFromParameterList();
removeParameter('BASEURL');
return
% - - - - - - - - - - - - - - -
function setBaseUrlFromParameterList()
baseUrl = getParameter('BASEURL');
if ~isempty(baseUrl)
service = serviceManager.getStationService(baseUrl);
else
service = serviceManager.getStationService();
end % setBaseUrlFromParameterList
end
end %connectToStationService()
function removeParameter(s)
[UNUSED_VARIABLE, idx] = getParameter(s); %#ok<ASGLU>
varargin(idx * 2 -1 : idx* 2) = [];
end
function [p, i] = getParameter(s)
i = find(strcmpi(parameterNames(),s),1,'first');
p = parameterValues();
p = p(i);
end
function pn = parameterNames()
pn = varargin(1:2:end);
end
function pv = parameterValues()
pv = varargin(2:2:end);
end
function setCriteria()
crit = edu.iris.dmc.criteria.StationCriteria;
%crit = edu.iris.dmc.criteria.StationCriteria;
%----------------------------------------------------------
% Deal with the Station/Network/Channel/Location parameters
% These are treated separately, as they're "add" & not "set"
% Each may handle multiple strings (as a cell array)
%----------------------------------------------------------
crit = irisFetch.addCriteria(crit, network, 'addNetwork');
crit = irisFetch.addCriteria(crit, station, 'addStation');
crit = irisFetch.addCriteria(crit, location,'addLocation');
crit = irisFetch.addCriteria(crit, channel, 'addChannel');
crit = irisFetch.setCriteria(crit, varargin);
end %setCriteria
function fetchTheStations()
try
j_networks = service.fetch(crit, outputLevel);
catch je
if strfind(je.message,'ServiceNotSupportedException')
error('IRISFETCH:ServiceNotSupportedByLibrary',...
'The IRIS-WS java library version doesn''t support the requested station service version');
elseif strfind(je.message,'NoDataFoundException')
warning('IRISFETCH:NoDataFoundException','No data was found that matched your criteria');
j_networks = [];
else
rethrow(je)
end
end %catch
end %fetchTheStations
end %Networks
%% EVENT related STATIC, PUBLIC routines
function [events, urlParams] = Events(varargin)
%irisFetch.Events retrieves event data from the IRIS-DMC
% ev = irisFetch.Events(param, value [, ...]) retrieves event data from the
% IRIS-DMC database as a matlab structure. An arbitrary number of
% parameter-value pairs may be specified in order to narrow down the search
% results.
%
% [ev, myParams] = irisFetch.Events( ... ) also returns the URL parameters that
% were used to make the query.
%
% irisFetch.Events(..., 'BASEURL',alternateURL) specifies an alternate base URL
% to query. By default queries go to: http://service.iris.edu/fdsnws/event/1/
%
% Usable parameters are listed below. For detailed descriptions of their effect
% and use, consult the webservice webpage for events, available at:
%
% http://service.iris.edu/fdsnws/event/1/
%
% Examples:
%
% Retrieve event parameters regarding earthquakes of a specific size and location:
% ev = irisFetch.Events('MinimumMagnitude',6.0,...
% 'minimumLatitude',45,'maximumLatitude', 60,...
% 'minimumLongitude', -150,'maximumLongitude', -90)
%
%PARAMETER LIST (for IRIS-WS-2.0.0.jar)
% contributor, endTime, eventId, fetchLimit, latitude, longitude, magnitudeType,
% maximumDepth, maximumLatitude, maximumLongitude, maximumMagnitude,
% minimumDepth, minimumLatitude, minimumLongitude, minimumMagnitude,
% minimumRadius, maximumRadius, offset, startTime updatedAfter
%
%CONVENIENCE PARAMETERS
% 'boxcoordinates' : [minLat, maxLat, minLon, maxLon] % use NaN as a wildcard
% 'radialcoordinates' : [Lat, Lon, MaxRadius, MinRadius] % MinRadius is optional
%
%NOTE: Any parameter-value pair that is not listed here will be passed along to
% the Event Service. this is to accomodate other datacenters that may have
% specialized request parameters.
import edu.iris.dmc.*
% import edu.iris.dmc.*
%if ~exist('edu.iris.dmc.criteria.EventCriteria','class')
if ~exist('criteria.EventCriteria','class')
irisFetch.connectToJar()
end
%serviceManager = ws.service.ServiceUtil.getInstance();
serviceManager = edu.iris.dmc.service.ServiceUtil.getInstance();
serviceManager.setAppName(['MATLAB:irisFetch/' irisFetch.version()]);
indexOffsetOfBASEURL=find(strcmpi(varargin(1:2:end),'BASEURL'),1,'first') * 2;
if ~isempty(indexOffsetOfBASEURL)
baseURL = varargin{indexOffsetOfBASEURL};
end
if exist('baseURL','var')
varargin(indexOffsetOfBASEURL-1:indexOffsetOfBASEURL) = [];
service = serviceManager.getEventService(baseURL);
else
service = serviceManager.getEventService();
end
%crit = ws.criteria.EventCriteria;
crit = criteria.EventCriteria;
crit = irisFetch.setCriteria(crit, varargin);
if nargout == 2
urlParams = crit.toUrlParams;
end
disp('fetching...')
try
j_events = service.fetch(crit);
catch er
if any(strfind(er.message,'NoDataFoundException')) || any(strfind(er.message,'No Content'))
warning('IRISFETCH:NoDataFoundException','No data was found that matched your criteria');
events=[];
return
end
rethrow(er);
end
fprintf('\n\n%d events found *************\n\n',j_events.size);
disp('parsing into MATLAB structures')
events=irisFetch.parser_for_IRIS_WS_2_0_0(j_events);
% v2.0 uses Preferred, while original code uses "Primary"
end
%% RESPONSE related STATIC, PLUBLIC routines
function [respstructures, urlparams] = Resp(network, station, location, channel, starttime, endtime)
% retrieve the RESP information into a character string.
% net, sta, loc, and cha are all required.
% channels and locations may be wildcarded using either ? or *
% starttime and endtime options may be ignored by using [] instead of a time.
import edu.iris.dmc.*
%crit = edu.iris.dmc.criteria.RespCriteria();
crit = criteria.RespCriteria();
crit.setNetwork(network);
crit.setStation(station);
crit.setLocation(location);
crit.setChannel(channel);
if ~isempty(starttime)
crit.setStartTime(irisFetch.mdate2jdate(starttime));
end
if ~isempty(endtime)
crit.setEndTime(irisFetch.mdate2jdate(endtime));
end
urlparams = char(crit.toUrlParams());
serviceManager = edu.iris.dmc.service.ServiceUtil.getInstance();
baseUrl = 'http://service.iris.edu/irisws/resp/1/';
serviceManager.setAppName(['MATLAB:irisFetch/' irisFetch.version()]);
service = serviceManager.getRespService(baseUrl);
respstructures= char(service.fetch(crit));
end
%% HELPER ROUTINES
function connectToJar(isSilent)
%irisFetch.connectToJar connects to the jar for this MATLAB session
% irisFetch.connectToJar() searches the javaclasspath for the
% IRIS-WS jar file. If it does not exist, then it will try to access the latest
% jar over the internet. If it cannot connect, it will error.
%
% irisFetch requires version 2.0.2 or greater of the IRIS Web Services Library java jar,
% available from:
%
% http://www.iris.edu/files/IRIS-WS/2/
%
% This jar file must be added to your MATLAB path, which may be done
% in a variety of ways. One common way is to include a javaaddpath
% statement in the startup.m file. For more details, consult MATLAB's
% documentation for 'Bringing Java Classes and Methods into MATLAB
% Workspace'.
%
% SEE ALSO javaaddpath
assert(usejava('jvm'),'IRISFETCH:jvmNotRunning','irisFetch requires Java to run.');
isSilent = nargin>0 && strcmpi(isSilent,'silent');
if exist('edu.iris.dmc.extensions.fetch.TraceData','class');
return
end
if ~isSilent
disp('please add the latest IRIS-WS.jar file to your javaclasspath.');
fprintf('Available here: %s\n',irisFetch.SURROGATE_JAR);
disp('ex. javaaddpath(''/usr/local/somewhere/IRIS-WS.jar'');');
end
javaaddpath(irisFetch.SURROGATE_JAR);
if ~exist('edu.iris.dmc.extensions.fetch.TraceData','class');
error('irisFetch:noDefaultJar',...
'Unable to access the default jar. Please download and add the latest IRIS-WS-JAR to your javaclasspath.');
end
end
function runExamples()
delay=1; % seconds
codeToExecute={
'% Retrieve 1 hr of all ''HZ'' channels from all locations at station ANMO for net IU'
'traces = irisFetch.Traces(''IU'',''ANMO'',''*'',''?HZ'',''2010-02-27 06:30:00'',''2010-02-27 07:30:00'')'
'% Notice that multiple traces were retrieved, look at the first trace.'
'tr = traces(1)'
'% -------- plot the data from the first trace, and then label the plot ------'
'sampletimes=linspace(tr.startTime,tr.endTime,tr.sampleCount); %calculate the time of each sample'
'whos(''sampletimes'')'
'plot(sampletimes,tr.data);'
'legendDetails = sprintf(''%s-%s-%s'', tr.network, tr.station, tr.location, tr.channel)'
'legend(legendDetails);'
'title(''Simple plot'');'
'datetick;'
' '
'% next, get some station data (same data, at different levels of detail'
'n = irisFetch.Networks(''Response'',''IU'',''ANMO'','''',''BHZ'',''baseurl'',''http://service.iris.edu/fdsnws/station/1/'')';
's = irisFetch.Stations(''Response'',''IU'',''ANMO'','''',''BHZ'')';
'c = irisFetch.Channels(''Response'',''IU'',''ANMO'','''',''BHZ'')';
' '
'% retrieve station data using other search parameters'
'arcticNetworkList = irisFetch.Networks(''Station'','''','''','''','''',''minimumlatitude'',66.3)';
'netNames = {arcticNetworkList.NetworkCode}'
' '
'% retrieve event data'
' ev = irisFetch.Events(''minimummagnitude'',8.0)'
' ev(1)'
' ev = irisFetch.Events(''starttime'',''2010-02-27'',''endtime'',''2010-02-28 12:00:00'',''catalog'',''ISC'',''includeallorigins'',true,''includeallmagnitudes'',true)'
' '
'% retrieve the RESP formatted response for a station'
'irisFetch.Resp(''IU'',''ANMO'',''00'',''BHZ'',now,now)'
};
for n=1:numel(codeToExecute)
disp(codeToExecute{n});
eval(codeToExecute{n});
pause(delay);
end
clear traces tr n s c ev
end %fn runExamples
end % static methods
methods(Static, Hidden=true)
function channelList = flattenToChannel(networkTree)
%irisFetch.flattenToChannel flattens the structure returned by irisFetch.Networks
% flatStruct = irisFetch.flattenToChannel(networkTree) takes the hierarchy
% returned by irisFetch.Networks, and returns a 1xN array of channels (channel
% epochs, technically).
%
% flatStruct is an array containing ALL channel epochs.
assert(isa(networkTree,'struct'),'Cannot Flatten a non-structure');