Debian Codegraph @

docs/tutorials/scheduling.rst

raw
1 .. _scheduling_tutorial:
2
3 .. doctest-skip-all
4
5 ***************************
6 Scheduling an Observing Run
7 ***************************
8
9 .. note::
10
11 Some terms used have been defined in :ref:`Terminology <terminology>`.
12
13 Contents
14 ========
15
16 * :ref:`scheduling-defining_targets`
17
18 * :ref:`scheduling-creating_constraints_and_observing_blocks`
19
20 * :ref:`scheduling-creating_a_transitioner`
21
22 * :ref:`scheduling-scheduling`
23
24 * :ref:`scheduling-user_defined_schedulers`
25
26 * :ref:`scheduling-using_the_scorer`
27
28 .. _scheduling-defining_targets:
29
30 Defining Targets
31 ================
32
33 We want to observe Deneb and M13 in the B, V and R filters. We are scheduled
34 for the first half-night on July 6 2016 and want to know the order we should
35 schedule the targets in.
36
37 First we define our `~astroplan.Observer` object (where we are observing from):
38
39 .. code-block:: python
40
41 >>> from astroplan import Observer
42
43 >>> apo = Observer.at_site('apo')
44
45 Now we want to define our list of targets (`~astroplan.FixedTarget` objects),
46 any object that is in SIMBAD can be called by an identifier.
47
48 .. code-block:: python
49
50 >>> from astroplan import FixedTarget
51
52 >>> # Initialize the targets
53 >>> deneb = FixedTarget.from_name('Deneb')
54 >>> m13 = FixedTarget.from_name('M13')
55
56 >>> deneb
57 <FixedTarget "deneb" at SkyCoord (ICRS): (ra, dec) in deg (310.35797975, 45.28033881)>
58
59 >>> m13
60 <FixedTarget "M13" at SkyCoord (ICRS): (ra, dec) in deg (250.423475, 36.4613194)>
61
62 We also need to define bounds within which our blocks will be scheduled
63 using `~astropy.time.Time` objects. Our bounds will be from the noon
64 before our observation, to the noon after (19:00 UTC). Later we will
65 account for only being able to use the first half of the night.
66
67 .. code-block:: python
68
69 >>> from astropy.time import Time
70
71 >>> noon_before = Time('2016-07-06 19:00')
72 >>> noon_after = Time('2016-07-07 19:00')
73
74 :ref:`Return to Top <scheduling_tutorial>`
75
76 .. _scheduling-creating_constraints_and_observing_blocks:
77
78 Creating Constraints and Observing Blocks
79 =========================================
80
81 An in-depth tutorial on creating and using constraints can be found in
82 the :ref:`constraint tutorial <constraints>`.
83
84 Constraints, when evaluated, take targets and times, and give scores that
85 indicate how well the combination of target and time fulfill the constraint.
86 We want to make sure that our targets will be high in the sky while observed
87 and that they will be observed during the night. We don't want any object to
88 be observed at an airmass greater than 3, but we prefer a better airmass.
89 Usually constraints scores are boolean, but with ``boolean_constraint = False``
90 the constraint will output floats instead, indicated when it is closer to ideal.
91
92 .. code-block:: python
93
94 >>> from astroplan.constraints import AtNightConstraint, AirmassConstraint
95
96 >>> # create the list of constraints that all targets must satisfy
97 >>> global_constraints = [AirmassConstraint(max = 3, boolean_constraint = False),
98 ... AtNightConstraint.twilight_civil()]
99
100 Now that we have constraints that we will apply to every target, we need to
101 create an `~astroplan.ObservingBlock` for each target+configuration
102 combination. An observing block needs a target, a duration, and a priority;
103 configuration information can also be given (i.e. filter, instrument, etc.).
104 For each filter we want 16 exposures per target (100 seconds for M13 and 60
105 seconds for Deneb) and the instrument has a read-out time of 20 seconds.
106 The half night goes from 7PM local time to 1AM local time, in UTC this will
107 be from 2AM to 8AM, so we use `~astroplan.constraints.TimeConstraint`.
108
109 .. code-block:: python
110
111 >>> from astroplan import ObservingBlock
112 >>> from astroplan.constraints import TimeConstraint
113 >>> from astropy import units as u
114
115 >>> # Define the read-out time, exposure duration and number of exposures
116 >>> read_out = 20 * u.second
117 >>> deneb_exp = 60*u.second
118 >>> m13_exp = 100*u.second
119 >>> n = 16
120 >>> blocks = []
121
122 >>> half_night_start = Time('2016-07-07 02:00')
123 >>> half_night_end = Time('2016-07-07 08:00')
124 >>> first_half_night = TimeConstraint(half_night_start, half_night_end)
125 >>> # Create ObservingBlocks for each filter and target with our time
126 >>> # constraint, and durations determined by the exposures needed
127 >>> for priority, bandpass in enumerate(['B', 'G', 'R']):
128 ... # We want each filter to have separate priority (so that target
129 ... # and reference are both scheduled)
130 ... b = ObservingBlock.from_exposures(deneb, priority, deneb_exp, n, read_out,
131 ... configuration = {'filter': bandpass},
132 ... constraints = [first_half_night])
133 ... blocks.append(b)
134 ... b = ObservingBlock.from_exposures(m13, priority, m13_exp, n, read_out,
135 ... configuration = {'filter': bandpass},
136 ... constraints = [first_half_night])
137 ... blocks.append(b)
138
139 .. _scheduling-creating_a_transitioner:
140
141 Creating a Transitioner
142 =======================
143
144 Now that we have observing blocks, we need to define how the telescope
145 transitions between them. The first parameter needed is the slew_rate
146 of the telescope (degrees/second) and the second is a dictionary that
147 tells how long it takes to transition between two configurations. You
148 can also give a default duration if you aren't able to give one for
149 each pair of configurations.
150
151 .. code-block:: python
152
153 >>> from astroplan.scheduling import Transitioner
154
155 >>> # Initialize a transitioner object with the slew rate and/or the
156 >>> # duration of other transitions (e.g. filter changes)
157 >>> slew_rate = .8*u.deg/u.second
158 >>> transitioner = Transitioner(slew_rate,
159 ... {'filter':{('B','G'): 10*u.second,
160 ... ('G','R'): 10*u.second,
161 ... 'default': 30*u.second}})
162
163 The transitioner now knows that it takes 10 seconds to go from 'B' to 'G',
164 or from 'G' to 'R' but has to use the default transition time of 30 seconds
165 for any other transition between filters. Non-transitions, like 'g' to 'g',
166 will not take any time though.
167
168 .. _scheduling-scheduling:
169
170 Scheduling
171 ==========
172
173 Now all we have left is to initialize the scheduler, input our list
174 of blocks and the schedule to put them in. There are currently two
175 schedulers to choose from in astroplan.
176
177 The first is a sequential scheduler. It starts at the start_time and
178 scores each block (constraints and target) at that time and then
179 schedules it, it then moves to where the first observing block stops
180 and repeats the scoring and scheduling on the remaining blocks.
181
182 .. code-block:: python
183
184 >>> from astroplan.scheduling import SequentialScheduler
185 >>> from astroplan.scheduling import Schedule
186
187 >>> # Initialize the sequential scheduler with the constraints and transitioner
188 >>> seq_scheduler = SequentialScheduler(constraints = global_constraints,
189 ... observer = apo,
190 ... transitioner = transitioner)
191 >>> # Initialize a Schedule object, to contain the new schedule
192 >>> sequential_schedule = Schedule(noon_before, noon_after)
193
194 >>> # Call the schedule with the observing blocks and schedule to schedule the blocks
195 >>> seq_scheduler(blocks, sequential_schedule)
196
197 The second is a priority scheduler. It sorts the blocks by their
198 priority (multiple blocks with the same priority will stay in the
199 order they were in), then schedules them one-by-one at the best
200 time for that block (highest score).
201
202 .. code-block:: python
203
204 >>> from astroplan.scheduling import PriorityScheduler
205
206 >>> # Initialize the priority scheduler with the constraints and transitioner
207 >>> prior_scheduler = PriorityScheduler(constraints = global_constraints,
208 ... observer = apo,
209 ... transitioner = transitioner)
210 >>> # Initialize a Schedule object, to contain the new schedule
211 >>> priority_schedule = Schedule(noon_before, noon_after)
212
213 >>> # Call the schedule with the observing blocks and schedule to schedule the blocks
214 >>> prior_scheduler(blocks, priority_schedule)
215
216 Now that you have a schedule there are a few ways of viewing it.
217 One way is to have it print a table where you can show, or hide,
218 unused time and transitions with ``show_transitions`` and
219 ``show_unused`` (default is showing transitions and not unused).
220
221 .. code-block:: python
222
223 >>> priority_schedule.to_table()
224 target start time (UTC) end time (UTC) duration (minutes) ra dec configuration
225 str15 str23 str23 float64 str32 str32 object
226 --------------- ----------------------- ----------------------- ------------------ --------------- -------------- -----------------
227 M13 2016-07-07 03:49:20.019 2016-07-07 04:21:20.019 32.0 250d25m24.51s 36d27m40.7498s {'filter': 'R'}
228 TransitionBlock 2016-07-07 04:21:20.019 2016-07-07 04:22:00.019 0.666666666667 ['filter:R to B']
229 M13 2016-07-07 04:25:20.021 2016-07-07 04:57:20.021 32.0 250d25m24.51s 36d27m40.7498s {'filter': 'B'}
230 TransitionBlock 2016-07-07 04:57:20.021 2016-07-07 04:57:40.021 0.333333333333 ['filter:B to G']
231 M13 2016-07-07 04:57:40.021 2016-07-07 05:29:40.021 32.0 250d25m24.51s 36d27m40.7498s {'filter': 'G'}
232 TransitionBlock 2016-07-07 05:29:40.021 2016-07-07 05:31:00.021 1.33333333333 ['filter:G to R']
233 Deneb 2016-07-07 06:44:00.026 2016-07-07 07:05:20.026 21.3333333333 310d21m28.7271s 45d16m49.2197s {'filter': 'R'}
234 TransitionBlock 2016-07-07 07:05:20.026 2016-07-07 07:06:00.026 0.666666666667 ['filter:R to G']
235 Deneb 2016-07-07 07:09:20.027 2016-07-07 07:30:40.027 21.3333333333 310d21m28.7271s 45d16m49.2197s {'filter': 'G'}
236 TransitionBlock 2016-07-07 07:30:40.027 2016-07-07 07:31:20.027 0.666666666667 ['filter:G to B']
237 Deneb 2016-07-07 07:34:40.028 2016-07-07 07:56:00.028 21.3333333333 310d21m28.7271s 45d16m49.2197s {'filter': 'B'}
238
239 The other way is to plot the schedule against the airmass of the
240 targets.
241
242 .. code-block:: python
243
244 >>> from astroplan.plots import plot_schedule_airmass
245 >>> import matplotlib.pyplot as plt
246
247 >>> # plot the schedule with the airmass of the targets
248 >>> plt.figure(figsize = (14,6))
249 >>> plot_schedule_airmass(priority_schedule)
250 >>> plt.legend(loc = "upper right")
251 >>> plt.show()
252
253 .. plot::
254
255 # first import everything we will need for the scheduling
256 import astropy.units as u
257 from astropy.time import Time
258 from astroplan import (Observer, FixedTarget, ObservingBlock, Transitioner, PriorityScheduler,
259 Schedule)
260 from astroplan.constraints import AtNightConstraint, AirmassConstraint, TimeConstraint
261 from astroplan.plots import plot_schedule_airmass
262 import matplotlib.pyplot as plt
263
264 # Now we define the targets, observer, start time, and end time of the schedule.
265 deneb = FixedTarget.from_name('Deneb')
266 m13 = FixedTarget.from_name('M13')
267
268 noon_before = Time('2016-07-06 19:00')
269 noon_after = Time('2016-07-07 19:00')
270 apo = Observer.at_site('apo')
271
272 # Then define the constraints (global and specific) and make a list of the
273 # observing blocks that you want scheduled
274 global_constraints = [AirmassConstraint(max = 3, boolean_constraint = False),
275 AtNightConstraint.twilight_civil()]
276 # defining the read-out time, exposure duration and number of exposures
277 read_out = 20 * u.second
278 deneb_exp = 60*u.second
279 m13_exp = 100*u.second
280 n = 16
281 blocks = []
282 first_half_night = TimeConstraint(Time('2016-07-07 02:00'), Time('2016-07-07 08:00'))
283 for priority, bandpass in enumerate(['B', 'G', 'R']):
284 # We want each filter to have separate priority (so that target
285 # and reference are both scheduled)
286 b = ObservingBlock.from_exposures(deneb, priority, deneb_exp, n, read_out,
287 configuration = {'filter': bandpass},
288 constraints = [first_half_night])
289 blocks.append(b)
290 b = ObservingBlock.from_exposures(m13, priority, m13_exp, n, read_out,
291 configuration = {'filter': bandpass},
292 constraints = [first_half_night])
293 blocks.append(b)
294
295 # Define how the telescope transitions between the configurations defined in the
296 # observing blocks (target, filter, instrument, etc.).
297 transitioner = Transitioner(.8*u.deg/u.second,
298 {'filter':{('B','G'): 10*u.second,
299 ('G','R'): 10*u.second,
300 'default': 30*u.second}})
301
302 # Initialize the scheduler
303 prior_scheduler = PriorityScheduler(constraints = global_constraints,
304 observer = apo, transitioner = transitioner)
305 # Create a schedule for the scheduler to insert the blocks into, and run the scheduler
306 priority_schedule = Schedule(noon_before, noon_after)
307 prior_scheduler(blocks, priority_schedule)
308
309 # To get a plot of the airmass vs where the blocks were scheduled
310 plt.figure(figsize = (14,6))
311 plot_schedule_airmass(priority_schedule)
312 plt.tight_layout()
313 plt.legend(loc="upper right")
314 plt.show()
315
316 There is a lot of unfilled space in our schedule currently. We can
317 fill that time with more observations of our targets by calling our
318 scheduler using the same blocks and the schedule we already added to.
319
320 .. code-block:: python
321
322 >>> prior_schedule(blocks, priority_schedule)
323 >>> plt.figure(figsize = (14,6))
324 >>> plot_schedule_airmass(priority_schedule)
325 >>> plt.legend(loc = "upper right")
326 >>> plt.show()
327
328 .. plot::
329
330 # first import everything we will need for the scheduling
331 import astropy.units as u
332 from astropy.time import Time
333 from astroplan import (Observer, FixedTarget, ObservingBlock, Transitioner, PriorityScheduler,
334 Schedule)
335 from astroplan.constraints import AtNightConstraint, AirmassConstraint, TimeConstraint
336 from astroplan.plots import plot_schedule_airmass
337 import matplotlib.pyplot as plt
338
339 # Now we define the targets, observer, start time, and end time of the schedule.
340 deneb = FixedTarget.from_name('Deneb')
341 m13 = FixedTarget.from_name('M13')
342
343 noon_before = Time('2016-07-06 19:00')
344 noon_after = Time('2016-07-07 19:00')
345 apo = Observer.at_site('apo')
346
347 # Then define the constraints (global and specific) and make a list of the
348 # observing blocks that you want scheduled
349 global_constraints = [AirmassConstraint(max = 3, boolean_constraint = False),
350 AtNightConstraint.twilight_civil()]
351 rot = 20 * u.second
352 blocks = []
353 first_half_night = TimeConstraint(Time('2016-07-07 02:00'), Time('2016-07-07 08:00'))
354 for priority, bandpass in enumerate(['B', 'G', 'R']):
355 # We want each filter to have separate priority (so that target
356 # and reference are both scheduled)
357 blocks.append(ObservingBlock.from_exposures(deneb, priority, 60*u.second, 16, rot,
358 configuration = {'filter': bandpass},
359 constraints = [first_half_night]))
360 blocks.append(ObservingBlock.from_exposures(m13, priority, 100*u.second, 16, rot,
361 configuration = {'filter': bandpass},
362 constraints = [first_half_night]))
363
364 # Define how the telescope transitions between the configurations defined in the
365 # observing blocks (target, filter, instrument, etc.).
366 transitioner = Transitioner(.8*u.deg/u.second,
367 {'filter':{('B','G'): 10*u.second,
368 ('G','R'): 10*u.second,
369 'default': 30*u.second}})
370
371 # Initialize the scheduler
372 prior_scheduler = PriorityScheduler(constraints = global_constraints,
373 observer = apo, transitioner = transitioner)
374 # Create a schedule for the scheduler to insert the blocks into, and run the scheduler
375 priority_schedule = Schedule(noon_before, noon_after)
376 prior_scheduler(blocks, priority_schedule)
377 # add more of the blocks into the schedule
378 prior_scheduler(blocks, priority_schedule)
379
380 # To get a plot of the airmass vs where the blocks were scheduled
381 plt.figure(figsize = (14,6))
382 plot_schedule_airmass(priority_schedule)
383 plt.tight_layout()
384 plt.legend(loc="upper right")
385 plt.show()
386
387 We want to check if there is any way that we could observe Alpha
388 Centauri A as well during our time slot. So we create a new block
389 for it with priority over the others, add it to our list of blocks
390 and run the priority scheduler again.
391
392 .. code-block:: python
393
394 >>> alpha_cen = FixedTarget.from_name('Alpha Centauri A')
395 >>> # ObservingBlocks can also be called with arguments: target, duration, priority
396 >>> blocks.append(ObservingBlock(alpha_cen, 20*u.minute, -1))
397 >>> # Initialize a new schedule for this test
398 >>> schedule = Schedule(start_time, end_time)
399 >>> prior_scheduler(blocks, schedule)
400
401 >>> plt.figure(figsize = (14,6))
402 >>> plot_schedule_airmass(priority_schedule)
403 >>> plt.legend(loc = "upper right")
404 >>> plt.show()
405
406 .. plot::
407
408 # first import everything we will need for the scheduling
409 import astropy.units as u
410 from astropy.time import Time
411 from astroplan import (Observer, FixedTarget, ObservingBlock, Transitioner, PriorityScheduler,
412 Schedule)
413 from astroplan.constraints import AtNightConstraint, AirmassConstraint, TimeConstraint
414 from astroplan.plots import plot_schedule_airmass
415 import matplotlib.pyplot as plt
416
417 # Now we define the targets, observer, start time, and end time of the schedule.
418 deneb = FixedTarget.from_name('Deneb')
419 m13 = FixedTarget.from_name('M13')
420
421 noon_before = Time('2016-07-06 19:00')
422 noon_after = Time('2016-07-07 19:00')
423 apo = Observer.at_site('apo')
424
425 # Then define the constraints (global and specific) and make a list of the
426 # observing blocks that you want scheduled
427 global_constraints = [AirmassConstraint(max = 3, boolean_constraint = False),
428 AtNightConstraint.twilight_civil()]
429 # defining the read-out time, exposure duration and number of exposures
430 read_out = 20 * u.second
431 deneb_exp = 60*u.second
432 m13_exp = 100*u.second
433 n = 16
434 blocks = []
435 first_half_night = TimeConstraint(Time('2016-07-07 02:00'), Time('2016-07-07 08:00'))
436 for priority, bandpass in enumerate(['B', 'G', 'R']):
437 # We want each filter to have separate priority (so that target
438 # and reference are both scheduled)
439 b = ObservingBlock.from_exposures(deneb, priority, deneb_exp, n, read_out,
440 configuration = {'filter': bandpass},
441 constraints = [first_half_night])
442 blocks.append(b)
443 b = ObservingBlock.from_exposures(m13, priority, m13_exp, n, read_out,
444 configuration = {'filter': bandpass},
445 constraints = [first_half_night])
446 blocks.append(b)
447 # add the new target's block
448 alpha_cen = FixedTarget.from_name('Alpha Centauri A')
449 blocks.append(ObservingBlock(alpha_cen, 20*u.minute, -1))
450
451 # Define how the telescope transitions between the configurations defined in the
452 # observing blocks (target, filter, instrument, etc.).
453 transitioner = Transitioner(.8*u.deg/u.second,
454 {'filter':{('B','G'): 10*u.second,
455 ('G','R'): 10*u.second,
456 'default': 30*u.second}})
457
458 # Initialize the scheduler
459 prior_scheduler = PriorityScheduler(constraints = global_constraints,
460 observer = apo, transitioner = transitioner)
461 # Create a schedule for the scheduler to insert the blocks into, and run the scheduler
462 priority_schedule = Schedule(noon_before, noon_after)
463 prior_scheduler(blocks, priority_schedule)
464
465 # To get a plot of the airmass vs where the blocks were scheduled
466 plt.figure(figsize = (14,6))
467 plot_schedule_airmass(priority_schedule)
468 plt.tight_layout()
469 plt.legend(loc="upper right")
470 plt.show()
471
472 Nothing new shows up because Alpha Centauri isn't visible from APO.
473
474 .. _scheduling-user_defined_schedulers:
475
476 User-Defined Schedulers
477 =======================
478
479 There are many ways that targets can be scheduled, only two of which
480 are currently implemented. This example will walk through the steps for
481 creating your own scheduler that will be compatible with the tools of
482 the ``scheduling`` module.
483
484 As you may have noticed above, the schedulers are assembled by making a
485 call to the initializer of the class (e.g. `~astroplan.scheduling.PriorityScheduler`).
486 Each of the schedulers is subclassed from the abstract `astroplan.scheduling.Scheduler`
487 class, and our custom scheduler needs to be as well.
488
489 A scheduler needs to be able to schedule observing blocks where they have a non-zero
490 score (i.e. they satisfy all of their constraints). For our scheduler, we will make
491 one that schedules ``ObservingBlocks`` at the first unoccupied place they have a score
492 greater than zero: a ``SimpleScheduler``. We need to include two methods, ``__init__``
493 and ``_make_schedule`` for it to work:
494
495 * The ``__init__`` is already defined by the super class, and accepts global constraints,
496 the `~astroplan.Observer`, the `~astroplan.scheduling.Transitioner`, a ``gap_time``,
497 and a ``time_resolution`` for spacing during the creation of the schedule.
498
499 * It also needs a ``_make_schedule`` to do the heavy lifting. This takes a list of
500 `~astroplan.scheduling.ObservingBlock` objects and a `~astroplan.scheduling.Schedule`
501 object to input them into. This method needs to be able to check whether a
502 block can be scheduled in a given spot, and be able to insert it into the
503 schedule once a suitable spot has been found. For score evaluation we will
504 use the built-in `~astroplan.scheduling.Scorer`.
505
506 Here's the ``SimpleScheduler`` implementation::
507
508 from astroplan.scheduling import Scheduler, Scorer
509 from astroplan.utils import time_grid_from_range
510 from astroplan.constraints import AltitudeConstraint
511 from astropy import units as u
512
513 import numpy as np
514
515 class SimpleScheduler(Scheduler):
516 """
517 schedule blocks randomly
518 """
519 def __init__(self, *args, **kwargs):
520 super(SimpleScheduler, self).__init__(*args, **kwargs)
521
522 def _make_schedule(self, blocks):
523 # gather all the constraints on each block into a single attribute
524 for b in blocks:
525 if b.constraints is None:
526 b._all_constraints = self.constraints
527 else:
528 b._all_constraints = self.constraints + b.constraints
529
530 # to make sure the Scorer has some constraint to work off of
531 # and to prevent scheduling of targets below the horizon
532 if b._all_constraints is None:
533 b._all_constraints = [AltitudeConstraint(min=0*u.deg)]
534 b.constraints = [AltitudeConstraint(min=0*u.deg)]
535 elif not any(isinstance(c, AltitudeConstraint) for c in b._all_constraints):
536 b._all_constraints.append(AltitudeConstraint(min=0*u.deg))
537 if b.constraints is None:
538 b.constraints = [AltitudeConstraint(min=0*u.deg)]
539 else:
540 b.constraints.append(AltitudeConstraint(min=0*u.deg))
541 b.observer = self.observer
542
543 # before we can schedule, we need to know where blocks meet the constraints
544 scorer = Scorer(blocks, self.observer, self.schedule,
545 global_constraints=self.constraints)
546 score_array = scorer.create_score_array(self.time_resolution)
547 # now we have an array of the scores for the blocks at intervals of
548 # ``time_resolution``. The scores range from zero to one, some blocks may have
549 # higher scores than others, but we only care if they are greater than zero
550
551 # we want to start from the beginning and start scheduling
552 start_time = self.schedule.start_time
553 current_time = start_time
554 while current_time < self.schedule.end_time:
555 scheduled = False
556 i=0
557 while i < len(blocks) and scheduled is False:
558 block = blocks[i]
559 # the schedule starts with only 1 slot
560 if len(self.schedule.slots) == 1:
561 test_time = current_time
562 # when a block is inserted, the number of slots increases
563 else:
564 # a test transition between the last scheduled block and this one
565 transition = self.transitioner(schedule.observing_blocks[-1],
566 block, current_time, self.observer)
567 test_time = current_time + transition.duration
568 # how many time intervals are we from the start
569 start_idx = int((test_time - start_time)/self.time_resolution)
570 duration_idx = int(block.duration/self.time_resolution)
571 # if any score during the block's duration would be 0, reject it
572 if any(score_array[i][start_idx:start_idx+duration_idx] == 0):
573 i +=1
574 # if all of the scores are >0, accept and schedule it
575 else:
576 if len(self.schedule.slots) >1:
577 self.schedule.insert_slot(current_time, transition)
578 self.schedule.insert_slot(test_time, block)
579 # advance the time and remove the block from the list
580 current_time = test_time + block.duration
581 scheduled = True
582 blocks.remove(block)
583 # if every block failed, progress the time
584 if i == len(blocks):
585 current_time += self.gap_time
586 return schedule
587
588 Then to use our new scheduler, we just need to call it how we did
589 up above::
590
591 >>> from astroplan.constraints import AtNightConstraint
592 >>> from astroplan.scheduling import Schedule, ObservingBlock
593 >>> from astroplan import FixedTarget, Observer, Transitioner
594 >>> from astropy.time import Time
595
596 >>> # Initialize the observer and targets, and create observing blocks
597 >>> apo = Observer.at_site('apo')
598 >>> deneb = FixedTarget.from_name('Deneb')
599 >>> m13 = FixedTarget.from_name('M13')
600 >>> blocks = [ObservingBlock(deneb, 20*u.minute, 0)]
601 >>> blocks.append(ObservingBlock(m13, 20*u.minute, 0))
602
603 >>> # For a telescope that can slew at a rate of 2 degrees/second
604 >>> transitioner = Transitioner(slew_rate=2*u.deg/u.second)
605
606 >>> # Schedule the observing blocks using the simple scheduler
607 >>> schedule = Schedule(Time('2016-07-06 19:00'), Time('2016-07-07 19:00'))
608 >>> scheduler = SimpleScheduler(observer = apo, transitioner = transitioner,
609 ... constraints = [])
610 >>> scheduler(blocks, schedule)
611
612 >>> # Plot the created schedule
613 >>> import matplotlib.pyplot as plt
614 >>> from astroplan.plots import plot_schedule_airmass
615 >>> plot_schedule_airmass(schedule)
616 >>> plt.legend()
617 >>> plt.show()
618
619 .. plot::
620
621 from astroplan.scheduling import Scheduler, Scorer
622 from astroplan.utils import time_grid_from_range
623 from astroplan.constraints import AltitudeConstraint
624 from astropy import units as u
625
626 import numpy as np
627
628 class SimpleScheduler(Scheduler):
629 """
630 schedule blocks randomly
631 """
632 def __init__(self, *args, **kwargs):
633 super(SimpleScheduler, self).__init__(*args, **kwargs)
634
635 def _make_schedule(self, blocks):
636 # gather all the constraints on each block into a single attribute
637 for b in blocks:
638 if b.constraints is None:
639 b._all_constraints = self.constraints
640 else:
641 b._all_constraints = self.constraints + b.constraints
642 # to make sure the Scorer has some constraint to work off of
643 # and to prevent scheduling of targets below the horizon
644 if b._all_constraints is None:
645 b._all_constraints = [AltitudeConstraint(min=0*u.deg)]
646 b.constraints = [AltitudeConstraint(min=0*u.deg)]
647 elif not any(isinstance(c, AltitudeConstraint) for c in b._all_constraints):
648 b._all_constraints.append(AltitudeConstraint(min=0*u.deg))
649 if b.constraints is None:
650 b.constraints = [AltitudeConstraint(min=0*u.deg)]
651 else:
652 b.constraints.append(AltitudeConstraint(min=0*u.deg))
653 b.observer = self.observer
654
655 # before we can schedule, we need to know where blocks meet the constraints
656 scorer = Scorer(blocks,self.observer, self.schedule, global_constraints=self.constraints)
657 score_array = scorer.create_score_array(self.time_resolution)
658 # now we have an array with the scores for all of the blocks at intervals of time_resolution
659
660 # we want to start from the beginning and start scheduling
661 current_time = self.schedule.start_time
662 while current_time < self.schedule.end_time:
663 scheduled = False
664 i=0
665 while i < len(blocks) and scheduled is False:
666 block = blocks[i]
667 # the schedule starts with only 1 slot
668 if len(self.schedule.slots) == 1:
669 test_time = current_time
670 # when a block is inserted, the number of slots increases
671 else:
672 # make a transition between the last scheduled block and this one
673 transition = self.transitioner(schedule.observing_blocks[-1], block,
674 current_time, self.observer)
675 test_time = current_time + transition.duration
676 # how far from the start is the time we are testing
677 start_idx = int((test_time - self.schedule.start_time)/self.time_resolution)
678 duration_idx = int(block.duration/self.time_resolution)
679 # if any score during the block's duration would be 0, reject it
680 if any(score_array[i][start_idx:start_idx+duration_idx] == 0):
681 i +=1
682 # if all of the scores are >0, accept and schedule it
683 else:
684 if len(self.schedule.slots) >1:
685 self.schedule.insert_slot(current_time, transition)
686 self.schedule.insert_slot(test_time, block)
687 # advance the time, break this while loop and remove the block from the list
688 current_time = test_time + block.duration
689 scheduled = True
690 blocks.remove(block)
691 # if every block failed, progress the time
692 if i == len(blocks):
693 current_time += self.gap_time
694 return schedule
695 from astroplan.constraints import AtNightConstraint
696 from astroplan.scheduling import Schedule, ObservingBlock
697 from astroplan import FixedTarget, Observer, Transitioner
698 from astropy.time import Time
699
700 apo = Observer.at_site('apo')
701 deneb = FixedTarget.from_name('Deneb')
702 m13 = FixedTarget.from_name('M13')
703 blocks = [ObservingBlock(deneb, 20*u.minute, 0)]
704 blocks.append(ObservingBlock(m13, 20*u.minute, 0))
705
706 transitioner = Transitioner(2*u.deg/u.second)
707 global_constraints = [AtNightConstraint.twilight_civil()]
708
709 schedule = Schedule(Time('2016-07-06 19:00'), Time('2016-07-07 19:00'))
710 scheduler = SimpleScheduler(observer = apo, transitioner = transitioner,
711 constraints = [])
712 scheduler(blocks, schedule)
713
714 import matplotlib.pyplot as plt
715 from astroplan.plots import plot_schedule_airmass
716 plot_schedule_airmass(schedule)
717 plt.tight_layout()
718 plt.legend()
719 plt.show()
720
721 We gave the scheduler no constraints, global or local, so it added the default
722 ``AltitudeConstraint`` which is only satisfied when the targets are above the
723 horizon. Therefore the ObservingBlocks are scheduled at the first available time
724 after the target rises, which occurs at much higher airmass than the plot shows.
725
726 .. _scheduling-using_the_scorer:
727
728 Using the Scorer
729 ================
730
731 The Scheduler defined above uses `~astroplan.scheduling.Scorer.create_score_array`,
732 which creates an array with dimensions (# of blocks, schedule duration/``time_resolution``).
733 The Score of any element (block, time) in that array is made by
734 multiplying the scores returned by all of the constraints for that
735 target and time.
736
737 If you wish to use a different method of score evaluation, you can
738 add a new method to the ``Scorer``. The general framework of the
739 ``create_score_array`` method will ensure evaluation of all of the
740 constraints, but change how it combines the scores from the separate
741 constraints (e.g. add the reciprocals of the scores together and then
742 use smaller values as better). If you create a method that might be
743 generically useful to other users, `consider submitting it
744 <http://github.com/astropy/astroplan/pulls>`_ so that others will
745 be able to use it as well.