-
Notifications
You must be signed in to change notification settings - Fork 11
/
nll_locator.cpp
1505 lines (1164 loc) · 40.5 KB
/
nll_locator.cpp
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
/***************************************************************************
* Copyright (C) by ETHZ/SED *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as published*
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program 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 Affero General Public License for more details. *
* *
* Developed by gempa GmbH *
***************************************************************************/
#define SEISCOMP_COMPONENT NLLocator
#define EXTERN_MODE
#include "nll_locator.h"
extern "C" {
#include "GridLib.h"
#include "ran1/ran1.h"
#include "velmod.h"
#include "GridMemLib.h"
#include "calc_crust_corr.h"
#include "phaseloclist.h"
#include "otime_limit.h"
#include "NLLocLib.h"
}
#include <seiscomp/logging/log.h>
#include <seiscomp/core/strings.h>
#include <seiscomp/system/environment.h>
#include <seiscomp/datamodel/utils.h>
#include <seiscomp/datamodel/comment.h>
#include <seiscomp/math/geo.h>
#include <seiscomp/math/vector3.h>
#include <seiscomp/utils/files.h>
#include <seiscomp/utils/replace.h>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <set>
ADD_SC_PLUGIN(
"Locator implementation using NonLinLoc by Anthony Lomax "
"(http://alomax.free.fr/nlloc/)",
"Jan Becker, gempa GmbH",
0, 7, 2
)
using namespace std;
using namespace Seiscomp::Core;
using namespace Seiscomp::DataModel;
namespace Seiscomp {
namespace Seismology {
namespace Plugins {
namespace {
// Global region class defining a rectangular region
// by latmin, lonmin, latmax, lonmax.
struct GlobalRegion : public NLLocator::Region {
GlobalRegion() {
isEmpty = true;
}
bool isGlobal() const { return isEmpty; }
bool init(const Config::Config &config, const std::string &prefix) {
vector<string> region;
try { region = config.getStrings(prefix + "region"); }
catch ( ... ) {}
if ( region.empty() )
isEmpty = true;
else {
isEmpty = false;
// Parse region
if ( region.size() != 4 ) {
SEISCOMP_ERROR("%s: expected 4 values in region definition, got %d",
prefix.c_str(), (int)region.size());
return false;
}
if ( !fromString(latMin, region[0]) ||
!fromString(lonMin, region[1]) ||
!fromString(latMax, region[2]) ||
!fromString(lonMax, region[3]) ) {
SEISCOMP_ERROR("%s: invalid region value(s)", prefix.c_str());
return false;
}
}
return true;
}
bool isInside(double lat, double lon) const {
if ( isEmpty ) return true;
double len, dist;
if ( lat < latMin || lat > latMax ) return false;
len = lonMax - lonMin;
if ( len < 0 )
len += 360.0;
dist = lon - lonMin;
if ( dist < 0 )
dist += 360.0;
return dist <= len;
}
bool isEmpty;
double latMin, lonMin;
double latMax, lonMax;
};
// Class that implementes the SIMPLE transformation as documented
// here: http://alomax.free.fr/nlloc/
// It expects the region to be a grid
struct SimpleTransformedRegion : public NLLocator::Region {
bool init(const Config::Config &config, const std::string &prefix) {
vector<string> list;
try { list = config.getStrings(prefix + "origin"); }
catch ( ... ) {
SEISCOMP_ERROR("%s: missing origin definition for simple transformation",
prefix.c_str());
return false;
}
if ( list.size() != 2 ) {
SEISCOMP_ERROR("%s: expected 2 values in origin definition for simple transformation, got %d",
prefix.c_str(), (int)list.size());
return false;
}
if ( !fromString(lat0, list[0]) ||
!fromString(lon0, list[1]) ) {
SEISCOMP_ERROR("%s: invalid origin value(s)", prefix.c_str());
return false;
}
try {
angle = config.getDouble(prefix + "rotation");
}
catch ( ... ) {
SEISCOMP_ERROR("%s: missing rotation definition for simple transformation",
prefix.c_str());
return false;
}
try { list = config.getStrings(prefix + "region"); }
catch ( ... ) {
SEISCOMP_ERROR("%s: missing region definition for simple transformation",
prefix.c_str());
return false;
}
// Parse region
if ( list.size() != 4 ) {
SEISCOMP_ERROR("%s: expected 4 values in region definition for simple transformation, got %d",
prefix.c_str(), (int)list.size());
return false;
}
if ( !fromString(xmin, list[0]) ||
!fromString(ymin, list[1]) ||
!fromString(xmax, list[2]) ||
!fromString(ymax, list[3]) ) {
SEISCOMP_ERROR("%s: invalid region value(s)", prefix.c_str());
return false;
}
return true;
}
bool isInside(double lat, double lon) const {
double lonDiff = lon - lon0;
if ( lonDiff < -180 )
lonDiff += 360;
else if ( lonDiff > 180 )
lonDiff -= 360;
double x = Math::Geo::deg2km(lonDiff) * cos(deg2rad(lat));
double y = Math::Geo::deg2km(lat - lat0);
double cosa = cos(-deg2rad(angle));
double sina = sin(-deg2rad(angle));
double tx = x * cosa - y * sina;
double ty = y * cosa + x * sina;
if ( tx < xmin ) return false;
if ( ty < ymin ) return false;
if ( tx > xmax ) return false;
if ( ty > ymax ) return false;
return true;
}
double lat0, lon0;
double angle;
double xmin, xmax;
double ymin, ymax;
};
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void makeUpper(std::string &dest, const std::string &src) {
dest = src;
for ( size_t i = 0; i < src.size(); ++i )
dest[i] = toupper(src[i]);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
double timeError(const TimeQuantity &t, double defaultValue) {
try {
return quantityUncertainty(t);
}
catch ( ... ) {
return defaultValue;
}
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void replaceWeight(vector<string> &observations, const std::string staCode,
double weight) {
for ( vector<string>::iterator it = observations.begin();
it != observations.end(); ++it ) {
size_t pos = it->find(' ');
if ( pos == string::npos ) continue;
if ( it->compare(0, pos, staCode) != 0 ) continue;
pos = it->rfind(' ');
if ( pos == string::npos ) continue;
it->replace(pos+1, it->size(), Core::toString(weight)+"\n");
break;
}
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
double normalizeAz(double az) {
if ( az < 0 )
az += 360.0;
else if ( az >= 360.0 )
az -= 360.0;
return az;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
double normalizeLon(double lon) {
while ( lon < -180.0 ) lon += 360.0;
while ( lon > 180.0 ) lon -= 360.0;
return lon;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
std::string stationName(const Seiscomp::DataModel::Pick *pick, const std::string& rule)
{
struct Resolver : public Seiscomp::Util::VariableResolver {
Resolver(const Seiscomp::DataModel::Pick &pick)
: _pick(pick) {}
bool resolve(std::string& variable) const {
if ( variable == "NET" )
variable = _pick.waveformID().networkCode();
else if ( variable == "STA" )
variable = _pick.waveformID().stationCode();
else if ( variable == "LOC" )
variable = _pick.waveformID().locationCode();
else
return false;
return true;
}
const Seiscomp::DataModel::Pick &_pick;
};
return Seiscomp::Util::replace(rule, Resolver(*pick), "@", "@", "");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
} // private namespace
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
REGISTER_LOCATOR(NLLocator, "NonLinLoc");
NLLocator::IDList NLLocator::_allowedParameters;
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
NLLocator::NLLocator() {
_name = "NonLinLoc";
_publicIDPattern = "NLL.@time/%Y%m%d%H%M%S.%f@.@id@";
if ( _allowedParameters.empty() ) {
_allowedParameters.push_back("CONTROL");
_allowedParameters.push_back("LOCGRID");
_allowedParameters.push_back("LOCGAU");
_allowedParameters.push_back("LOCGAU2");
_allowedParameters.push_back("LOCELEVCORR");
_allowedParameters.push_back("LOCSEARCH");
_allowedParameters.push_back("LOCMETH");
}
_defaultPickError = 0.5;
_fixedDepthGridSpacing = 0.1;
_allowMissingStations = true;
_enableSEDParameters = false;
_enableNLLOutput = true;
_enableNLLSaveInput = true;
_SEDdiffMaxLikeExpectTag = "SED.diffMaxLikeExpect";
_SEDqualityTag = "SED.quality";
// Set allowed parameters to unset
for ( IDList::iterator it = _allowedParameters.begin();
it != _allowedParameters.end(); ++it ) {
_parameters[*it] = "";
}
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
NLLocator::~NLLocator() {}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool NLLocator::init(const Config::Config &config) {
Environment *env = Environment::Instance();
try {
_publicIDPattern = config.getString("NonLinLoc.publicID");
}
catch ( ... ) {
_publicIDPattern = "NLL.@time/%Y%m%d%H%M%S.%f@.@id@";
}
try {
_outputPath = env->absolutePath(config.getString("NonLinLoc.outputPath"));
}
catch ( ... ) {
_outputPath = "/tmp/sc3.nll";
}
if ( !Util::pathExists(_outputPath) ) {
if ( ! Util::createPath(_outputPath) ) {
SEISCOMP_ERROR("NonLinLoc.outputPath: failed to create path %s", _outputPath.c_str());
return false;
}
}
if ( _outputPath.size() > 0 ) {
if ( _outputPath[_outputPath.size()-1] != '/' )
_outputPath += '/';
}
try {
_controlFilePath = env->absolutePath(config.getString("NonLinLoc.controlFile"));
/*
if ( !Util::fileExists(_controlFilePath) ) {
SEISCOMP_ERROR("NonLinLoc.controlFile: file %s does not exist",
_controlFilePath.c_str());
return false;
}
*/
}
catch ( ... ) {
_controlFilePath = "";
}
_currentProfile = NULL;
bool result = true;
_profileNames.clear();
try { _profileNames = config.getStrings("NonLinLoc.profiles"); }
catch ( ... ) {}
for ( IDList::iterator it = _profileNames.begin();
it != _profileNames.end(); ) {
Profile prof;
string prefix = string("NonLinLoc.profile.") + *it + ".";
prof.name = *it;
try { prof.earthModelID = config.getString(prefix + "earthModelID"); }
catch ( ... ) {}
try { prof.methodID = config.getString(prefix + "methodID"); }
catch ( ... ) {
prof.methodID = "NonLinLoc";
}
try { prof.tablePath = env->absolutePath(config.getString(prefix + "tablePath")); }
catch ( ... ) {}
try { prof.stationNameFormat = config.getString(prefix + "stationNameFormat"); }
catch ( ... ) { prof.stationNameFormat = "@STA@"; }
if ( prof.tablePath.empty() ) {
SEISCOMP_ERROR("NonLinLoc.profile.%s: none or empty tablePath", it->c_str());
it = _profileNames.erase(it);
result = false;
continue;
}
string regionType;
try {
makeUpper(regionType, config.getString(prefix + "transform"));
}
catch ( ... ) {
regionType = "GLOBAL";
}
if ( regionType == "GLOBAL" )
prof.region = new GlobalRegion;
else if ( regionType == "SIMPLE" )
prof.region = new SimpleTransformedRegion;
if ( prof.region == NULL ) {
SEISCOMP_ERROR("NonLinLoc.profile.%s: invalid transformation: %s",
it->c_str(), regionType.c_str());
it = _profileNames.erase(it);
result = false;
continue;
}
if ( !prof.region->init(config, prefix) ) {
SEISCOMP_ERROR("NonLinLoc.profile.%s: invalid region parameters", it->c_str());
it = _profileNames.erase(it);
result = false;
continue;
}
try {
prof.controlFile = env->absolutePath(config.getString(prefix + "controlFile"));
}
catch ( ... ) {}
if ( prof.controlFile.empty() )
prof.controlFile = _controlFilePath;
if ( !Util::fileExists(prof.controlFile) ) {
SEISCOMP_ERROR("NonLinLoc.profile.%s.controlFile: file %s does not exist",
it->c_str(), prof.controlFile.c_str());
it = _profileNames.erase(it);
result = false;
continue;
}
_profiles.push_back(prof);
++it;
}
_profileNames.insert(_profileNames.begin(), "automatic");
try {
_enableNLLOutput = config.getBool("NonLinLoc.saveIntermediateOutput");
}
catch ( ... ) {
_enableNLLOutput = true;
}
try {
_enableNLLSaveInput = config.getBool("NonLinLoc.saveInput");
}
catch ( ... ) {
_enableNLLSaveInput = true;
}
try {
_defaultPickError = config.getDouble("NonLinLoc.defaultPickError");
}
catch ( ... ) {
_defaultPickError = 0.5;
}
try {
_fixedDepthGridSpacing = config.getDouble("NonLinLoc.fixedDepthGridSpacing");
}
catch ( ... ) {
_fixedDepthGridSpacing = 0.1;
}
try {
_allowMissingStations = config.getBool("NonLinLoc.allowMissingStations");
}
catch ( ... ) {
_allowMissingStations = true;
}
try {
_enableSEDParameters = config.getBool("NonLinLoc.enableSEDParameters");
}
catch ( ... ) {
_enableSEDParameters = false;
}
try {
_SEDqualityTag = config.getString("NonLinLoc.commentSEDQuality");
}
catch ( ... ) {
_SEDqualityTag = "SED.quality";
}
try {
_SEDdiffMaxLikeExpectTag = config.getString("NonLinLoc.commentSEDDiffMaxLikeExpect");
}
catch ( ... ) {
_SEDdiffMaxLikeExpectTag = "SED.diffMaxLikeExpect";
}
updateProfile("");
return result;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
NLLocator::IDList NLLocator::parameters() const {
return _allowedParameters;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
string NLLocator::parameter(const string &name) const {
ParameterMap::const_iterator it = _parameters.find(name);
if ( it != _parameters.end() )
return it->second;
return "";
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool NLLocator::setParameter(const string &name,
const string &value) {
ParameterMap::iterator it = _parameters.find(name);
if ( it == _parameters.end() )
return false;
it->second = value;
return true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
NLLocator::IDList NLLocator::profiles() const {
return _profileNames;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void NLLocator::setProfile(const string &name) {
if ( find(_profileNames.begin(), _profileNames.end(), name) ==
_profileNames.end() )
return;
if ( name == "automatic" )
updateProfile("");
else
updateProfile(name);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int NLLocator::capabilities() const {
return FixedDepth | DistanceCutOff;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Origin* NLLocator::locate(PickList &pickList) {
_lastWarning = "";
if ( pickList.empty() )
throw LocatorException("Empty observation set");
if ( _currentProfile == NULL ) {
throw GeneralException("No profile set");
}
if ( _controlFile.empty() ) {
throw GeneralException("Invalid control file");
}
SEISCOMP_DEBUG("requested earth model: %s", _currentProfile->earthModelID.c_str());
string earthModelPath, stationNameFormat;
bool globalMode = false;
earthModelPath = _currentProfile->tablePath;
stationNameFormat = _currentProfile->stationNameFormat;
globalMode = _currentProfile->region->isGlobal();
if ( earthModelPath.empty() ) {
if ( _profileNames.empty() )
throw GeneralException("No earth model configured");
else
throw GeneralException("Wrong earth model set");
}
TextLines obs, params;
std::vector<string> observationIDs;
// copy user set parameters to param strings
for ( ParameterMap::iterator it = _parameters.begin();
it != _parameters.end(); ++it )
if ( !it->second.empty() )
params.push_back(it->first + " " + it->second);
PickList usedPicks;
// create observation buffer
for ( PickList::iterator it = pickList.begin();
it != pickList.end(); ++it )
{
Pick *pick = it->pick.get();
double weight = it->flags & F_TIME?1.0:0.0;
SensorLocation *sloc = getSensorLocation(pick);
if ( sloc == NULL ) {
if ( _allowMissingStations ) {
// Append a new line to the warning message
if ( !_lastWarning.empty() )
_lastWarning += "\n";
_lastWarning += "Sensor location ";
_lastWarning += pick->waveformID().networkCode() + "." +
pick->waveformID().stationCode() + "." +
pick->waveformID().locationCode() + " is not available and ignored";
continue;
}
else {
throw StationNotFoundException(
(string("station ") + pick->waveformID().networkCode() +
"." + pick->waveformID().stationCode() +
" not found").c_str()
);
}
}
usedPicks.push_back(*it);
// create the LOCSRCE entries
params.push_back(string("LOCSRCE ") +
stationName(pick, stationNameFormat) +
" LATLON " +
toString(sloc->latitude()) + " " +
toString(sloc->longitude()) + " 0 " +
toString(sloc->elevation()*0.001));
stringstream ss;
ss << setprecision(2);
ss.setf(ios_base::scientific, ios_base::floatfield);
ss // station code
<< left << setw(10) << stationName(pick, stationNameFormat)
<< internal << setw(0) << " "
// instrument
<< "? "
// component
<< (pick->waveformID().channelCode().size() > 2
?
pick->waveformID().channelCode().substr(pick->waveformID().channelCode().size()-1)
:
"?"
) << " "
// P phase onset (i, e)
<< "? "
// phase descriptor
<< pick->phaseHint().code() << " "
// first motion
<< "? "
// date
<< pick->time().value().toString("%Y%m%d") << " "
// hour Minute
<< pick->time().value().toString("%H%M") << " "
// seconds
<< pick->time().value().toString("%S.%4f") << " "
// error type
<< "GAU "
// error magnitude
<< timeError(pick->time(), _defaultPickError) << " "
// coda duration
<< -1.0 << " "
// amplitude
<< -1.0 << " "
// period
<< -1.0 << " "
// priorWt
<< weight << endl;
// NOTE: The weight must be the last value otherwise the method "replaceWeight"
// needs to be changed.
obs.push_back(ss.str());
}
if ( obs.empty() )
throw LocatorException("Empty observation set due to missing stations");
Origin *origin;
if ( !_publicIDPattern.empty() ) {
origin = Origin::Create("");
PublicObject::GenerateId(origin, _publicIDPattern);
}
else
origin = Origin::Create();
SEISCOMP_DEBUG("New origin publicID: %s", origin->publicID().c_str());
string outputPath = _outputPath + origin->publicID();
if ( globalMode )
params.push_back("LOCFILES - NLLOC_OBS " + earthModelPath + " " + outputPath + " 1");
else
params.push_back("LOCFILES - NLLOC_OBS " + earthModelPath + " " + outputPath);
if ( globalMode )
params.push_back("TRANS GLOBAL");
if ( _usingFixedDepth ) {
bool foundLocGrid = false;
for ( TextLines::iterator it = params.begin(); it != params.end(); ++it ) {
size_t pos = it->find_first_of(" \t\r\n");
if ( pos != string::npos ) {
if ( it->compare(0, pos, "LOCGRID") != 0 )
continue;
}
else if ( *it != "LOCGRID") continue;
// Modify LOCGRID element
vector<string> toks;
Core::split(toks, it->c_str(), " \t\r\n", true);
if ( toks.size() < 10 ) {
delete origin;
origin = NULL;
throw GeneralException((string("Unable to fix depth: invalid LOCGRID line in ") +
_currentProfile->controlFile).c_str());
}
// modify num_grid_z, orig_grid_z and d_grid_z
toks[3] = "2";
toks[6] = Core::toString(_fixedDepth);
toks[9] = Core::toString(_fixedDepthGridSpacing);
*it = "";
for ( size_t i = 0; i < toks.size(); ++i ) {
if ( i > 0 ) *it += ' ';
*it += toks[i];
}
foundLocGrid = true;
}
if ( !foundLocGrid ) {
delete origin;
origin = NULL;
throw GeneralException((string("Unable to fix depth: LOCGRID line not found in ") +
_currentProfile->controlFile).c_str());
}
}
// Suppress physical NLL output it will be done later manually
if ( _enableSEDParameters )
params.push_back("LOCHYPOUT NONE CALC_SED_ORIGIN");
else
params.push_back("LOCHYPOUT NONE");
std::vector<char*> obs_buf, control_buf;
obs_buf.resize(obs.size());
for ( size_t i = 0; i < obs.size(); ++i )
obs_buf[i] = &obs[i][0];
control_buf.resize(_controlFile.size() + params.size());
for ( size_t i = 0; i < _controlFile.size(); ++i )
control_buf[i] = &_controlFile[i][0];
for ( size_t i = 0; i < params.size(); ++i )
control_buf[_controlFile.size()+i] = ¶ms[i][0];
// call taken from NLL_func_test
int return_locations = 1;
int return_oct_tree_grid = 1;
int return_scatter_sample = 1;
LocNode *loc_list_head = NULL;
int istat = NLLoc(NULL, NULL,
&control_buf[0], (int)control_buf.size(),
&obs_buf[0], (int)obs_buf.size(), return_locations,
return_oct_tree_grid, return_scatter_sample, &loc_list_head);
SEISCOMP_DEBUG("NLLoc returned with code %d", istat);
int id = 0;
LocNode *locNode = getLocationFromLocList(loc_list_head, id);
bool validOrigin = false;
for ( ; locNode != NULL; locNode = getLocationFromLocList(loc_list_head, ++id) ) {
SEISCOMP_DEBUG("Processing node");
validOrigin = NLL2SC3(origin, _lastWarning, locNode, usedPicks, _usingFixedDepth);
if ( validOrigin ) {
bool rejectedLocation = false;
try {
rejectedLocation = origin->evaluationStatus() == REJECTED;
}
catch ( ... ) {}
if ( _enableDistanceCutOff && !rejectedLocation ) {
// Update input weights for stations within distance
// greater that the cut-off
for ( PickList::iterator it = usedPicks.begin();
it != usedPicks.end(); ++it ) {
Pick *pick = it->pick.get();
SensorLocation *sloc = getSensorLocation(pick);
if ( sloc == NULL ) continue;
double dist, az, baz;
// Compute distance from origin to station
Math::Geo::delazi(origin->latitude(), origin->longitude(),
sloc->latitude(), sloc->longitude(),
&dist, &az, &baz);
dist = Math::Geo::deg2km(dist);
if ( dist > _distanceCutOff )
replaceWeight(obs, stationName(pick, stationNameFormat), 0);
}
// Rebuild observation buffer
for ( size_t i = 0; i < obs.size(); ++i )
obs_buf[i] = &obs[i][0];
// Free previous results
freeLocList(loc_list_head, 1);
// call NLL again
loc_list_head = NULL;
id = 0;
istat = NLLoc(NULL, NULL,
&control_buf[0], (int)control_buf.size(),
&obs_buf[0], (int)obs_buf.size(), return_locations,
return_oct_tree_grid, return_scatter_sample, &loc_list_head);
SEISCOMP_DEBUG("NLLoc 2nd call returned with code %d", istat);
validOrigin = false;
locNode = getLocationFromLocList(loc_list_head, id);
if ( locNode ) {
// Create a new origin with the same publicID
std::string publicID = origin->publicID();
delete origin;
origin = NULL;
origin = Origin::Create(publicID);
validOrigin = NLL2SC3(origin, _lastWarning, locNode, usedPicks, _usingFixedDepth);
}
else {
delete origin;
origin = NULL;
freeLocList(loc_list_head, 1);
throw LocatorException("Distance cut-off failed: empty location");
}
if ( !validOrigin ) break;
}
// fill additional values
origin->setEarthModelID(_currentProfile?_currentProfile->earthModelID:"");
origin->setMethodID(_currentProfile?_currentProfile->methodID:"NonLinLoc");
if ( _enableNLLOutput ) {
// write NLLoc Hypocenter-Phase file to disk
if ( WriteLocation(NULL, locNode->plocation->phypo, locNode->plocation->parrivals,
locNode->plocation->narrivals, const_cast<char*>((outputPath + ".loc.hyp").c_str()),
1, 1, 0, locNode->plocation->pgrid, 0) < 0 )
SEISCOMP_ERROR("Failed writing location to event file: %s", (outputPath + ".loc.hyp").c_str());
// write NLLoc location Grid Header file to disk
if ( WriteGrid3dHdr(locNode->plocation->pgrid, NULL,
const_cast<char*>(outputPath.c_str()),
const_cast<char*>("loc")) < 0 )
SEISCOMP_ERROR("Failed writing grid header to disk: %s", outputPath.c_str());
// write NLLoc location Oct tree structure of locaiton likelihood values to disk
if ( return_oct_tree_grid ) {
FILE *fpio = fopen((outputPath + ".loc.octree").c_str(), "w");
if ( fpio != NULL ) {
istat = writeTree3D(fpio, locNode->plocation->poctTree);
fclose(fpio);
SEISCOMP_INFO("Oct tree structure written to file: %d nodes", istat);
}
else
SEISCOMP_ERROR("Failed writing octree grid: %s", (outputPath + ".loc.octree").c_str());
}
// write NLLoc binary Scatter file to disk
if ( return_scatter_sample ) {
FILE *fpio = fopen((outputPath + ".loc.scat").c_str(), "w");
if ( fpio != NULL ) {
// write scatter file header informaion
fseek(fpio, 0, SEEK_SET);
fwrite(&(locNode->plocation->phypo->nScatterSaved), sizeof(int), 1, fpio);
float ftemp = (float) locNode->plocation->phypo->probmax;
fwrite(&ftemp, sizeof(float), 1, fpio);
// skip header record
fseek(fpio, 4 * sizeof(float), SEEK_SET);
// write scatter samples
fwrite(locNode->plocation->pscatterSample, 4 * sizeof(float), locNode->plocation->phypo->nScatterSaved, fpio);
fclose(fpio);
}
else
SEISCOMP_ERROR("Failed writing scatter file: %s", (outputPath + ".loc.scat").c_str());
}