-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathScheduler.cpp
More file actions
3612 lines (3178 loc) · 158 KB
/
Scheduler.cpp
File metadata and controls
3612 lines (3178 loc) · 158 KB
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
/*
* VieSched++ Very Long Baseline Interferometry (VLBI) Scheduling Software
* Copyright (C) 2018 Matthias Schartner
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* File: Scheduler.cpp
* Author: mschartn
*
* Created on June 29, 2017, 2:29 PM
*/
#include "Scheduler.h"
using namespace std;
using namespace VieVS;
unsigned long Scheduler::nextId = 0;
Scheduler::Scheduler( Initializer &init, string path, string fname )
: VieVS_NamedObject( move( fname ), nextId++ ),
version_{init.version_},
path_{ std::move( path ) },
network_{ std::move( init.network_ ) },
sourceList_{ std::move( init.sourceList_ ) },
himp_{ std::move( init.himp_ ) },
calib_{ std::move( init.calib_ ) },
multiSchedulingParameters_{ std::move( init.multiSchedulingParameters_ ) },
xml_{ init.xml_ },
obsModes_{ init.obsModes_ },
currentObservingMode_{ obsModes_->getMode( 0 ) } {
if ( init.parameters_.subnetting ) {
if ( init.parameters_.subnettingMinNStaPercent_otherwiseAllBut ) {
parameters_.subnetting = make_unique<Subnetting_percent>( init.preCalculated_.subnettingSrcIds,
init.parameters_.subnettingMinNStaPercent );
} else {
parameters_.subnetting = make_unique<Subnetting_minIdle>( init.preCalculated_.subnettingSrcIds,
init.parameters_.subnettingMinNStaAllBut );
}
}
parameters_.fillinmodeDuringScanSelection = init.parameters_.fillinmodeDuringScanSelection;
parameters_.fillinmodeInfluenceOnSchedule = init.parameters_.fillinmodeInfluenceOnSchedule;
parameters_.fillinmodeAPosteriori = init.parameters_.fillinmodeAPosteriori;
parameters_.fillinmodeAPosteriori_minSites = init.parameters_.fillinmodeAPosteriori_minSites;
parameters_.fillinmodeAPosteriori_minRepeat = init.parameters_.fillinmodeAPosteriori_minRepeat;
parameters_.idleToObservingTime = init.parameters_.idleToObservingTime;
if ( parameters_.idleToObservingTime ) {
parameters_.idleToObservingTime_staids =
init.getMembers( init.parameters_.idleToObservingTimeGroup, network_.getStations() );
}
parameters_.andAsConditionCombination = init.parameters_.andAsConditionCombination;
parameters_.minNumberOfSourcesToReduce = init.parameters_.minNumberOfSourcesToReduce;
parameters_.maxNumberOfIterations = init.parameters_.maxNumberOfIterations;
parameters_.numberOfGentleSourceReductions_1 = init.parameters_.numberOfGentleSourceReductions_1;
parameters_.reduceFactor_1 = init.parameters_.reduceFactor_1;
parameters_.numberOfGentleSourceReductions_2 = init.parameters_.numberOfGentleSourceReductions_2;
parameters_.reduceFactor_2 = init.parameters_.reduceFactor_2;
parameters_.writeSkyCoverageData = false;
parameters_.doNotObserveSourcesWithinMinRepeat = init.parameters_.doNotObserveSourcesWithinMinRepeat;
parameters_.ignoreSuccessiveScansSameSrc = init.parameters_.ignoreSuccessiveScansSameSrc;
}
Scheduler::Scheduler(std::string name, std::string path, Network network, SourceList sourceList,
std::vector<Scan> scans,
boost::property_tree::ptree xml, std::shared_ptr<ObservingMode> obsModes_ )
: VieVS_NamedObject( move( name ), nextId++ ),
version_{0},
path_{std::move(path)},
network_{ std::move( network ) },
sourceList_{ std::move( sourceList ) },
scans_{ std::move( scans ) },
obsModes_{ std::move( obsModes_ ) },
currentObservingMode_{ nullptr },
xml_{ xml } {}
void Scheduler::startScanSelection( unsigned int endTime, std::ofstream &of, Scan::ScanType type,
boost::optional<StationEndposition> &opt_endposition,
boost::optional<Subcon> &opt_subcon, int depth ) {
#ifdef VIESCHEDPP_LOG
if ( Flags::logDebug ) BOOST_LOG_TRIVIAL( debug ) << "start scan selection (depth " << depth << ")";
#endif
// necessary vectors for calibrator blocks
vector<double> prevLowElevationScores( network_.getNSta(), 0 );
vector<double> prevHighElevationScores( network_.getNSta(), 0 );
vector<double> highestElevations( network_.getNSta(), numeric_limits<double>::min() );
vector<double> lowestElevations( network_.getNSta(), numeric_limits<double>::max() );
int countCalibratorScans = 0;
if ( type == Scan::ScanType::astroCalibrator ) {
writeCalibratorHeader( of );
}
// Check if there is a required opt_endposition. If yes change station availability with respect to opt_endposition
if ( opt_endposition.is_initialized() ) {
changeStationAvailability( opt_endposition, StationEndposition::change::start );
}
while ( true ) {
// look if station is possible with respect to opt_endposition
if ( opt_endposition.is_initialized() ) {
if ( !opt_endposition->checkStationPossibility( network_.getStations() ) ) {
break;
}
}
// create a subcon with all possible next scans
Subcon subcon;
if ( opt_subcon.is_initialized() ) {
// if you already have a subcon, check the endposition of each scan and generate subnetting scans and new
// score.
subcon = std::move( *opt_subcon );
opt_subcon = boost::none;
subcon.changeType( sourceList_, Scan::ScanType::fillin );
subcon.checkIfEnoughTimeToReachEndposition( network_, sourceList_, opt_endposition );
subcon.clearSubnettingScans();
if ( parameters_.subnetting != nullptr ) {
subcon.createSubnettingScans( parameters_.subnetting, network_, sourceList_ );
}
} else {
// otherwise calculate new subcon
subcon = createSubcon( parameters_.subnetting, type, opt_endposition );
// string fileName = path_ + getName();
// for ( const auto &sky : network_.getSkyCoverages() ) {
// string stations;
// unsigned int i = 0;
// for ( const auto &any : network_.getStaid2skyCoverageId() ) {
// if ( any.second == sky.getId() ) {
// i = network_.getStation( any.first ).getCurrentTime();
// stations.append( network_.getStation( any.first ).getName() ).append( " " );
// }
// }
// sky.generateDebuggingFiles( i, fileName, stations );
// }
}
// check algorithm focus corners for intensive sessions
if ( FocusCorners::startFocusCorner && depth == 0 ) {
of << boost::format( "| %=140s |\n" ) % "reweight sources to focus observation at corner";
FocusCorners::reweight( subcon, sourceList_, of );
++FocusCorners::iscan;
of << boost::format( "| %=140s |\n" ) %
( boost::format( "Focus corner scan %d of %d" ) % FocusCorners::iscan % FocusCorners::nscans )
.str();
}
if ( type != Scan::ScanType::astroCalibrator ) {
// standard case
subcon.generateScore( network_, sourceList_ );
} else {
// special case for calibrator scans
subcon.generateScore( prevLowElevationScores, prevHighElevationScores, network_, sourceList_ );
}
unsigned long nSingleScans = subcon.getNumberSingleScans();
unsigned long nSubnettingScans = subcon.getNumberSubnettingScans();
// select the best possible next scan(s) and save them under 'bestScans'
vector<Scan> bestScans;
if ( type != Scan::ScanType::astroCalibrator ) {
// standard case
bestScans = subcon.selectBest( network_, sourceList_, currentObservingMode_, opt_endposition );
} else {
// special calibrator case
bestScans = subcon.selectBest( network_, sourceList_, currentObservingMode_, prevLowElevationScores,
prevHighElevationScores, opt_endposition );
}
if ( FocusCorners::startFocusCorner && depth == 0 && FocusCorners::iscan >= FocusCorners::nscans ) {
FocusCorners::reset( bestScans, sourceList_ );
}
bestScans.erase( std::remove_if( bestScans.begin(), bestScans.end(),
[]( const Scan &scan ) { return scan.getScore() == 0.0; } ),
bestScans.end() );
// check if you have possible next scan
if ( bestScans.empty() ) {
if ( depth == 0 && type != Scan::ScanType::fillin ) {
if ( type == Scan::ScanType::astroCalibrator ) {
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( warning )
<< "no valid scan found in calibrator block -> finished calibration block";
#else
cout << "[warning] no valid scan found in calibrator block -> finished calibration block\n";
#endif
break;
}
// if there is no more possible scan at the outer most iteration, check 1minute later
unsigned int maxScanEnd = 0;
for ( auto &any : network_.refStations() ) {
PointingVector pv = any.getCurrentPointingVector();
pv.setTime( pv.getTime() + 60 );
if ( !any.getPARA().available || !any.getPARA().tagalong ) {
any.setCurrentPointingVector( pv );
if ( pv.getTime() > maxScanEnd ) {
maxScanEnd = pv.getTime();
}
}
}
if ( util::absDiff( endTime, maxScanEnd ) > 1800 ) {
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( warning ) << "no valid scan found, checking one minute later";
#else
cout << "[warning] no valid scan found, checking one minute later\n";
#endif
of << boost::format( "| [warning] no valid scan found, checking one minute later: %s %143t|\n" ) %
TimeSystem::time2string( maxScanEnd );
}
checkForNewEvents( maxScanEnd, true, of, true );
if ( maxScanEnd > endTime ) {
break;
}
continue;
} else {
// if there is no more possible scan in an deep recursion, break this recursion
break;
}
}
// check end time of best possible next scan
unsigned int maxScanEnd = 0;
for ( const auto &any : bestScans ) {
if ( any.getTimes().getScanTime( Timestamp::end ) > maxScanEnd ) {
maxScanEnd = any.getTimes().getScanTime( Timestamp::end );
}
}
if ( maxScanEnd > FocusCorners::nextStart ) {
FocusCorners::startFocusCorner = true;
}
// check if end time triggers a new event
bool hardBreak = checkForNewEvents( maxScanEnd, true, of, true );
if ( hardBreak ) {
continue;
}
if ( maxScanEnd > endTime ) {
break;
}
// if end time of best possible next scans is greater than end time of scan selection stop
if ( maxScanEnd > TimeSystem::duration ) {
int i = 0;
while ( i < bestScans.size() ) {
Scan &any = bestScans[i];
bool valid = any.prepareForScanEnd( network_, sourceList_.getSource( any.getSourceId() ),
currentObservingMode_, endTime );
if ( !valid ) {
bestScans.erase( bestScans.begin() + i );
} else {
++i;
}
}
if ( bestScans.empty() ) {
break;
}
}
// the best scans are now already fixed. add observing duration to total observing duration to avoid fillin mode
// scans which extend the allowed total observing time.
for ( const auto &scan : bestScans ) {
for ( int i = 0; i < scan.getNSta(); ++i ) {
unsigned long staid = scan.getStationId( i );
unsigned int obsDur = scan.getTimes().getObservingDuration( i );
network_.refStation( staid ).addObservingTime( obsDur );
}
}
// check if it is possible to start a fillin mode block, otherwise put best scans to schedule
if ( parameters_.fillinmodeDuringScanSelection && !scans_.empty() ) {
boost::optional<StationEndposition> newEndposition( network_.getNSta() );
if ( opt_endposition.is_initialized() ) {
for ( unsigned long i = 0; i < network_.getNSta(); ++i ) {
if ( opt_endposition->hasEndposition( i ) ) {
newEndposition->addPointingVectorAsEndposition( opt_endposition->getFinalPosition( i ).get() );
}
}
}
for ( const auto &any : bestScans ) {
for ( int i = 0; i < any.getNSta(); ++i ) {
newEndposition->addPointingVectorAsEndposition( any.getPointingVector( i ) );
}
// newEndposition->setBackupEarliestScanStart(any.getTimes().getObservingTime());
}
newEndposition->setStationAvailable( network_.getStations() );
newEndposition->checkStationPossibility( network_.getStations() );
boost::optional<Subcon> new_opt_subcon( std::move( subcon ) );
// start recursion for fillin mode scans
unsigned long scansBefore = scans_.size();
startScanSelection( min( maxScanEnd, TimeSystem::duration ), of, Scan::ScanType::fillin,
newEndposition, new_opt_subcon, depth + 1 );
// check if a fillin mode scan was created and update times if necessary
unsigned long scansAfter = scans_.size();
if ( scansAfter != scansBefore ) {
// loop over all stations
for ( const Station &thisSta : network_.getStations() ) {
unsigned long staid = thisSta.getId();
// search for station in all best scans
for ( auto &thisScan : bestScans ) {
boost::optional<unsigned long> oidx = thisScan.findIdxOfStationId( staid );
if ( oidx.is_initialized() ) {
bool valid = true;
auto idx = static_cast<int>( oidx.get() );
const PointingVector &slewEnd = thisScan.getPointingVector( idx, Timestamp::start );
boost::optional<unsigned int> oSlewTime = thisSta.slewTime( slewEnd );
if ( oSlewTime.is_initialized() ) {
unsigned int slewTime = oSlewTime.get();
auto oidx2 = thisScan.findIdxOfStationId( staid );
if ( oidx2.is_initialized() ) {
if ( thisSta.getPARA().firstScan ) {
valid = thisScan.referenceTime().updateAfterFillinmode(
idx, thisSta.getCurrentTime(), 0, slewTime, 0 );
} else {
valid = thisScan.referenceTime().updateAfterFillinmode(
idx, thisSta.getCurrentTime(), thisSta.getPARA().systemDelay, slewTime,
thisSta.getPARA().preob );
}
}
} else {
valid = false;
}
if ( !valid ) {
string msg = (boost::format("check fillin mode scan for station %s "
"prior to scan %d") % thisSta.getName()
% thisScan.getId()).str();
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( warning ) << msg;
#else
cout << "[warning] "<< msg << "\n";
#endif
of << "[warning] "<< msg << "\n";
}
break;
}
}
}
}
}
// update highestElevation and lowestElevation in case of calibrator block
bool stopScanSelection = false;
if ( type == Scan::ScanType::astroCalibrator ) {
++countCalibratorScans;
stopScanSelection = calibratorUpdate( bestScans, prevHighElevationScores, prevLowElevationScores,
highestElevations, lowestElevations );
}
// update best possible scans
consideredUpdate( nSingleScans, nSubnettingScans, depth, of );
for ( auto &bestScan : bestScans ) {
update( bestScan, of );
}
// stop if calibration block is finished of number of maximum scans reached
if ( type == Scan::ScanType::astroCalibrator ) {
if ( stopScanSelection || countCalibratorScans >= AstrometricCalibratorBlock::nmaxScans ) {
break;
}
}
// update number of scan selections if it is a standard scan
if ( type == Scan::ScanType::standard ) {
++Scan::nScanSelections;
if ( Scan::scanSequence_flag ) {
Scan::newScan();
}
}
// check if you need to schedule a calibration block
if ( type == Scan::ScanType::standard && AstrometricCalibratorBlock::scheduleCalibrationBlocks && depth == 0 ) {
switch ( AstrometricCalibratorBlock::cadenceUnit ) {
case AstrometricCalibratorBlock::CadenceUnit::scans: {
if ( Scan::nScanSelections == AstrometricCalibratorBlock::nextBlock ) {
boost::optional<Subcon> empty_subcon = boost::none;
startScanSelection( endTime, of, Scan::ScanType::astroCalibrator, opt_endposition, empty_subcon,
depth + 1 );
AstrometricCalibratorBlock::nextBlock += AstrometricCalibratorBlock::cadence;
}
break;
}
case AstrometricCalibratorBlock::CadenceUnit::seconds: {
if ( maxScanEnd >= AstrometricCalibratorBlock::nextBlock ) {
boost::optional<Subcon> empty_subcon = boost::none;
startScanSelection( endTime, of, Scan::ScanType::astroCalibrator, opt_endposition, empty_subcon,
depth + 1 );
AstrometricCalibratorBlock::nextBlock += AstrometricCalibratorBlock::cadence;
}
break;
}
default:
break;
}
}
}
// write clibrator statistics
if ( type == Scan::ScanType::astroCalibrator ) {
writeCalibratorStatistics( of, highestElevations, lowestElevations );
}
// scan selection block is over. Change station availability back to start value
if ( opt_endposition.is_initialized() ) {
changeStationAvailability( opt_endposition, StationEndposition::change::end );
}
}
void Scheduler::start() noexcept {
string prefix = util::version2prefix(version_);
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL(info) << prefix << "start scheduling";
#else
cout << "[info] " + prefix + "start scheduling\n";
#endif
string fileName = getName() + "_iteration_" + to_string( parameters_.currentIteration ) + ".txt";
ofstream of;
if ( xml_.get( "VieSchedpp.output.iteration_log", true ) ) {
of.open( path_ + fileName );
}
if ( FocusCorners::flag ) {
FocusCorners::initialize( network_, of );
}
CalibratorBlock::stationFlag = vector<int>( network_.getNSta(), 0 );
if ( network_.getNSta() == 0 || sourceList_.empty() || network_.getNBls() == 0 ) {
string e = ( boost::format( "number of stations: %d number of baselines: %d number of sources: %d;\n" ) %
network_.getNSta() % network_.getNBls() % sourceList_.getNSrc() )
.str();
of << "ERROR: " << e;
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( error ) << e;
#else
cout << "ERROR: " << e;
#endif
return;
}
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( info ) << "writing scheduling file to: " << fileName;
#else
cout << "[info] writing scheduling file to: " << fileName;
#endif
if ( parameters_.currentIteration > 0 ) {
of << "Iteration number: " << parameters_.currentIteration << "\n";
}
if ( multiSchedulingParameters_.is_initialized() ) {
of << "multi scheduling parameters:\n";
multiSchedulingParameters_->output( of );
}
resetAllEvents( of );
listSourceOverview( of );
boost::optional<StationEndposition> endposition = boost::none;
boost::optional<Subcon> subcon = boost::none;
of << boost::format( ".%|143T-|.\n" );
const auto &o_a_priori_scans = xml_.get_child_optional( "VieSchedpp.a_priori_satellite_scans" );
// for(auto &sta : network_.refStations()){
// for(const auto &sat : sourceList_.getSatellites()){
// ofstream of;
// of.open(sta.getName()+"_"+sat->getName()+".txt");
// PointingVector pv(sta.getId(), sat->getId());
// for(unsigned int time = 0; time < TimeSystem::duration; ++time){
// pv.setTime(time);
// sta.calcAzEl_rigorous(sat, pv);
// of << boost::format("%s %18.10f %18.10f \n") % TimeSystem::time2string(pv.getTime()) %
// (pv.getAz()*rad2deg) % (pv.getEl()*rad2deg);
// }
// }
// }
if ( o_a_priori_scans.is_initialized() ) {
scheduleAPrioriScans( *o_a_priori_scans, of );
}
if ( !calib_.empty() ) {
calibratorBlocks( of );
// return;
}
if ( ParallacticAngleBlock::nscans > 0 ) {
parallacticAngleBlocks( of );
}
if ( DifferentialParallacticAngleBlock::nscans > 0 ) {
DifferentialParallacticAngleBlock::iScan = 0;
differentialParallacticAngleBlocks( of );
}
if ( himp_.is_initialized() ) {
highImpactScans( himp_.get(), of );
}
Scan::scanSequence_modulo = 0;
// check if you have some fixed high impact scans
if ( scans_.empty() ) {
// no fixed scans: start creating a schedule
startScanSelection( TimeSystem::duration, of, Scan::ScanType::standard, endposition, subcon, 0 );
// sort scans
sortSchedule( Timestamp::start );
} else {
startScanSelectionBetweenScans( TimeSystem::duration, of, Scan::ScanType::standard, true, false );
}
checkForNewEvents( TimeSystem::duration, true, of, true );
// start fillinmode a posterior
if ( parameters_.fillinmodeAPosteriori ) {
of << boost::format( "|%|143t||\n" );
of << boost::format( "|%=142s|\n" ) % "start fillin mode a posteriori";
of << boost::format( "|%|143t||\n" );
of << boost::format( "|%|143T-||\n" );
startScanSelectionBetweenScans( TimeSystem::duration, of, Scan::ScanType::fillin, false, true );
}
// output some statistics
statistics( of );
bool newScheduleNecessary = checkOptimizationConditions( of );
// check if new iteration is necessary
if ( newScheduleNecessary ) {
of.close();
++parameters_.currentIteration;
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( info )
<< "source optimization conditions not met -> restarting schedule with reduced number of sources";
#else
cout << "[info] source optimization conditions not met -> restarting schedule with reduced number of sources";
#endif
// restart schedule
start();
} else {
if ( parameters_.idleToObservingTime ) {
switch ( ScanTimes::getAlignmentAnchor() ) {
case ScanTimes::AlignmentAnchor::start: {
idleToScanTime( Timestamp::end, of );
break;
}
case ScanTimes::AlignmentAnchor::end: {
idleToScanTime( Timestamp::start, of );
break;
}
case ScanTimes::AlignmentAnchor::individual: {
idleToScanTime( Timestamp::end, of );
idleToScanTime( Timestamp::start, of );
break;
}
default:
break;
}
}
updateObservingTimes();
// check if there was an error during the session
if ( !checkAndStatistics( of ) ) {
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( error ) << boost::format( "%s iteration %d error while checking the schedule" ) %
getName() % ( parameters_.currentIteration );
#else
cout << boost::format( "[error] %s iteration %d error while checking the schedule" ) % getName() %
( parameters_.currentIteration );
#endif
}
of.close();
}
sortSchedule( Timestamp::start );
}
void Scheduler::statistics( ofstream &of ) {
int nobs = std::accumulate( scans_.begin(), scans_.end(), 0,
[]( int sum, const Scan &any ) { return sum + any.getNObs(); } );
of << boost::format( "|%|143t||\n" );
of << boost::format( "|%=142s|\n" ) % "SUMMARY";
of << boost::format( "|%|143t||\n" );
of << boost::format( "| %-35s %-30d %143t|\n" ) % "number of scans" % scans_.size();
of << boost::format( "| %-35s %-30d %143t|\n" ) % "number of observations" % nobs;
of << boost::format( "| %-35s %d (single source scans %d, subnetting scans %d) %143t|\n" ) %
"total scans considered" % ( nSingleScansConsidered + 2 * nSubnettingScansConsidered ) %
nSingleScansConsidered % ( 2 * nSubnettingScansConsidered );
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( info ) << "created schedule with " << scans_.size() << " scans and " << nobs << " observations";
#else
cout << "[info] created schedule with " << scans_.size() << " scans and " << nobs << " observations";
#endif
}
Subcon Scheduler::createSubcon( const shared_ptr<Subnetting> &subnetting, Scan::ScanType type,
const boost::optional<StationEndposition> &endposition ) noexcept {
Subcon subcon = allVisibleScans( type, endposition, parameters_.doNotObserveSourcesWithinMinRepeat );
subcon.calcStartTimes( network_, sourceList_, endposition );
subcon.updateAzEl( network_, sourceList_ );
subcon.constructAllBaselines( network_, sourceList_ );
subcon.calcAllBaselineDurations( network_, sourceList_, currentObservingMode_ );
subcon.calcAllScanDurations( network_, sourceList_, endposition );
subcon.checkTotalObservingTime( network_, sourceList_ );
subcon.checkIfEnoughTimeToReachEndposition( network_, sourceList_, endposition );
if ( subnetting != nullptr ) {
subcon.createSubnettingScans( subnetting, network_, sourceList_ );
}
return subcon;
}
Subcon Scheduler::allVisibleScans( Scan::ScanType type, const boost::optional<StationEndposition> &endposition,
bool doNotObserveSourcesWithinMinRepeat ) noexcept {
// get latest start time of new scan
unsigned int currentTime = 0;
for ( auto &station : network_.getStations() ) {
if ( station.getCurrentTime() > currentTime ) {
currentTime = station.getCurrentTime();
}
}
// save all ids of the next observed sources (if there is a required endposition)
set<unsigned long> observedSources;
if ( type != Scan::ScanType::fringeFinder ) {
if ( parameters_.ignoreSuccessiveScansSameSrc ) {
if ( endposition.is_initialized() ) {
observedSources = endposition->getObservedSources( currentTime, sourceList_ );
}
for ( const auto &sta : network_.getStations() ) {
observedSources.insert( sta.getCurrentPointingVector().getSrcid() );
}
}
}
// create subcon with all visible scans
Subcon subcon;
#ifdef VIESCHEDPP_LOG
if ( Flags::logDebug ) BOOST_LOG_TRIVIAL( debug ) << "creating new subcon " << subcon.printId();
#endif
for ( const auto &thisSource : sourceList_.getSources() ) {
subcon.visibleScan( currentTime, type, network_, thisSource, observedSources,
doNotObserveSourcesWithinMinRepeat );
}
return subcon;
}
void Scheduler::update( Scan &scan, ofstream &of ) noexcept {
#ifdef VIESCHEDPP_LOG
if ( Flags::logDebug ) BOOST_LOG_TRIVIAL( debug ) << "adding scan " << scan.printId() << " to schedule";
#endif
// check if scan has influence (only required for fillin mode scans)
bool influence;
influence = !( scan.getType() == Scan::ScanType::fillin && !parameters_.fillinmodeInfluenceOnSchedule );
unsigned long srcid = scan.getSourceId();
for ( int i = 0; i < scan.getNSta(); ++i ) {
const PointingVector &pv = scan.getPointingVector( i );
unsigned long staid = pv.getStaid();
const PointingVector &pv_end = scan.getPointingVector( i, Timestamp::end );
unsigned long nObs = scan.getNObs( staid );
network_.update( nObs, pv_end, influence );
}
for ( int i = 0; i < scan.getNObs(); ++i ) {
const Observation &obs = scan.getObservation( i );
network_.update( obs.getBlid(), influence );
}
unsigned long nbl = scan.getNObs();
unsigned int latestTime = scan.getTimes().getObservingTime( Timestamp::start );
const auto &thisSource = sourceList_.refSource( srcid );
thisSource->update( scan.getNSta(), nbl, latestTime, influence );
// update minimum slew time in case of custom data write speed to disk
for ( int i = 0; i < scan.getNSta(); ++i ) {
unsigned long staid = scan.getPointingVector( i ).getStaid();
Station &sta = network_.refStation( staid );
if ( sta.getPARA().dataWriteRate.is_initialized() ) {
// double recRate = currentObservingMode_->recordingRate( staid );
unsigned int duration = scan.getTimes().getObservingDuration( i );
sta.referencePARA().overheadTimeDueToDataWriteSpeed( duration );
}
}
scan.output( scans_.size(), network_, thisSource, of );
scans_.push_back( std::move( scan ) );
}
void Scheduler::consideredUpdate( unsigned long n1scans, unsigned long n2scans, int depth, ofstream &of ) noexcept {
if ( n1scans + n2scans > 0 ) {
string right;
if ( n2scans == 0 ) {
right = ( boost::format( "considered single scans %d" ) % n1scans ).str();
} else {
right = ( boost::format( "considered single scans %d, subnetting scans %d" ) % n1scans % n2scans ).str();
}
of << boost::format( "| depth: %d %130s |\n" ) % depth % right;
nSingleScansConsidered += n1scans;
nSubnettingScansConsidered += n2scans;
}
}
bool Scheduler::checkAndStatistics( ofstream &of ) noexcept {
resetAllEvents( of );
bool everythingOk = true;
#ifdef VIESCHEDPP_LOG
if ( Flags::logDebug ) BOOST_LOG_TRIVIAL( debug ) << "checking schedule";
#endif
of << "starting check routine!\n";
int countErrors = 0;
int countWarnings = 0;
bool debug = xml_.get("VieSchedpp.output.createSlewFile", false);
// debug = true;
for ( auto &thisStation : network_.refStations() ) {
#ifdef VIESCHEDPP_LOG
if ( Flags::logDebug ) BOOST_LOG_TRIVIAL( debug ) << "checking station " << thisStation.getName();
#endif
ofstream of_slew;
if (debug){
string name = path_ + (boost::format("%s_slew_%s.txt") %this->getName() %thisStation.getName()).str();
of_slew.open(name);
}
of << " checking station " << thisStation.getName() << ":\n";
unsigned long staid = thisStation.getId();
unsigned int constTimes = thisStation.getPARA().systemDelay + thisStation.getPARA().preob;
thisStation.referencePARA().firstScan = false;
// sort scans based on observation start of this station (can be different if you align scans individual or at
// end)
sortSchedule( staid );
// get first scan with this station and initialize idx
int i_thisEnd = 0;
int idx_thisEnd = -1;
while ( i_thisEnd < scans_.size() ) {
const Scan &scan_thisEnd = scans_[i_thisEnd];
// look for index of station in scan
boost::optional<unsigned long> oidx_thisEnd = scan_thisEnd.findIdxOfStationId( staid );
if ( !oidx_thisEnd.is_initialized() ) {
++i_thisEnd;
continue; // if you do not find one continue
}
idx_thisEnd = static_cast<int>( *oidx_thisEnd );
break;
}
// save staStatistics
Station::Statistics staStatistics;
while ( i_thisEnd < scans_.size() ) {
// get scan and pointing vector at start
const Scan &scan_thisEnd = scans_[i_thisEnd];
const PointingVector &thisEnd = scan_thisEnd.getPointingVector( idx_thisEnd, Timestamp::end );
// update staStatistics
staStatistics.scanStartTimes.push_back( scan_thisEnd.getPointingVector( idx_thisEnd ).getTime() );
staStatistics.totalObservingTime += scan_thisEnd.getTimes().getObservingDuration( idx_thisEnd );
staStatistics.totalFieldSystemTime += scan_thisEnd.getTimes().getFieldSystemDuration( idx_thisEnd );
staStatistics.totalPreobTime += scan_thisEnd.getTimes().getPreobDuration( idx_thisEnd );
int i_nextStart = i_thisEnd + 1;
while ( i_nextStart < scans_.size() ) {
// get scan and pointing vector at end
const Scan &scan_nextStart = scans_[i_nextStart];
// look for index of station in scan
boost::optional<unsigned long> oidx_nextStart = scan_nextStart.findIdxOfStationId( staid );
if ( !oidx_nextStart.is_initialized() ) {
++i_nextStart;
continue; // if you do not find one continue
}
auto idx_nextStart = static_cast<int>( *oidx_nextStart );
const PointingVector &nextStart = scan_nextStart.getPointingVector( idx_nextStart );
bool dummy = true;
thisStation.checkForNewEvent( nextStart.getTime(), dummy );
thisStation.referencePARA().firstScan = false;
// check if scan times are in correct order
unsigned int thisEndTime = thisEnd.getTime();
unsigned int nextStartTime = nextStart.getTime();
if ( nextStartTime < thisEndTime ) {
++countErrors;
of << " ERROR #" << countErrors
<< ": start time of next scan is before end time of previouse scan! scans: "
<< scan_thisEnd.printId() << " and " << scan_nextStart.printId() << "\n";
boost::posix_time::ptime thisEndTime_ = TimeSystem::internalTime2PosixTime( thisEndTime );
boost::posix_time::ptime nextStartTime_ = TimeSystem::internalTime2PosixTime( nextStartTime );
of << " end time of previouse scan: " << thisEndTime_.time_of_day() << " "
<< thisEnd.printId() << "\n";
of << " start time of next scan: " << nextStartTime_.time_of_day() << " "
<< nextStart.printId() << "\n";
of << "*\n";
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( error )
<< boost::format( "%s iteration %d:" ) % getName() % ( parameters_.currentIteration )
<< " start time of next scan is before end time of previouse scan! station: "
<< thisStation.getName();
#endif
everythingOk = false;
} else {
// check slew time
auto oslewtime = thisStation.slewTime(
thisEnd, nextStart, scan_thisEnd.getTimes().getObservingDuration( idx_thisEnd ) );
unsigned int slewtime;
if ( oslewtime.is_initialized() ) {
slewtime = *oslewtime;
} else {
slewtime = TimeSystem::duration;
}
unsigned int min_neededTime = slewtime + constTimes;
unsigned int availableTime = nextStartTime - thisEndTime;
unsigned int idleTime;
if ( debug ) {
double abs_unaz = abs( thisEnd.getAz() - nextStart.getAz() );
double abs_el = abs( thisEnd.getEl() - nextStart.getEl() );
of_slew << boost::format(
"%s - %s dt %4d unaz from %9.4f to %9.4f total %9.4f el from %9.4f to %9.4f total %9.4f "
"slew %3d fixed %3d good by %4d src %s - %s\n")
% TimeSystem::internalTime2PosixTime( thisEndTime ).time_of_day()
% TimeSystem::internalTime2PosixTime( nextStartTime ).time_of_day()
% (static_cast<long>(nextStartTime) - static_cast<long>(thisEndTime))
% (thisEnd.getAz() *rad2deg)
% (nextStart.getAz() *rad2deg)
% (abs_unaz *rad2deg)
% (thisEnd.getEl() *rad2deg)
% (nextStart.getEl() *rad2deg)
% (abs_el *rad2deg)
% slewtime
% constTimes
% (static_cast<long>(availableTime) - static_cast<long>(slewtime)
- static_cast<long>(constTimes))
% sourceList_.getSource(thisEnd.getSrcid())->getName()
% sourceList_.getSource(nextStart.getSrcid())->getName();
}
// update staStatistics
staStatistics.totalSlewTime += slewtime;
if ( availableTime >= min_neededTime ) {
idleTime = availableTime - min_neededTime;
} else {
idleTime = 0;
}
staStatistics.totalIdleTime += idleTime;
int buffer = 1;
if ( this->sourceList_.isSatellite(scan_nextStart.getSourceId()) ){
buffer = 2;
}
if ( availableTime + buffer < min_neededTime ) {
if ( this->sourceList_.isSatellite(scan_nextStart.getSourceId()) ){
++countWarnings;
of << " WARNING #" << countErrors
<< ": maybe not enough available time for slewing! scans: " << scan_thisEnd.printId() << " and "
<< scan_nextStart.printId() << "\n";
of << "it might not be a problem if there is enough preob/fs time to compensate for it";
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( warning )
<< boost::format( "%s iteration %d:" ) % getName() % ( parameters_.currentIteration )
<< "maybe not enough available time for slewing to satellite? station: " << thisStation.getName() << " ("
<< ( (long)availableTime - (long)min_neededTime ) << " [sec])";
#endif
}else{
++countErrors;
of << " ERROR #" << countErrors
<< ": not enough available time for slewing! scans: " << scan_thisEnd.printId() << " and "
<< scan_nextStart.printId() << "\n";
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( error )
<< boost::format( "%s iteration %d:" ) % getName() % ( parameters_.currentIteration )
<< "not enough available time for slewing! station: " << thisStation.getName() << " ("
<< ( (long)availableTime - (long)min_neededTime ) << " [sec])";
#endif
}
boost::posix_time::ptime thisEndTime_ = TimeSystem::internalTime2PosixTime( thisEndTime );
boost::posix_time::ptime nextStartTime_ = TimeSystem::internalTime2PosixTime( nextStartTime );
of << " end time of previouse scan: " << thisEndTime_.time_of_day() << " "
<< thisEnd.printId() << "\n";
of << " start time of next scan: " << nextStartTime_.time_of_day() << " "
<< nextStart.printId() << "\n";
of << " available time: " << availableTime << "\n";
of << " needed slew time: " << slewtime << "\n";
of << " needed constant times: " << constTimes << "\n";
of << " needed time: " << min_neededTime << "\n";
of << " difference: " << (long)availableTime - (long)min_neededTime << "\n";
of << "*\n";
everythingOk = false;
} else {
if ( idleTime > 1200 ) {
unsigned int midpoint = ( thisEndTime + nextStartTime ) / 2;
bool dummy = false;
thisStation.checkForNewEvent( midpoint, dummy );
if ( thisStation.getPARA().available ) {
++countWarnings;
of << " WARNING #" << countWarnings
<< ": long idle time! scans: " << scan_thisEnd.printId() << " and "
<< scan_nextStart.printId() << "\n";
of << " idle time: " << idleTime << "[s]\n";
boost::posix_time::ptime thisEndTime_ =
TimeSystem::internalTime2PosixTime( thisEndTime );
boost::posix_time::ptime nextStartTime_ =
TimeSystem::internalTime2PosixTime( nextStartTime );
of << " end time of previouse scan: " << thisEndTime_.time_of_day() << " "
<< thisEnd.printId() << "\n";
of << " start time of next scan: " << nextStartTime_.time_of_day() << " "
<< nextStart.printId() << "\n";
of << "*\n";
#ifdef VIESCHEDPP_LOG
BOOST_LOG_TRIVIAL( warning )
<< boost::format( "%s iteration %d:" ) % getName() %
( parameters_.currentIteration )
<< "long idle time! (" << idleTime << " [s]) station: " << thisStation.getName();
#endif
}
}
}
}
// change index of pointing vector and scan
idx_thisEnd = idx_nextStart;
break;
}
// change index of pointing vector and scan
i_thisEnd = i_nextStart;
}
of << " finished!\n";
thisStation.setStatistics( staStatistics );
}
of << "Total: " << countErrors << " errors and " << countWarnings << " warnings\n";
// sort scans again based on their observation start
sortSchedule( Timestamp::start );
// add source srcStatistics
std::vector<AbstractSource::Statistics> srcStatistics( sourceList_.getNSrc() );
std::vector<Baseline::Statistics> blsStatistics( network_.getNBls() );
for ( const auto &any : scans_ ) {
unsigned long srcid = any.getSourceId();
auto &thisSrcStatistics = srcStatistics[srcid];
thisSrcStatistics.scanStartTimes.push_back( any.getTimes().getObservingTime( Timestamp::start ) );
thisSrcStatistics.totalObservingTime += any.getTimes().getObservingDuration();
for ( const auto &obs : any.getObservations() ) {
unsigned long blid = obs.getBlid();