-
Notifications
You must be signed in to change notification settings - Fork 20
/
amplitudeprocessor.cpp
2457 lines (1856 loc) · 66.1 KB
/
amplitudeprocessor.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) gempa GmbH *
* All rights reserved. *
* Contact: gempa GmbH (seiscomp-dev@gempa.de) *
* *
* GNU Affero General Public License Usage *
* This file may be used under the terms of the GNU Affero *
* Public License version 3.0 as published by the Free Software Foundation *
* and appearing in the file LICENSE included in the packaging of this *
* file. Please review the following information to ensure the GNU Affero *
* Public License version 3.0 requirements will be met: *
* https://www.gnu.org/licenses/agpl-3.0.html. *
* *
* Other Usage *
* Alternatively, this file may be used in accordance with the terms and *
* conditions contained in a signed written agreement between you and *
* gempa GmbH. *
***************************************************************************/
#define SEISCOMP_COMPONENT AmplitudeProcessor
#include <seiscomp/datamodel/pick.h>
#include <seiscomp/processing/amplitudeprocessor.h>
#include <seiscomp/processing/regions.h>
#include <seiscomp/geo/feature.h>
#include <seiscomp/math/mean.h>
#include <seiscomp/math/filter/iirdifferentiate.h>
#include <seiscomp/logging/log.h>
#include <seiscomp/core/interfacefactory.ipp>
#include <seiscomp/system/environment.h>
#include <seiscomp/seismology/ttt.h>
#include <cmath>
#include <functional>
#include <fstream>
#include <limits>
#include <vector>
#include <mutex>
#include <boost/version.hpp>
#if BOOST_VERSION >= 103800
#include <boost/spirit/include/classic.hpp>
#include <boost/spirit/include/phoenix1_binders.hpp>
#include <boost/spirit/include/classic_error_handling.hpp>
namespace bs = boost::spirit::classic;
#else
#include <boost/spirit.hpp>
#include <boost/spirit/phoenix/binders.hpp>
#include <boost/spirit/error_handling.hpp>
namespace bs = boost::spirit;
#endif
using namespace std;
IMPLEMENT_INTERFACE_FACTORY(Seiscomp::Processing::AmplitudeProcessor, SC_SYSTEM_CLIENT_API);
namespace Seiscomp {
namespace Processing {
IMPLEMENT_SC_ABSTRACT_CLASS_DERIVED(AmplitudeProcessor, TimeWindowProcessor, "AmplitudeProcessor");
namespace {
typedef vector<AmplitudeProcessor::Locale> Regionalization;
DEFINE_SMARTPOINTER(TypeSpecificRegionalization);
class TypeSpecificRegionalization : public Core::BaseObject {
public:
const Regions *regions;
Regionalization regionalization;
};
typedef map<string, TypeSpecificRegionalizationPtr> RegionalizationRegistry;
RegionalizationRegistry regionalizationRegistry;
mutex regionalizationRegistryMutex;
class StatusException : public std::exception {
public:
StatusException(WaveformProcessor::Status status, double value)
: _status(status), _value(value) {}
public:
WaveformProcessor::Status status() const { return _status; }
double value() const { return _value; }
private:
WaveformProcessor::Status _status;
double _value;
};
namespace Expression {
class Context {
public:
Context(
const AmplitudeProcessor *proc,
bool leftSideOfTimeWindow
)
: _proc(proc), _leftSideOfTimeWindow(leftSideOfTimeWindow) {}
~Context() {
//
}
const AmplitudeProcessor *proc() const { return _proc; }
double getTravelTime(const string &phase, int statusValueOffset) {
auto env = _proc->environment();
if ( !env.hypocenter ) {
throw StatusException(WaveformProcessor::MissingHypocenter, statusValueOffset);
}
if ( !env.receiver ) {
throw StatusException(WaveformProcessor::MissingReceiver, statusValueOffset);
}
if ( !_ttt ) {
if ( _proc->config().ttInterface.empty() ) {
_ttt = TravelTimeTableInterfaceFactory::Create("libtau");
}
else {
_ttt = TravelTimeTableInterfaceFactory::Create(_proc->config().ttInterface);
}
if ( !_ttt ) {
throw StatusException(WaveformProcessor::TravelTimeEstimateFailed, statusValueOffset);
}
if ( !_ttt->setModel(_proc->config().ttModel.empty() ? "iasp91" : _proc->config().ttModel) ) {
throw StatusException(WaveformProcessor::TravelTimeEstimateFailed, statusValueOffset + 1);
}
}
auto hypoLat = env.hypocenter->latitude().value();
auto hypoLon = env.hypocenter->longitude().value();
double hypoDepth;
try {
// All attributes are optional and throw an exception if not set
hypoDepth = env.hypocenter->depth().value();
}
catch ( ... ) {
throw StatusException(WaveformProcessor::IncompleteMetadata, statusValueOffset);
}
double recvLat, recvLon, recvElev;
try {
// Both attributes are optional and throw an exception if not set
recvLat = env.receiver->latitude();
recvLon = env.receiver->longitude();
// Elevation is fully optional and set to zero if unset
try {
recvElev = env.receiver->elevation();
}
catch ( ... ) {
recvElev = 0;
}
}
catch ( ... ) {
throw StatusException(WaveformProcessor::IncompleteMetadata, statusValueOffset + 1);
}
try {
auto tt = Core::TimeSpan(
_ttt->computeTime(
phase.c_str(), hypoLat, hypoLon, hypoDepth,
recvLat, recvLon, recvElev
)
);
auto absoluteTime = env.hypocenter->time().value() + tt;
return static_cast<double>(absoluteTime - _proc->trigger());
}
catch ( ... ) {
throw StatusException(WaveformProcessor::TravelTimeEstimateFailed, statusValueOffset + 2);
}
}
double getArrival(const string &phase, bool acceptAll, int statusValueOffset) {
auto env = _proc->environment();
if ( !env.hypocenter ) {
throw StatusException(WaveformProcessor::MissingHypocenter, statusValueOffset);
}
for ( size_t i = 0; i < env.hypocenter->arrivalCount(); ++i ) {
auto arr = env.hypocenter->arrival(i);
if ( arr->phase().code() != phase ) {
continue;
}
auto pick = DataModel::Pick::Find(arr->pickID());
if ( !pick ) {
continue;
}
if ( pick->waveformID().networkCode() != env.networkCode
|| pick->waveformID().stationCode() != env.stationCode
|| pick->waveformID().locationCode() != env.locationCode ) {
continue;
}
bool acceptAllArrivals = acceptAll;
if ( !acceptAllArrivals ) {
try {
// If the origins evaluation mode is manual then all
// arrivals are accepted even automatic one since they
// have been checked in the context of the origin
acceptAllArrivals = env.hypocenter->evaluationMode() == DataModel::MANUAL;
}
catch ( ... ) {}
}
if ( !acceptAllArrivals ) {
try {
if ( pick->evaluationMode() != DataModel::MANUAL ) {
// We do not accept automatic picks
SEISCOMP_DEBUG("%s.%s.%s: arrival '%s' no accepted, origin evaluation mode != manual",
env.networkCode.c_str(),
env.stationCode.c_str(),
env.locationCode.c_str(),
arr->phase().code().c_str());
continue;
}
}
catch ( ... ) {
// An unset evaluation mode is not 'manual'
continue;
}
}
auto onset = pick->time().value();
double scale = _leftSideOfTimeWindow ? -1.0 : 1.0;
try {
onset += scale * pick->time().lowerUncertainty();
}
catch ( ... ) {
try {
onset += scale * pick->time().uncertainty();
}
catch ( ... ) {}
}
return static_cast<double>(onset - _proc->trigger());;
}
throw StatusException(WaveformProcessor::ArrivalNotFound, statusValueOffset);
}
private:
const AmplitudeProcessor *_proc;
TravelTimeTableInterfacePtr _ttt;
bool _leftSideOfTimeWindow;
};
DEFINE_SMARTPOINTER(Interface);
class Interface : public Core::BaseObject {
public:
static InterfacePtr parse(const std::string &, std::string *error_str);
virtual double evaluate(Context &ctx) = 0;
virtual std::string toString() const = 0;
};
class Fixed : public Interface {
public:
explicit Fixed(double value) : _value(value) {}
double evaluate(Context &ctx) override { return _value; }
std::string toString() const override { return Core::toString(_value); }
private:
double _value;
};
template <template<class> class F>
class OP1Expression : public Interface {
public:
OP1Expression(InterfacePtr op1) : _op(F<double>()), _op1(op1) {}
double evaluate(Context &ctx) override {
return _op(_op1->evaluate(ctx));
}
private:
F<double> _op;
protected:
InterfacePtr _op1;
};
class OP2BaseExpression : public Interface {
public:
OP2BaseExpression(InterfacePtr op1, InterfacePtr op2)
: _op1(op1), _op2(op2) {}
protected:
InterfacePtr _op1;
InterfacePtr _op2;
};
template <template<class> class F>
class OP2Expression : public OP2BaseExpression {
public:
OP2Expression(InterfacePtr op1, InterfacePtr op2)
: OP2BaseExpression(op1, op2), _op(F<double>()) {}
double evaluate(Context &ctx) override {
return _op(_op1->evaluate(ctx), _op2->evaluate(ctx));
}
private:
F<double> _op;
};
template<class T>
struct dabs {
T operator()( const T& arg ) const { return std::abs(arg); }
};
template<class T>
struct dmod {
T operator()( const T& arg1, const T& arg2 ) const { return std::fmod(arg1, arg2); }
};
template<class T>
struct dpow {
T operator()( const T& arg1, const T& arg2 ) const { return std::pow(arg1, arg2); }
};
// Operators
class NegExpression : public OP1Expression<std::negate> {
using OP1Expression<std::negate>::OP1Expression;
std::string toString() const override {
return "-" + _op1->toString();
}
};
class AbsExpression : public OP1Expression<dabs> {
using OP1Expression<dabs>::OP1Expression;
std::string toString() const override {
return "|" + _op1->toString() + "|";
}
};
class MinExpression : public OP2BaseExpression {
using OP2BaseExpression::OP2BaseExpression;
double evaluate(Context &ctx) override {
double e1, e2;
try {
e1 = _op1->evaluate(ctx);
}
catch ( ... ) {
// Operand1 is not set, forward operand2 in any case,
// even if it throws an exception. This case is only
// valid if both operands are unset.
return _op2->evaluate(ctx);
}
// Operand1 is set already
try {
e2 = _op2->evaluate(ctx);
}
catch ( ... ) {
// Operand2 is not set, forward operand1
return e1;
}
// Both operands are set, return minimum
return e1 <= e2 ? e1 : e2;
}
std::string toString() const override {
return "min(" + _op1->toString() + ", " + _op2->toString() + ")";
}
};
class MaxExpression : public OP2BaseExpression {
using OP2BaseExpression::OP2BaseExpression;
double evaluate(Context &ctx) override {
double e1, e2;
try {
e1 = _op1->evaluate(ctx);
}
catch ( ... ) {
// Operand1 is not set, forward operand2 in any case,
// even if it throws an exception. This case is only
// valid if both operands are unset.
return _op2->evaluate(ctx);
}
// Operand1 is set already
try {
e2 = _op2->evaluate(ctx);
}
catch ( ... ) {
// Operand2 is not set, forward operand1
return e1;
}
// Both operands are set, return maximum
return e1 >= e2 ? e1 : e2;
}
std::string toString() const override {
return "max(" + _op1->toString() + ", " + _op2->toString() + ")";
}
};
class AltExpression : public OP2BaseExpression {
using OP2BaseExpression::OP2BaseExpression;
double evaluate(Context &ctx) override {
try {
return _op1->evaluate(ctx);
}
catch ( ... ) {
return _op2->evaluate(ctx);
}
}
std::string toString() const override {
return _op1->toString() + " || " + _op2->toString();
}
};
class AddExpression : public OP2Expression<std::plus> {
using OP2Expression<std::plus>::OP2Expression;
std::string toString() const override {
return "(" + _op1->toString() + " + " + _op2->toString() + ")";
}
};
class SubExpression : public OP2Expression<std::minus> {
using OP2Expression<std::minus>::OP2Expression;
std::string toString() const override {
return "(" + _op1->toString() + " - " + _op2->toString() + ")";
}
};
class MulExpression : public OP2Expression<std::multiplies> {
using OP2Expression<std::multiplies>::OP2Expression;
std::string toString() const override {
return "(" + _op1->toString() + " * " + _op2->toString() + ")";
}
};
class DivExpression : public OP2Expression<std::divides> {
using OP2Expression<std::divides>::OP2Expression;
std::string toString() const override {
return "(" + _op1->toString() + " / " + _op2->toString() + ")";
}
};
class ModExpression : public OP2Expression<dmod> {
using OP2Expression<dmod>::OP2Expression;
std::string toString() const override {
return "(" + _op1->toString() + " % " + _op2->toString() + ")";
}
};
class PowExpression : public OP2Expression<dpow> {
using OP2Expression<dpow>::OP2Expression;
std::string toString() const override {
return "(" + _op1->toString() + " ^ " + _op2->toString() + ")";
}
};
// Variables
class ParamOriginTime : public Interface {
public:
double evaluate(Context &ctx) override {
auto env = ctx.proc()->environment();
if ( !env.hypocenter ) {
throw StatusException(WaveformProcessor::MissingHypocenter, 60);
}
return env.hypocenter->time().value() - ctx.proc()->trigger();
}
std::string toString() const override {
return "OT";
}
};
class ParamTrigger : public Interface {
public:
double evaluate(Context &ctx) override {
auto env = ctx.proc()->environment();
if ( !env.hypocenter ) {
throw StatusException(WaveformProcessor::MissingHypocenter, 50);
}
return ctx.proc()->trigger() - env.hypocenter->time().value();
}
std::string toString() const override {
return "T";
}
};
class ParamEpiDistDeg : public Interface {
public:
static double Evaluate(Context &ctx) {
auto env = ctx.proc()->environment();
if ( !env.hypocenter ) {
throw StatusException(WaveformProcessor::MissingHypocenter, 10);
}
auto hypoLon = env.hypocenter->longitude().value();
auto hypoLat = env.hypocenter->latitude().value();
double recvLat, recvLon;
try {
// Both attributes are optional and throw an exception if not set
recvLat = env.receiver->latitude();
recvLon = env.receiver->longitude();
}
catch ( ... ) {
throw StatusException(WaveformProcessor::MissingReceiver, 10);
}
double dist, az, baz;
Math::Geo::delazi_wgs84(hypoLat, hypoLon, recvLat, recvLon,
&dist, &az, &baz);
return dist;
}
double evaluate(Context &ctx) override {
return Evaluate(ctx);
}
std::string toString() const override {
return "D";
}
};
class ParamEpiDistKM : public ParamEpiDistDeg {
public:
static double Evaluate(Context &ctx) {
return Math::Geo::deg2km(ParamEpiDistDeg::Evaluate(ctx));
}
double evaluate(Context &ctx) override {
return Evaluate(ctx);
}
std::string toString() const override {
return "R";
}
};
class ParamDepth : public Interface {
public:
static double Evaluate(Context &ctx) {
auto env = ctx.proc()->environment();
if ( !env.hypocenter ) {
throw StatusException(WaveformProcessor::MissingHypocenter, 20);
}
try {
return env.hypocenter->depth().value();
}
catch ( ... ) {
throw StatusException(WaveformProcessor::MissingDepth, 20);
}
}
double evaluate(Context &ctx) override {
return Evaluate(ctx);
}
std::string toString() const override {
return "Z";
}
};
class ParamHypoDistKM : public Interface {
public:
static double Evaluate(Context &ctx) {
auto R = ParamEpiDistKM::Evaluate(ctx);
auto z = ParamDepth::Evaluate(ctx);
return sqrt(R * R + z * z);
}
double evaluate(Context &ctx) override {
return Evaluate(ctx);
}
std::string toString() const override {
return "h";
}
};
class ParamHypoDistDeg : public ParamHypoDistKM {
public:
static double Evaluate(Context &ctx) {
return Math::Geo::km2deg(ParamHypoDistKM::Evaluate(ctx));
}
double evaluate(Context &ctx) override {
return Evaluate(ctx);
}
std::string toString() const override {
return "H";
}
};
class ParamTT : public Interface {
public:
ParamTT(const std::string &phase) : _phase(phase) {}
public:
double evaluate(Context &ctx) override {
return ctx.getTravelTime(_phase, 30);
}
std::string toString() const override {
return "tt(" + _phase + ")";
}
private:
std::string _phase;
};
class ParamArrival : public Interface {
public:
ParamArrival(const std::string &phase, bool acceptAll)
: _phase(phase), _acceptAll(acceptAll) {}
public:
double evaluate(Context &ctx) override {
return ctx.getArrival(_phase, _acceptAll, 40);
}
std::string toString() const override {
return "arr(" + _phase + ", " + (_acceptAll ? "true" : "false") + ")";
}
private:
std::string _phase;
bool _acceptAll;
};
}
// -----------------------------------------------------------------------------
// Expression parser
// -----------------------------------------------------------------------------
struct LiteralClosure : bs::closure<LiteralClosure, double> {
member1 value;
};
template <typename T>
struct ValueClosure : bs::closure<ValueClosure<T>, T> {
typename bs::closure<ValueClosure<T>, T>::member1 value;
};
template <typename T>
struct ParamClosure : bs::closure<ParamClosure<T>, T, string> {
typename bs::closure<ParamClosure<T>, T, string>::member1 value;
typename bs::closure<ParamClosure<T>, T, string>::member2 name;
};
template <typename T>
struct Param2Closure : bs::closure<Param2Closure<T>, T, string, string> {
typename bs::closure<Param2Closure<T>, T, string, string>::member1 value;
typename bs::closure<Param2Closure<T>, T, string, string>::member2 name;
typename bs::closure<Param2Closure<T>, T, string, string>::member3 flag;
};
struct StringClosure : bs::closure<StringClosure, string> {
member1 name;
};
template <typename T> struct Parser;
template <typename ParserT>
struct Generator {
typedef typename ParserT::component_type component_type;
typedef typename ParserT::value_type value_type;
Generator(ParserT &p) : parser(p) {}
value_type constant(float f) const {
return new Expression::Fixed(f);
}
value_type abs(value_type f) const {
return new Expression::AbsExpression(f);
}
value_type min(value_type a, value_type b) const {
return new Expression::MinExpression(a, b);
}
value_type max(value_type a, value_type b) const {
return new Expression::MaxExpression(a, b);
}
value_type alt(value_type a, value_type b) const {
return new Expression::AltExpression(a, b);
}
value_type add(value_type a, value_type b) const {
return new Expression::AddExpression(a, b);
}
value_type sub(value_type a, value_type b) const {
return new Expression::SubExpression(a, b);
}
value_type mul(value_type a, value_type b) const {
return new Expression::MulExpression(a, b);
}
value_type div(value_type a, value_type b) const {
return new Expression::DivExpression(a, b);
}
value_type mod(value_type a, value_type b) const {
return new Expression::ModExpression(a, b);
}
value_type pow(value_type a, value_type b) const {
return new Expression::PowExpression(a, b);
}
value_type parameter(const string &name) const {
value_type f = nullptr;
if ( name == "R" || name == "d" ) {
f = new Expression::ParamEpiDistKM;
}
else if ( name == "D" ) {
f = new Expression::ParamEpiDistDeg;
}
else if ( name == "Z" ) {
f = new Expression::ParamDepth;
}
else if ( name == "h" ) {
f = new Expression::ParamHypoDistKM;
}
else if ( name == "H" ) {
f = new Expression::ParamHypoDistDeg;
}
else if ( name == "OT" ) {
f = new Expression::ParamOriginTime;
}
else if ( name == "T" ) {
f = new Expression::ParamTrigger;
}
if ( !f )
parser.error_message = "unknown parameter '" + name + "'";
return f;
}
value_type travelTime(const string &name) const {
return new Expression::ParamTT(name);
}
value_type arrival(const string &name, const string &flag) const {
if ( flag == "true" ) {
return new Expression::ParamArrival(name, true);
}
else if ( flag.empty() || (flag == "false") ) {
return new Expression::ParamArrival(name, false);
}
parser.error_message = "invalid manual flag '" + flag + "'";
return nullptr;
}
ParserT &parser;
};
template <typename T>
struct Parser : bs::grammar< Parser<T> > {
typedef T component_type;
typedef Expression::InterfacePtr value_type;
typedef Generator< Parser<T> > generator_type;
// The parser object is copied a lot, so instead of keeping its own table
// of variables, it keeps track of a reference to a common table.
Parser(value_type &res, string &err)
: result(res), error_message(err), generator(*this) {
result = nullptr;
}
struct Handler {
template <typename ScannerT, typename ErrorT>
bs::error_status<>
operator()(ScannerT const& /*scan*/, ErrorT const& /*error*/) const {
return bs::error_status<> (bs::error_status<>::fail);
}
};
template <typename ParserT>
struct ErrorCheck {
ErrorCheck(ParserT const &p) : parser(p) {}
template <typename Iterator>
void operator()(Iterator first, Iterator last) const {
if ( !parser.error_message.empty() )
bs::throw_(first, (int)-1);
}
ParserT const &parser;
};
// Following is the grammar definition.
template <typename ScannerT>
struct definition {
definition(Parser const& self) {
using namespace bs;
using namespace phoenix;
identifier
= lexeme_d
[
alpha_p
>> *alnum_p
][identifier.name = construct_<string>(arg1, arg2)];
// The longest_d directive is built-in to tell the parser to make
// the longest match it can. Thus "1.23" matches real_p rather than
// int_p followed by ".23".
literal
= longest_d
[
int_p[literal.value = arg1]
| real_p[literal.value = arg1]
];
group
= '(' >> expression[group.value = arg1] >> ')';
abs
= '|'
>> expression[abs.value = phoenix::bind(&generator_type::abs)(self.generator, arg1)]
>> '|';
min
= "min("
>> expression[min.value = arg1]
>> ','
>> expression[min.value = phoenix::bind(&generator_type::min)(self.generator, min.value, arg1)]
>> ')';
max
= "max("
>> expression[max.value = arg1]
>> ','
>> expression[max.value = phoenix::bind(&generator_type::max)(self.generator, max.value, arg1)]
>> ')';
constant
= literal[constant.value = phoenix::bind(&generator_type::constant)(self.generator, arg1)];
param
= (+identifier[param.name = arg1])
[
param.value = phoenix::bind(&generator_type::parameter)(self.generator, param.name)][ErrorCheck<Parser>(self)
];
tt
= ("tt(" >> (+identifier[tt.name = arg1]) >> ')')
[
tt.value = phoenix::bind(&generator_type::travelTime)(self.generator, tt.name)][ErrorCheck<Parser>(self)
];
arrival
= ("arr(" >> (+identifier[arrival.name = arg1][arrival.flag = string()]) >> * ( "," >> (+identifier[arrival.flag = arg1])) >> ')')
[
arrival.value = phoenix::bind(&generator_type::arrival)(self.generator, arrival.name, arrival.flag)][ErrorCheck<Parser>(self)
];
// A statement can end at the end of the line, or with a semicolon.
statement
= guard<int>()
(
expression[phoenix::bind(&Parser::setResult)(self, arg1)] >> end_p
)[Handler()];
value
= constant[value.value = arg1]
| tt[value.value = arg1]
| arrival[value.value = arg1]
| min[value.value = arg1]
| max[value.value = arg1]
| param[value.value = arg1]
| group[value.value = arg1]
| abs[value.value = arg1];
alternative
= value[alternative.value = arg1]
>> * (
"||" >> value[alternative.value = phoenix::bind(&generator_type::alt)(self.generator, alternative.value, arg1)]
);
power
= alternative[power.value = arg1]
>> * (
'^' >> alternative[power.value = phoenix::bind(&generator_type::pow)(self.generator, power.value, arg1)]
);
modulus
= power[modulus.value = arg1]
>> * ('%' >> power[modulus.value = phoenix::bind(&generator_type::mod)(self.generator, modulus.value, arg1)]);
multiplication
= modulus[multiplication.value = arg1]
>> * ( ( '*' >> modulus[multiplication.value = phoenix::bind(&generator_type::mul)(self.generator, multiplication.value, arg1)])
| ( '/' >> modulus[multiplication.value = phoenix::bind(&generator_type::div)(self.generator, multiplication.value, arg1)])
);
addition
= multiplication[addition.value = arg1]
>> * ( ( '+' >> multiplication[addition.value = phoenix::bind(&generator_type::add)(self.generator, addition.value, arg1)])
| ( '-' >> multiplication[addition.value = phoenix::bind(&generator_type::sub)(self.generator, addition.value, arg1)])
);
expression = addition[expression.value = arg1];
}
bs::rule<ScannerT> const&
start() const { return statement; }
// Each rule must be declared, optionally with an associated closure.
bs::rule<ScannerT> statement;
bs::rule<ScannerT, StringClosure::context_t> identifier;
bs::rule<ScannerT, LiteralClosure::context_t> literal;
bs::rule<ScannerT, typename ParamClosure<value_type>::context_t> param, tt;
bs::rule<ScannerT, typename Param2Closure<value_type>::context_t> arrival;
bs::rule<ScannerT, typename ValueClosure<value_type>::context_t> expression, value,
constant, group, abs, min, max,
multiplication, addition, modulus, power, alternative;
};
void setResult(value_type x) const {
result = x;
}
value_type &result;
string &error_message;
generator_type generator;
};
Expression::InterfacePtr Expression::Interface::parse(const std::string &text, std::string *error_str) {
string error;
Parser<double>::value_type result;