-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmmtscheduler.py
More file actions
executable file
·2109 lines (1795 loc) · 87.4 KB
/
mmtscheduler.py
File metadata and controls
executable file
·2109 lines (1795 loc) · 87.4 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
#!/usr/bin/python3.6
"""
mmtscheduler.py
Calculates a queue schedule for MMIRS or Binospec at the MMTO.
# ##
# Note: uses astropy >= 2.0.
# astroplan 0.4 files are included here under mmtqueue.
# External dependencies to astroplan are removed.
# (astropy dependency is still there...)
# Numpy is used when possible.
# Removing multiprocessing on 2018-04-04. Using the global daily_events
# for optimization instead.
#
# Going to astropy 3.0, 2018-02-19
# It should be backward compatible with astropy 2.0.
#
# Going to a multiprocessing version, 2018-02-19
# The best performance seems to be with 3 worker processes that calculate
# the constraint scores for the start, middle and end time for an observing
# block.
# This speeds up calculations by about 30%, i.e., 90 seconds goes to 60 seconds.
#
parser.add_argument('-m','--mode', help='Scheduling mode. mode 1: "scheduler" mode; mode 2: "dispatcher" mode.', type=int, choices=[1,2], required=False)
parser.add_argument('-d','--debug', help='Print debugging messages', required=False)
parser.add_argument('-v','--version', help='Software version. Release 1.0 is on ops; version 2.0 and above are on scheduler', type=float, required=False)
parser.add_argument('-s','--start_date', help='Start time for scheduling (UTC time), e.g., "2017-10-01T03:30:00". Defines the time used for dispatcher mode and the start time for scheduler mode', required=False)
parser.add_argument('-e','--end_date', help='End time for scheduling (UTC time), e.g., e.g., "2017-10-01T12:30:00". Defines the end time for scheduler mode.', required=False)
parser.add_argument('-i','--schedule_id', help='Queue scheduling run id.', type=int, required=False)
# New 2017-10-16. Adding binospec option for instrument. Defaults to type string.
parser.add_argument('-t','--instrument', help='Instrument "mmirs" or "binospec"', required=False)
Command line arguments
----------
-m, --mode : integer
Mode for computation. The scheduler mode computes a schedule for the entire queue; the dispatcher mode
schedules the first observing block
Example:
1 (scheduler), e.g., -m=1,
2 (dispatcher), e.g., -m=2
-i, --schedule_id : integer
Schedule ID. This is the database ID corresponding to the schedule. A new ID is assigned each time
a new schedule is generated. You can get the schedule_id from the ObservatoryManager web interface.
Example:
-i=836
-d, --debug : string
A debugging flag: 'true' for verbose output. Defaults to 'false' so only needed if you want
debugging output.
Example:
-d=true
-s :
Parameter:
Example:
./mmtscheduler.py -m=2 -i=836
"""
import argparse
import datetime
import json as json
import numpy as np
from pytz import timezone
import redis as redis
import sqlite3 as sqlite3
import time as time
import subprocess
# Trying this fix for the malformed finals2000A.all at the US Naval Observatory
from astropy.utils import iers
iers.IERS_A_URL = 'http://toshi.nofs.navy.mil/ser7/finals2000A.all'
# Using this to force a new auto_download.
# iers.auto_max_age = 0.001
iers.conf.auto_download = True
import traceback as traceback
# import warnings
# These are the Classes from astroplan that have been incorporated into the 'mmtqueue' module.
# from astroplan import Observer
# from astroplan import FixedTarget
# from astroplan import Constraint
# from astroplan import AirmassConstraint
# from astroplan import AltitudeConstraint
# from astroplan import AtNightConstraint
# from astroplan import TimeConstraint
# from astroplan import MoonSeparationConstraint
# from astroplan import ObservingBlock
# from astroplan import Transitioner
# from astroplan import Slot
# Only using if we program in short-circuiting for constraint calculations.
# from astroplan.constraints import _get_altaz
# from astropy.coordinates import Angle
from astropy.coordinates import SkyCoord
from astropy.coordinates import AltAz
from astropy.coordinates import EarthLocation
from astropy.time import Time
from astropy.time import TimeDelta
import astropy.units as u
from mmtqueue.constraints import AirmassConstraint
from mmtqueue.constraints import AltitudeConstraint
from mmtqueue.constraints import AtNightConstraint
from mmtqueue.constraints import MoonSeparationConstraint
# New (or modified) constraints.
from mmtqueue.constraints import MaskAngleConstraint
from mmtqueue.constraints import MaskNumberConstraint
from mmtqueue.constraints import MeridianConstraint
from mmtqueue.constraints import PIPriorityConstraint
from mmtqueue.constraints import RotatorConstraint
from mmtqueue.constraints import TimeAllocationConstraint
from mmtqueue.constraints import TimeConstraint
from mmtqueue.constraints import MaskReadyConstraint
from mmtqueue.constraints import TransitConstraint
from mmtqueue.constraints import ObjectTypeConstraint
from mmtqueue.constraints import TargetOfOpportunityConstraint
from mmtqueue.constraints import is_always_observable
from mmtqueue.observer import Observer
from mmtqueue.scheduling import Schedule
from mmtqueue.scheduling import Scheduler
from mmtqueue.scheduling import PriorityScheduler
from mmtqueue.scheduling import Scorer
# from mmtqueue.scheduling import SequentialScheduler
from mmtqueue.scheduling import ObservingBlock
from mmtqueue.scheduling import Transitioner
from mmtqueue.scheduling import Slot
from mmtqueue.target import FixedTarget
# These are my specific utility functions.
from mmtqueue.utilities import add_prefix
from mmtqueue.utilities import dict_factory
from mmtqueue.utilities import get_config_json
from mmtqueue.utilities import get_constraint_name
from mmtqueue.utilities import get_key
from mmtqueue.utilities import get_short_key
from mmtqueue.utilities import get_name
from mmtqueue.utilities import get_mask_id
from mmtqueue.utilities import get_program_id
from mmtqueue.utilities import get_score
from mmtqueue.utilities import set_score
from mmtqueue.utilities import set_scorer
from mmtqueue.utilities import get_now
from mmtqueue.utilities import get_target_name
from mmtqueue.utilities import get_target_key
from mmtqueue.utilities import get_sun_moon_date_key
from mmtqueue.utilities import get_target_date_key
from mmtqueue.utilities import is_numeric
from mmtqueue.utilities import localize_time
from mmtqueue.utilities import to_allocated_time
from mmtqueue.utilities import to_constraint_details
from mmtqueue.utilities import to_completed_time
from mmtqueue.utilities import to_mysql
from mmtqueue.utilities import to_output
from mmtqueue.utilities import to_queue
from mmtqueue.utilities import to_redis
from mmtqueue.utilities import to_status
from mmtqueue.utilities import to_stdout
from mmtqueue.utilities import roundup
from mmtqueue.utilities import roundHour
from mmtqueue.utilities import roundTime
from mmtqueue.utilities import table_to_entries
from mmtqueue.utils import time_grid_from_range
# Global variables.
# (Yes, it's best to avoid global variables, but these variables are used by multiple modules.)
# Global verbosity flags.
verbose = True
verbose2 = False
verbose3 = False
verbose4 = False
doing_line_profiling = False
# Global constraints flags: whether a global constraint is to be used in calculations.
# Each variable can be set to either True or False
#
# These parameters are used to turn each constraint on or off in this code.
# There are similar parameters loaded in the configuration structure during setup
# from the user.
#
# Both must be True for the constraint to be used.
use_AirmassConstraint = True
use_AltitudeConstraint = True
use_AtNightConstraint = True
use_MaskAngleConstraint = True
use_MaskNumberConstraint = False
use_MaskReadyConstraint = False
use_MeridianConstraint = True
use_MoonSeparationConstraint = True
use_ObjectTypeConstraint = True
use_PIPriorityConstraint = True
use_RotatorConstraint = True
use_TimeAllocationConstraint = True
use_TimeConstraint = True
use_TargetOfOpportunityConstraint = True
use_TransitConstraint = True
# Global constraint debugging flags: these variables provide detailed outputs for the constraint
# Each variable can be set to either True or False
test_AirmassConstraint = False
test_AltitudeConstraint = False
test_AtNightConstraint = False
test_MoonSeparationConstraint = False
test_MaskAngleConstraint = False
test_MaskNumberConstraint = False
test_MaskReadyConstraint = False
test_MeridianConstraint = False
test_ObjectTypeConstraint = False
test_PIPriorityConstraint = False
test_RotatorConstraint = False
test_TimeAllocationConstraint = False
test_TimeConstraint = False
test_TargetOfOpportunityConstraint = False
# Global sequential scheduling debugging flag: used for detailed testing of the MMTSequentialScheduler.
test_MMTSequentialScheduler = False
# Global flag on whether we want to post values to the Redis server.
do_redis = True
# The master Redis server.
redis_host = 'redis.mmto.arizona.edu'
# Lambda functions for reuse.
current_milliseconds = lambda: int(round(time.time() * 1000))
current_datetime = lambda: str(timezone('America/Phoenix').localize(datetime.datetime.now()))
# Global schedule id variable: Typically, reset during configuration
# Notes:
# schedule_id = 804, December binospec run
# schedule_id = 694, Binospec Commissioning Nov Run
#
# Also, "schedule_id" == "queue_id" in the ObservatoryManager GUI code.
schedule_id = 813
# This is a global dictionary of Astroplan FixedTarget's, indexed by 'objid_id' from the 'fields' structure.
fixed_targets = {}
# Target Of Opportunity info as a mutable object. This allows new values to be passed to
# constraints for processing. If it were immutable, we could not programmatically update values
# during the scheduling process.
ToO = {}
# These are elements of the target-of-opportunity structure:
# "found_ToO" is a boolean on whether there is at least one ToO observable for the scheduling time
# "objid_ids" are the target (i.e., object) ID's supplied by the user.
# "all_ToO" are the FixedTarget objects corresponding to the objid_ids.
# "observable_ToO" are the FixedTarget objects that are observable at a specific scheduling time.
ToO['found_ToO'] = False
ToO['objid_ids'] = []
ToO['all_ToO'] = []
ToO['observable_ToO'] = []
# The sqlite3 database file for caching.
sqlite_file = 'mmtqueue.sqlite'
# Global hash of events such as times for sunrise, sunset, target_set, etc.
use_daily_events = True
daily_events = {}
# Tables within the sqlite3 database:
#
if False:
print("sqlite_file", sqlite_file)
# The table name for cached constraint scores.
table = "scores"
# Default schema for schedules table.
"""
CREATE TABLE `schedules` (
`key` TEXT,
`value` TEXT,
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`timestamp` TEXT DEFAULT CURRENT_TIMESTAMP
);
"""
# Default schema for scores table
"""
CREATE TABLE `scores` (
`key` TEXT,
`value` REAL,
`schedule_MST` TEXT,
`schedule_id` INTEGER,
`comment` TEXT,
PRIMARY KEY(`key`)
);
"""
# To empty the scores table if it gets too big.
"""
DELETE from scores;
vacuum scores;
"""
# Create a shared global database connection
conn = sqlite3.connect(sqlite_file)
# For debugging sqlite.
# cursor = conn.cursor()
# cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
# print(cursor.fetchall())
# if True:
# print("conn: ", repr(conn))
# Setting query results to be a standard Python dictionary.
conn.row_factory = dict_factory
# This is used for the MaskNumberConstraint
# Always assume that masks 110 and 111 are on Binospec
default_masks = ['110','111']
# This keeps track of which masks have been used in scheduling.
# Used by MaskNumberConstraint
masks_used = default_masks
# Lookup tables.
program_id2program = {}
block_ids = {}
objid_ids = {}
def setup(args):
"""Retrieves configuration parameters from the scheduler server.
Retrieves rows pertaining to the given keys from the Table instance
represented by big_table. Silly things may happen if
other_silly_variable is not None.
Args:
args: An associative array from command line arguments (i.e, from argparse()).
Returns:
A boolean: True for success; False for failure
Raises:
None implemented yet.
"""
global schedule_id
global debug
global verbose
global instrument
global meta
global allocation
global stats
global configuration
global configs
global fields
global start_date
global end_date
global mode
global version
global program_id2program
global block_ids
global objid_ids
# Overall approach for input parameters:
# 1) Command-line arguments get the highest priority,
# 2) Parameters from the configs dictionary are next highest priority. These configs values are obtained by
# a web query.
# 3) Finally, fall back to a default value.
# All parameters should be defined in the configs structure with command-line arguments over-ruling those values.
if 'debug' in args and not args['debug'] is None:
if args['debug'].lower() == "true":
txt = "Turning debug on"
debug = True
else:
txt = "Turning debug off"
debug = False
print(txt)
else:
debug = False
# Code version.
version = 2.0
# Note: We need to define instrument before printing anything or posting anything to Redis.
if not args['version'] is None:
version = float(args['version'])
if verbose:
txt = "Setting software version to: {0}".format(version)
# Note: schedule_id is also in the "meta" data structure.
# We need to pass in schedule_id from command line so that
# the correct "meta" data is returned from the database.
if 'schedule_id' in args and not args['schedule_id'] is None:
schedule_id = int(args['schedule_id'])
if verbose:
txt = "Setting schedule_id from args array to: {0}".format(schedule_id)
print(txt)
# Grab all of the "meta" data about this queue schedule.
meta = get_config_json(schedule_id)
# Sending "which_instrument" to dataserver2.
instrument = meta['instrument']
cmd = r'echo "set json { \"which_instrument\" : \"' + instrument + r'\" }" | nc -w 1 tcs-server 8660'
subprocess.call(cmd, shell=True)
configuration = meta['configuration']
# An associative array of configuration key:value pairs.
configs = {}
for conf in configuration:
configs[conf] = configuration[conf]['parametervalue']
# Two different modes to run mmtscheduler:
# mode == 1, scheduler
# mode == 2, dispatcher
if 'mode' in args and not args['mode'] is None:
mode = int(args['mode'])
if verbose:
txt = "Setting mode to: {0}".format(mode)
print(txt)
# Then, use the configs values.
elif 'mode' in configs:
mode = int(configs['mode'])
# Should not get here...
else:
mode = 1
if 'start_date' in args and not args['start_date'] is None:
time = Time(args['start_date'])
start_date = time
elif 'start_date' in configs:
time = Time(configs['start_date'])
# Define the start of the scheduling run to the nearest sunrise.
# self.start_time = self.observer.sun_set_time(time, which='nearest', horizon=-12*u.deg)
# self.start_time = self.observer.sun_set_time(time, which='nearest', horizon=-6*u.deg)
start_date = time
# Should not get here...
else:
# Starting now.
start_date = Time.now()
if 'end_date' in args and not args['end_date'] is None:
time = Time(args['end_date'])
end_date = time
elif 'end_date' in configs:
time = Time(configs['end_date'])
# Define the start of the scheduling run to the nearest sunrise.
# self.start_time = self.observer.sun_set_time(time, which='nearest', horizon=-12*u.deg)
# self.start_time = self.observer.sun_set_time(time, which='nearest', horizon=-6*u.deg)
end_date = time
# Should not get here...
else:
# Ending 12 hours from now.
end_date = Time.now() + TimeDelta(43200.0, format='sec')
if False:
print("start_date: ", repr(start_date))
print("end_date: ", repr(end_date))
# This is the PostgreSQL database (on scheduler) key for the current queue. All queues
# have a unique ID. This schedule ID is used to keep track of different queue runs.
if 'schedule_id' in meta and not args['schedule_id'] is None:
if schedule_id == int(meta['schedule_id']):
if False:
print("The schedule_id agrees from both the command line and database: ", \
str(schedule_id))
else:
# Default to something. This is the Feb 2018 Binospec run.
# schedule_id = 812
if True:
print("There is a problem. The command line schedule_id: ", \
str(schedule_id), ", does not match the database schedule_id:", \
str(meta['schedule_id']))
# The instrument can currently be either 'binospec' or 'mmirs'
# The instrument name is cast to all lower characters so
# capitalization doesn't matter.
# Note that the instrument prefix for Redis is all caps:
# either BINOSPEC or MMIRS.
if 'instrument' in args and not args['instrument'] is None:
if args['instrument'].lower() == 'mmirs':
instrument = "mmirs"
else:
instrument = "binospec"
# Usually the instrument data is in "meta" unless you want to
# really confuse things, e.g., running a Binospec queue with
# MMIRS targets.
elif 'verbose' in meta:
if meta['instrument'].lower() == 'mmirs':
instrument = "mmirs"
else:
instrument = "binospec"
else:
instrument = "binospec"
# Dallan's ObservatoryManager code is providing this value.
# Just keep track of it here so that we can send it back to
# the ObservatoryManager after scheduling is done.
if 'queuerun_id' in meta and not meta["queuerun_id"] is None:
queuerun_id = meta["queuerun_id"]
else:
queuerun_id = "0"
# Big substructure of "meta" of the allocation of time to different observing programs.
allocation = meta['allocation']
if False:
txt = json.dumps(allocation, indent=2,ensure_ascii=False)
print(txt)
# Big substructure of meta of the allocation of stats for programs:
# How much time has already be used for each program, etc.
stats = meta['stats']
if False:
txt = json.dumps(stats, indent=2,ensure_ascii=False)
print(txt)
# Big substructure of meta with the observation fields details.
# "fields" are really the same as "observing blocks".
# Using 'fields' here for historical purposes.
fields = meta['fields']
if True:
txt = json.dumps(fields, indent=2,ensure_ascii=False)
print(txt)
# Populate lookup tables.
for f in fields:
program_id2program[f['program_id']] = f['program']
long_name = get_name(f)
block_ids[long_name] = f['block_id']
objid_ids[long_name] = f['objid_id']
return True
def add_observer():
"""Adds an observer for the MMT Observatory to a scheduling calculation.
Args:
None
Returns:
Returns an Astroplan Observer instance for the MMT Observatory
Raises:
None.
"""
global mmto
global mmto_earth_location
mmto = Observer(longitude=249.11499999999998*u.deg,
latitude=31.688333333333333*u.deg,
elevation=2608*u.m,
name="mmto",
timezone="America/Phoenix")
# Also, need an EarthLocation version of the MMT location
mmto_earth_location = EarthLocation(lon=249.11499999999998*u.deg, \
lat=31.688333333333333*u.deg, \
height=2608*u.m, )
# times = Time(["2017-08-01 06:00", "2017-08-01 12:00", "2017-08-01 18:00"])
if False:
print(get_now(), mmto, mmto_earth_location)
return mmto
# Read in the table of targets
# from astropy.io import ascii
# target_table = ascii.read('targets.txt')
#targets = [FixedTarget(coord=SkyCoord(ra=ra*u.deg, dec=dec*u.deg), name=name)
# for name, ra, dec in target_table]
# Define a set a new Astroplan Constraints.
# These include:
# 1) MaskAngleConstraint
# 2) MaskNumberConstraint
# 3) MeridianConstraint
# 4) PIPriorityConstraint
# 5) RotatorConstraint
# 6) TimeAllocationConstraint
# 7) TimeConstraint (modified to handle multiple time interval)
#
# The Constraints imported from Astroplan include:
# 1) AirmassConstraint
# 2) AltitudeConstraint
# 3) AtNightConstraint
# A total of ten Constraints.
# This is derived from the SequentialScheduler class from astroplan 0.4
# There are additional attributes and logging of results, among other
# changes.
class MMTSequentialScheduler(Scheduler):
"""
A scheduler that does "stupid simple sequential scheduling". That is, it
simply looks at all the blocks, picks the best one, schedules it, and then
moves on.
"""
# The list "masks_used" can be local to this class,
# The structure "stats" needs to be global since it is
# updated here, but is used by constraint calculations,
# based upon those updated values.
def __init__(self, masks_used=None, \
default_masks=None, \
target_of_opportunity_ids='', \
*args, **kwargs):
super(MMTSequentialScheduler, self).__init__(*args, **kwargs)
# This class attribute keeps track of which masks have been
# scheduling as the new schedule is computed.
# Its initial value can either be an empty list or
# a list with mask_id's [110, 111]. (110 == imaging,
# 111 = Longslit1) These two masks are normally on Binospec.
# There may be a special case where them would be removed.
# An emply masks_used list would be used in that case.
self.masks_used = masks_used
self.default_masks = default_masks
self.target_of_opportunity_ids = [x.strip() for x in target_of_opportunity_ids.split(',')]
# Function needs to accept a list.
def _do_constraint(self, constraint, observer, target, times):
# Note: times must be iterable.
return constraint(observer, target, times)
def _make_schedule(self, blocks):
global daily_events, ToO
# By this time, we know if there are any targets-of-opportunity (ToO's) and the
# FixedTargets for scheduling have been created.
# So, loop through the objid_id's for any ToO's and add to ToO['all_ToO']
for objid in ToO['objid_id']:
t = fixed_targets[objid]
# Prevent duplicate entries.
if t not in ToO['all_ToO']:
# Note that these are SkyCoord objects, not FixedTarget objects.
ToO['all_ToO'].append(fixed_targets[objid].coord)
pre_filled = np.array([[block.start_time, block.end_time] for
block in self.schedule.scheduled_blocks])
if len(pre_filled) == 0:
a = self.schedule.start_time
filled_times = Time([a - 1*u.hour, a - 1*u.hour,
a - 1*u.minute, a - 1*u.minute])
pre_filled = filled_times.reshape((2, 2))
else:
filled_times = Time(pre_filled.flatten())
pre_filled = filled_times.reshape((int(len(filled_times)/2), 2))
for b in blocks:
if b.constraints is None:
b._all_constraints = self.constraints
else:
b._all_constraints = self.constraints + b.constraints
# to make sure the scheduler has some constraint to work off of
# and to prevent scheduling of targets below the horizon
# TODO : change default constraints to [] and switch to append
if b._all_constraints is None:
b._all_constraints = [AltitudeConstraint(min=0 * u.deg)]
b.constraints = [AltitudeConstraint(min=0 * u.deg)]
elif not any(isinstance(c, AltitudeConstraint) for c in b._all_constraints):
b._all_constraints.append(AltitudeConstraint(min=0 * u.deg))
if b.constraints is None:
b.constraints = [AltitudeConstraint(min=0 * u.deg)]
else:
b.constraints.append(AltitudeConstraint(min=0 * u.deg))
if test_MMTSequentialScheduler:
print("All Constraints: ", repr(b._all_constraints))
b._duration_offsets = u.Quantity([0*u.second, b.duration/2,
b.duration])
b.observer = self.observer
current_time = self.schedule.start_time
if test_MMTSequentialScheduler:
print("Current time: ", repr(current_time))
# print("Current time: ", repr(current_time), ", blocks:", repr(blocks))
constraint_details = []
while (len(blocks) > 0) and (current_time < self.schedule.end_time):
t = current_time.datetime
txt = str(Time.now()) + ", Begin scheduling for: " + str(t)
to_stdout(txt, mode, redis_client, instrument, do_redis)
# new code to skip through the daylight hours at the MMT...
# if it's after 7AM MST, jump to the next sunset time (+5 minutes)
if t.hour >= 14:
if use_daily_events:
comment = 'next_sunset'
key = get_sun_moon_date_key(comment, Time(t))
if key in daily_events:
current_time = daily_events[key]
if False:
print("current_time: ", repr(current_time))
else:
current_time = self.observer.sun_set_time(current_time,
which='next',
horizon=configs['max_solar_altitude'] * u.deg)
daily_events[key] = current_time
else:
current_time = self.observer.sun_set_time(current_time,
which='next',
horizon=configs['max_solar_altitude']*u.deg)
# This is resetting which masks could be used each night.
# For Binospec, we can change the masks every day.
# Even changing during the night is possible, but not
# desirable.
#
# See if this works. default_masks_used is a global.
self.masks_used = self.default_masks
##### This code allows a gap to be inserted into a queue schedule.
#####!!!!!! This is a hard-coded hack. If it's Feb 27, 2018,
#####!!!!!! advance scheduling to April 5, 2018
if t.year == 2018 and t.month == 2 and t.day == 27:
# Advancing 39.5 days. (Feb 26 to April 5)
current_time += 60*60*24*39.5*u.second
# Get the next sunset
if use_daily_events:
comment = 'next_sunset'
key = get_sun_moon_date_key(comment, Time(t))
if key in daily_events:
current_time = daily_events[key]
if False:
print("current_time: ", repr(current_time))
else:
current_time = self.observer.sun_set_time(current_time,
which='next',
horizon=configs['max_solar_altitude'] * u.deg)
daily_events[key] = current_timg
else:
current_time = self.observer.sun_set_time(current_time,
which='next',
horizon=configs['max_solar_altitude'] * u.deg)
# current_time = self.observer.sun_set_time(current_time, \
# which='next', \
# horizon=configs['max_solar_altitude']*u.deg)
#####!!!!!! End of hard-coded hack.
# Adding a five--minute "buffer" after sunset.
# We need to do this so that we don't fail the "max_solar_altitude" criteria
# at the beginning of the night.
current_time += 300*u.second
current_time.format = 'isot'
txt = str(Time.now()) + ", Advancing scheduling to: " + str(current_time.datetime)
to_stdout(txt, mode, redis_client, instrument, do_redis)
# first compute the value of all the constraints for each block
# given the current starting time
if test_MMTSequentialScheduler:
print("Current time: ", repr(current_time), ", blocks:", repr(blocks))
block_transitions = []
block_scores = []
block_constraint_results = []
constraint_scores = {}
target_constraint_scores = {}
#
# New: Target of Opportunity (ToO's) code section
#
# Pre-processing observing blocks for any ToO's:
#
if True:
ToO['observable_ToO'] = []
# Passing in the target_of_opportunity_names through a configuration
# parameter. This CSV string is parsed during initialization.
if False:
print("targets of opportunity target ids: ", self.target_of_opportunity_names)
if len(ToO['all_ToO']) > 0:
for b in blocks:
name = get_target_name(b)
if False:
print("Name: ", name)
ToO['found_ToO'] = False
found = False
for skycoord in ToO['all_ToO']:
if b.target.coord == skycoord:
target = b.target
# Calculate the time duration of the block.
#
# First figure out the transition
#
# We are not using transition blocks at the moment so "trans" should
# be None and the transition_time will be 0 seconds.
# Adding the code in case we start using transition blocks.
if len(self.schedule.observing_blocks) > 0:
trans = self.transitioner(
self.schedule.observing_blocks[-1], b, current_time, self.observer)
else:
trans = None
transition_time = 0*u.second if trans is None else trans.duration
times = current_time + transition_time + b._duration_offsets
# If the block is a ToO and is always observable for the time duration,
# then we want to schedule it.
#
# A zero will be set to any non-ToO blocks in the next section of code.
#
if np.all(is_always_observable(b._all_constraints, self.observer, [target], times)):
ToO['found_ToO'] = True
# Note that which_ToO is a SkyCoord to be compatible with constraints,
# not a FixedTarget or an observing block.
if skycoord not in ToO['observable_ToO']:
ToO['observable_ToO'].append(skycoord)
if False:
print("1421: ToO", repr(ToO))
print("break")
if False:
print("3643 ToO: ", repr(ToO))
# This is where we would parallelize for multiple blocks.
for b in blocks:
# first figure out the transition
if len(self.schedule.observing_blocks) > 0:
trans = self.transitioner(
self.schedule.observing_blocks[-1], b, current_time, self.observer)
else:
trans = None
block_transitions.append(trans)
transition_time = 0*u.second if trans is None else trans.duration
times = current_time + transition_time + b._duration_offsets
# make sure it isn't in a pre-filled slot
if (any((current_time < filled_times) & (filled_times < times[2])) or
any(abs(pre_filled.T[0]-current_time) < 1*u.second)):
block_constraint_results.append(0)
else:
constraint_res = []
#
# Target of Opportunity (ToO) calculations:
#
# If we found a ToO and if the target for the block is
# the ToO, append a constraint score result of 1.
# Otherwise, append a constraint score of 0.
# This latter case will cause the overall_score to be zero for all non-ToO blocks.
#
# Code needs testing.
if False:
print("15352, ToO: ", repr(ToO))
if ToO['found_ToO']:
# See if the target is a ToO.
if b.target.coord is ToO['observable_ToO']:
# Appending a 1, which has no overall effect when the
# constraint results are multiplied for the overall score.
# Note that several OB may have a score of 1 here if they
# are for the same ToO target.
# Other constraints will rank blocks with the same ToO target.
if False:
print("constraint_res append 1")
constraint_res.append(1.0)
else:
# Appending a zero to the constraint results list, this will
# cause the overall score to be zero when all results are
# multiplied together.
if False:
print("constraint_res append 0")
constraint_res.append(0.1)
else:
# Doing this for consistency so that each block will have the same
# number of constraint results to be multiplied for the overall score.
if False:
print("constraint_res append 1")
constraint_res.append(1.0)
for constraint in b._all_constraints:
key = get_key(constraint, b.target, times[0], time2=times[-1])
if False:
# This "if" branch:
# 1) does not use the sqlite database for caching
c = constraint(self.observer, b.target, times)
score = np.prod(c)
else:
obj = get_score(conn, key)
# These astronomical constraints will not change with programmatic changes,
# so we can use cached values.
if ("RotatorConstraint" in key or \
"TargetOfOpportunityConstraint" in key or \
"AirmassConstraint" in key or \
"AltitudeConstraint" in key or \
"MeridianConstraint" in key or \
"AtNightConstraint" in key or \
"MoonSeparationConstraint" in key) and \
obj is not None:
# Not using stored scores for now. We may be able to
# use some scores, such as MeridianConstraint, but
# probably not programmatic constraints, such as
# TimeAllocationConstraint. Programmatic constraints
# should be recalculated in case something has changed.
if False:
print("obj: ", repr(obj))
score = float(obj['value'])
if schedule_id != obj['schedule_id']:
# Updating this score. Commonly, the current
# schedule_id will be newer than the saved score.
# We've calculated this target/time/constraint
# combination before for an older schedule.
# We want to keep the schedule_id with
# the most recent schedule.
schedule_MST = obj['schedule_MST']
set_score(conn,key,score,time=schedule_MST,schedule_id=schedule_id)
if False:
print("key:", key, ", using saved score:", score)
else:
if True:
try:
c = constraint(self.observer, b.target, times)
score = np.prod(c)
except:
print("traceback: ", traceback.format_exc())
# We shouldn't get here. Something is wrong with the input values.
print("Cannot calculate constraint score for ", get_constraint_name(constraint))
schedule_time = localize_time(times[0])
set_score(conn,key,score,time=schedule_time,schedule_id=schedule_id)
if verbose3:
print(key, ": ", score)
constraint_res.append(score)
target_name = get_target_name(b)
constraint_name = get_constraint_name(constraint)
if target_name not in target_constraint_scores:
target_constraint_scores[target_name] = {}
if False:
print("target_name: ", target_name, ", constraint_name: ", constraint_name, ", score: ", str(score))
target_constraint_scores[target_name][constraint_name] = score
schedule_time = localize_time(times[0])
set_score(conn,key,score,time=schedule_time,schedule_id=schedule_id)
# take the product over all the constraints *and* times
overall_score = np.prod(constraint_res)
# Saving overall score for this target to sqlite.
target_key = get_target_key(target_name, times[0], time2=times[-1])
schedule_time = localize_time(times[0])
set_score(conn,target_key,overall_score,time=schedule_time,schedule_id=schedule_id)
block_constraint_results.append(overall_score)
# Need the block to calculated RA, Dec, etc. later.
block_scores.append({"overall_score":overall_score,"name":b.target.name,"block":b})
constraint_scores[b.target.name] = overall_score
if verbose:
txt = "***** Target: " + b.target.name.ljust(25) + " overall_score: " + \
str(round(overall_score,8)).ljust(12) + " *****"
to_stdout(txt, mode, redis_client, instrument, do_redis)
# now identify the block that's the best
bestblock_idx = np.argmax(block_constraint_results)
txt = "***** Best result: " + str(block_constraint_results[bestblock_idx]) + " *****"
to_stdout(txt, mode, redis_client, instrument, do_redis)
if block_constraint_results[bestblock_idx] == 0.:
# if even the best is unobservable, we need a gap
current_time += self.gap_time
txt = "Adding gap_time", str(self.gap_time)
to_stdout(txt, mode, redis_client, instrument, do_redis)
else:
# If there's a best one that's observable, first get its transition
trans = block_transitions.pop(bestblock_idx)
if trans is not None:
self.schedule.insert_slot(trans.start_time, trans)