-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.cpp
612 lines (496 loc) · 18.6 KB
/
main.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
/***************************************************************************
* 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 screloc
#include <seiscomp/logging/log.h>
#include <seiscomp/core/datamessage.h>
#include <seiscomp/client/application.h>
#include <seiscomp/client/inventory.h>
#include <seiscomp/datamodel/eventparameters.h>
#include <seiscomp/datamodel/origin.h>
#include <seiscomp/datamodel/pick.h>
#include <seiscomp/datamodel/network.h>
#include <seiscomp/datamodel/station.h>
#include <seiscomp/datamodel/sensorlocation.h>
#include <seiscomp/datamodel/utils.h>
#include <seiscomp/datamodel/publicobjectcache.h>
#include <seiscomp/seismology/locatorinterface.h>
#include <seiscomp/io/archive/xmlarchive.h>
#include <iostream>
#include <iomanip>
using namespace std;
using namespace Seiscomp;
using namespace Seiscomp::Core;
using namespace Seiscomp::DataModel;
using namespace Seiscomp::Seismology;
class Reloc : public Client::Application {
public:
Reloc(int argc, char **argv) : Client::Application(argc, argv) {
setMessagingEnabled(true);
setDatabaseEnabled(true, true);
setLoadStationsEnabled(true);
setPrimaryMessagingGroup("LOCATION");
// Listen for picks (caching) and origins
addMessagingSubscription("PICK");
addMessagingSubscription("LOCATION");
// set up 1 hour of pick caching
// otherwise the picks will be read from the database
_cache.setTimeSpan(Core::TimeSpan(60*60));
_useWeight = false;
_originEvaluationMode = "AUTOMATIC";
_adoptFixedDepth = false;
_repeatedRelocationCount = 1;
_storeSourceOriginID = false;
}
protected:
void createCommandLineDescription() {
commandline().addGroup("Mode");
commandline().addOption("Mode", "test", "test mode, do not send any message");
commandline().addOption("Mode", "dump", "dump processed origins as XML to stdout");
commandline().addGroup("Input");
commandline().addOption("Input", "origin-id,O", "reprocess the origin and send a message", &_originIDs);
commandline().addOption("Input", "locator", "the locator type to use", &_locatorType, false);
commandline().addOption("Input", "profile", "the locator profile to use", &_locatorProfile, false);
commandline().addOption("Input", "use-weight", "use current picks weight", &_useWeight, true);
commandline().addOption("Input", "ep", "Event parameters XML file for offline processing of all contained origins. "
"This option should not be mixed with --dump.", &_epFile);
commandline().addOption("Input", "replace", "Used in combination with --ep and defines if origins are to be replaced "
"by their relocated counterparts or just added to the output.");
commandline().addGroup("Output");
commandline().addOption("Output", "origin-id-suffix", "create origin ID from that of the input origin plus the specfied suffix", &_originIDSuffix);
commandline().addOption("Output", "evaluation-mode", "evaluation mode of the new origin (AUTOMATIC or MANUAL)", &_originEvaluationMode, true);
commandline().addGroup("Profiling");
commandline().addOption("Profiling", "measure-relocation-time", "measure and log the time it takes to run each relocation");
commandline().addOption("Profiling", "repeated-relocations", "improve measurement of relocation time by running each relocation multiple times", &_repeatedRelocationCount);
}
bool initConfiguration() {
// first call the application's configuration routine
if ( !Client::Application::initConfiguration() )
return false;
_ignoreRejected = false;
_allowPreliminary = false;
if (_repeatedRelocationCount < 1)
_repeatedRelocationCount = 1;
try { _locatorType = configGetString("reloc.locator"); }
catch ( ... ) {}
try { _locatorProfile = configGetString("reloc.profile"); }
catch ( ... ) {}
try { _ignoreRejected = configGetBool("reloc.ignoreRejectedOrigins"); }
catch ( ... ) {}
try { _allowPreliminary = configGetBool("reloc.allowPreliminaryOrigins"); }
catch ( ... ) {}
try { _allowManual = configGetBool("reloc.allowManualOrigins"); }
catch ( ... ) {
if ( !_originIDs.empty() || !_epFile.empty()) {
_allowManual = true;
std::cerr << "OriginID or XML file provided: activating option reloc.allowManualOrigins" << endl;
}
else {
_allowManual = false;
}
}
try { _adoptFixedDepth = configGetBool("reloc.adoptFixedDepth"); }
catch ( ... ) {}
try { _useWeight = configGetBool("reloc.useWeight"); }
catch ( ... ) {}
try { _originIDSuffix = configGetString("reloc.originIDSuffix"); }
catch ( ... ) {}
try { _storeSourceOriginID = configGetBool("reloc.storeSourceOriginID"); }
catch ( ... ) {}
if ( !_epFile.empty() )
setMessagingEnabled(false);
if ( !isInventoryDatabaseEnabled() )
setDatabaseEnabled(false, false);
return true;
}
bool init() {
if ( !Client::Application::init() )
return false;
_locator = LocatorInterfaceFactory::Create(_locatorType.c_str());
if ( !_locator ) {
SEISCOMP_ERROR("Locator %s is not available -> abort", _locatorType.c_str());
SEISCOMP_DEBUG(" + examples:");
SEISCOMP_DEBUG(" + LOCSAT");
SEISCOMP_DEBUG(" + NonLinLoc (add locnll plugin)");
SEISCOMP_DEBUG(" + Hypo71 (add hypo71 plugin)");
return false;
}
_inputOrgs = addInputObjectLog("origin");
_outputOrgs = addOutputObjectLog("origin", primaryMessagingGroup());
_cache.setDatabaseArchive(query());
_locator->init(configuration());
if ( !_locatorProfile.empty() )
_locator->setProfile(_locatorProfile);
if ( _originEvaluationMode != "AUTOMATIC" && _originEvaluationMode != "MANUAL") {
SEISCOMP_ERROR("output evaluation-mode is %s ", _originEvaluationMode.c_str());
SEISCOMP_ERROR(" + must be (AUTOMATIC|MANUAL)");
return false;
}
SEISCOMP_DEBUG("Running with configuration:");
SEISCOMP_DEBUG(" + Locator / profile: %s / %s", _locatorType.c_str(), _locatorProfile.c_str());
SEISCOMP_DEBUG(" + ignoreRejectOrigins: %s", _ignoreRejected?"True":"False");
SEISCOMP_DEBUG(" + allowPreliminaryOrigins: %s", _allowPreliminary?"True":"False");
SEISCOMP_DEBUG(" + allowManualOrigins: %s", _allowManual?"True":"False");
SEISCOMP_DEBUG(" + useWeight: %s", _useWeight?"True":"False");
SEISCOMP_DEBUG(" + adoptFixedDepth: %s", _adoptFixedDepth?"True":"False");
SEISCOMP_DEBUG(" + evaluation mode of relocated origins: %s", _originEvaluationMode.c_str());
if ( !_originIDs.empty() ) {
SEISCOMP_DEBUG(" + considered origins: %s", toString<string>(_originIDs).c_str());
}
if ( !_originIDSuffix.empty() ) {
SEISCOMP_DEBUG(" + for relocated origins add suffix to ID or original origins: %s",
_originIDSuffix.c_str());
}
if ( !_epFile.empty() ) {
SEISCOMP_DEBUG(" + input XML file: %s", _epFile.c_str());
}
return true;
}
bool run() {
if ( !_epFile.empty() ) {
// Disable database
setDatabase(NULL);
SEISCOMP_INFO("Processing file %s", _epFile.c_str());
IO::XMLArchive ar;
if ( !ar.open(_epFile.c_str()) ) {
SEISCOMP_ERROR(" + failed to open %s", _epFile.c_str());
return false;
}
EventParametersPtr ep;
ar >> ep;
ar.close();
if ( !ep ) {
SEISCOMP_ERROR(" + no event parameters found");
return false;
}
int numberOfOrigins = (int)ep->originCount();
SEISCOMP_INFO(" + found %i origins", numberOfOrigins);
bool replace = commandline().hasOption("replace");
if ( !_originIDs.empty() ) {
// test if requested origin was loaded
for ( vector<string>::const_iterator it = _originIDs.begin();
it != _originIDs.end(); ++it ) {
if ( !Origin::Find(it->c_str()) ) {
SEISCOMP_ERROR(" + found no origin with ID: %s", it->c_str());
return false;
}
}
}
int processed = 0;
for ( int i = 0; i < numberOfOrigins; ++i, ++processed ) {
OriginPtr org = ep->origin(i);
std::string publicID = org->publicID();
SEISCOMP_DEBUG("Processing origin %s", publicID.c_str());
bool processing = true;
if ( !_originIDs.empty() ) {
processing = false;
for ( size_t i = 0; i < _originIDs.size(); ++i ) {
if ( publicID == _originIDs[i] ) {
processing = true;
}
}
if ( !processing ) {
SEISCOMP_DEBUG(" + skip origin, not in origin-id list");
continue;
}
}
try {
org = process(org.get());
}
catch ( std::exception &e ) {
SEISCOMP_ERROR(" + processing failed - %s", e.what());
continue;
}
if ( !_originIDSuffix.empty()) {
org->setPublicID(publicID+_originIDSuffix);
SEISCOMP_DEBUG(" + new origin publicID is derived from original");
}
SEISCOMP_DEBUG(" + relocated origin has publicID: %s ",
org->publicID().c_str());
if ( org ) {
if ( replace ) {
ep->removeOrigin(i);
--i;
--numberOfOrigins;
}
ep->add(org.get());
}
if (((processed+1) % 100) == 0 ) {
SEISCOMP_INFO(" + processed %d origins", processed+1);
}
}
SEISCOMP_INFO(" + processed %d origins", processed);
ar.create("-");
ar.setFormattedOutput(true);
ar << ep;
ar.close();
return true;
}
else if ( !_originIDs.empty() ) {
for ( size_t i = 0; i < _originIDs.size(); ++i ) {
OriginPtr org = Origin::Cast(query()->getObject(Origin::TypeInfo(), _originIDs[i]));
if ( !org ) {
std::cerr << "ERROR: Origin with ID '" << _originIDs[i] << "' has not been found" << endl;
continue;
}
std::string publicID = org->publicID();
OriginPtr newOrg;
SEISCOMP_DEBUG("Processing origin %s", publicID.c_str());
try {
newOrg = process(org.get());
}
catch ( std::exception &e ) {
SEISCOMP_ERROR(" + processing failed - %s", e.what());
continue;
}
if ( !_originIDSuffix.empty()) {
newOrg->setPublicID(publicID+_originIDSuffix);
SEISCOMP_DEBUG(" + new origin publicID is derived from original");
}
SEISCOMP_DEBUG(" + relocated origin has publicID: %s ",
newOrg->publicID().c_str());
// Log warning messages
string msgWarning = _locator->lastMessage(LocatorInterface::Warning);
if ( !msgWarning.empty() )
std::cerr << "WARNING: " << msgWarning << std::endl;
bool sendOrigin = true;
if ( _ignoreRejected ) {
try {
if ( newOrg->evaluationStatus() == REJECTED ) {
SEISCOMP_DEBUG(" + Origin status is REJECTED, skip sending");
sendOrigin = false;
}
}
catch ( ... ) {}
}
if ( sendOrigin && !send(newOrg.get()) ) {
SEISCOMP_ERROR(" + sending of processed origin failed");
continue;
}
std::cerr << "INFO: new Origin created OriginID=" << newOrg.get()->publicID().c_str() << std::endl;
}
return true;
}
return Client::Application::run();
}
protected:
void handleMessage(Core::Message* msg) {
Application::handleMessage(msg);
DataMessage *dm = DataMessage::Cast(msg);
if ( dm == NULL ) return;
for ( DataMessage::iterator it = dm->begin(); it != dm->end(); ++it ) {
Origin *org = Origin::Cast(it->get());
if ( org )
addObject("", org);
}
}
void addObject(const std::string &parentID, Object *obj) {
Pick *pick = Pick::Cast(obj);
if ( pick ) {
_cache.feed(pick);
return;
}
Origin *org = Origin::Cast(obj);
if ( org ) {
logObject(_inputOrgs, Core::Time::GMT());
if ( isAgencyIDBlocked(objectAgencyID(org)) ) {
SEISCOMP_DEBUG("%s: skipping: agencyID '%s' is blocked",
org->publicID().c_str(), objectAgencyID(org).c_str());
return;
}
try {
// ignore non automatic origins
if ( org->evaluationMode() != AUTOMATIC && !_allowManual ) {
SEISCOMP_DEBUG("%s: skipping: mode is not 'automatic'", org->publicID().c_str());
return;
}
}
// origins without an evaluation mode are treated as
// automatic origins
catch ( ... ) {}
// Skip confirmed or otherwise tagged solutions unless
// preliminary origins are allowed
try {
EvaluationStatus stat = org->evaluationStatus();
if ( stat != PRELIMINARY || !_allowPreliminary ) {
SEISCOMP_DEBUG("%s: skipping due to valid evaluation status", org->publicID().c_str());
return;
}
}
catch ( ... ) {}
OriginPtr newOrg;
try {
newOrg = process(org);
if ( !newOrg ) {
SEISCOMP_ERROR("processing of origin '%s' failed", org->publicID().c_str());
return;
}
}
catch ( std::exception &e ) {
SEISCOMP_ERROR("%s: %s", org->publicID().c_str(), e.what());
return;
}
string msgWarning = _locator->lastMessage(LocatorInterface::Warning);
if ( !msgWarning.empty() )
SEISCOMP_WARNING("%s: %s", org->publicID().c_str(), msgWarning.c_str());
bool sendOrigin = true;
if ( _ignoreRejected ) {
try {
if ( newOrg->evaluationStatus() == REJECTED ) {
SEISCOMP_WARNING("%s: relocated origin has evaluation status REJECTED: result not sent",
org->publicID().c_str());
sendOrigin = false;
}
}
catch ( ... ) {}
}
if ( sendOrigin && !send(newOrg.get()) ) {
SEISCOMP_ERROR("%s: sending of derived origin failed", org->publicID().c_str());
return;
}
return;
}
}
private:
OriginPtr process(Origin *org) {
if ( org->arrivalCount() == 0 )
query()->loadArrivals(org);
LocatorInterface::PickList picks;
// Load all referenced picks and store them locally. Through the
// global PublicObject pool they can then be found by the locator.
for ( size_t i = 0; i < org->arrivalCount(); ++i ) {
Arrival *ar = org->arrival(i);
PickPtr pick = _cache.get<Pick>(ar->pickID());
if ( !pick ) continue;
if ( !_useWeight ) {
// Set weight to 1
ar->setWeight(1.0);
ar->setTimeUsed(true);
ar->setBackazimuthUsed(true);
ar->setHorizontalSlownessUsed(true);
}
picks.push_back(pick.get());
}
_locator->useFixedDepth(false);
if ( _adoptFixedDepth ) {
try {
if ( org->depthType() == OPERATOR_ASSIGNED )
_locator->setFixedDepth(org->depth().value());
}
catch ( ... ) {}
try {
if ( org->depth().uncertainty() == 0.0 )
_locator->setFixedDepth(org->depth().value());
}
catch ( ... ) {}
}
OriginPtr newOrg;
Seiscomp::Util::StopWatch timer;
timer.restart();
for (size_t i=0; i<_repeatedRelocationCount; i++)
newOrg = _locator->relocate(org);
double seconds = (double) timer.elapsed() / _repeatedRelocationCount;
if ( newOrg ) {
if ( _originEvaluationMode == "AUTOMATIC" ) {
newOrg->setEvaluationMode(EvaluationMode(AUTOMATIC));
}
else {
newOrg->setEvaluationMode(EvaluationMode(MANUAL));
SEISCOMP_DEBUG(" + set evaluation mode: 'manual'");
}
CreationInfo *ci;
try {
ci = &newOrg->creationInfo();
}
catch ( ... ) {
newOrg->setCreationInfo(CreationInfo());
newOrg->creationInfo().setCreationTime(Core::Time::GMT());
ci = &newOrg->creationInfo();
}
ci->setAgencyID(agencyID());
ci->setAuthor(author());
// keep track of the triggering origin of this relocation
if (_storeSourceOriginID ) {
DataModel::CommentPtr comment = new DataModel::Comment();
comment->setId("relocation::sourceOrigin");
comment->setText(org->publicID());
comment->setCreationInfo(*ci);
newOrg->add(comment.get());
}
}
if ( commandline().hasOption("measure-relocation-time") ) {
double milliseconds = 1000.*seconds;
SEISCOMP_DEBUG(" + time for relocating: %.3f ms", milliseconds);
}
if ( commandline().hasOption("dump") ) {
EventParametersPtr ep = new EventParameters;
ep->add(newOrg.get());
for ( LocatorInterface::PickList::iterator it = picks.begin();
it != picks.end(); ++it ) {
ep->add(it->pick.get());
}
IO::XMLArchive ar;
ar.setFormattedOutput(true);
ar.create("-");
ar << ep;
ar.close();
}
return newOrg;
}
bool send(Origin *org) {
if ( org == NULL ) return false;
logObject(_outputOrgs, Core::Time::GMT());
if ( commandline().hasOption("test") ) return true;
EventParametersPtr ep = new EventParameters;
bool wasEnabled = Notifier::IsEnabled();
Notifier::Enable();
// Insert origin to event parameters
ep->add(org);
NotifierMessagePtr msg = Notifier::GetMessage();
bool result = false;
if ( connection() )
result = connection()->send(msg.get());
Notifier::SetEnabled(wasEnabled);
return result;
}
private:
std::vector<std::string> _originIDs;
std::string _originIDSuffix;
std::string _locatorType;
std::string _locatorProfile;
bool _ignoreRejected;
bool _allowPreliminary;
bool _allowManual;
bool _adoptFixedDepth;
LocatorInterfacePtr _locator;
PublicObjectTimeSpanBuffer _cache;
ObjectLog *_inputOrgs;
ObjectLog *_outputOrgs;
bool _useWeight;
bool _storeSourceOriginID;
std::string _originEvaluationMode;
std::string _epFile;
size_t _repeatedRelocationCount;
};
int main(int argc, char **argv) {
int retCode = EXIT_SUCCESS;
// Create an own block to make sure the application object
// is destroyed when printing the overall objectcount
{
Reloc app(argc, argv);
retCode = app.exec();
}
return retCode;
}