This file is indexed.

/usr/lib/python3/dist-packages/astroplan/scheduling.py is in python3-astroplan 0.4-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tools for scheduling observations.
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import copy
from abc import ABCMeta, abstractmethod

import numpy as np

from astropy import units as u
from astropy.time import Time
from astropy.table import Table

from .utils import time_grid_from_range, stride_array
from .constraints import AltitudeConstraint, AirmassConstraint
from .target import get_skycoord

__all__ = ['ObservingBlock', 'TransitionBlock', 'Schedule', 'Slot', 'Scheduler',
           'SequentialScheduler', 'PriorityScheduler', 'Transitioner', 'Scorer']


class ObservingBlock(object):
    """
    An observation to be scheduled, consisting of a target and associated
    constraints on observations.
    """
    @u.quantity_input(duration=u.second)
    def __init__(self, target, duration, priority, configuration={}, constraints=None):
        """
        Parameters
        ----------
        target : `~astroplan.FixedTarget`
            Target to observe

        duration : `~astropy.units.Quantity`
            exposure time

        priority : integer or float
            priority of this object in the target list. 1 is highest priority,
            no maximum

        configuration : dict
            Configuration metadata

        constraints : list of `~astroplan.constraints.Constraint` objects
            The constraints to apply to this particular observing block.  Note
            that constraints applicable to the entire list should go into the
            scheduler.

        """
        self.target = target
        self.duration = duration
        self.priority = priority
        self.configuration = configuration
        self.constraints = constraints
        self.start_time = self.end_time = None
        self.observer = None

    def __repr__(self):
        orig_repr = object.__repr__(self)
        if self.start_time is None or self.end_time is None:
            return orig_repr.replace('object at',
                                     '({0}, unscheduled) at'
                                     .format(self.target.name))
        else:
            s = '({0}, {1} to {2}) at'.format(self.target.name, self.start_time,
                                              self.end_time)
            return orig_repr.replace('object at', s)

    @property
    def constraints_scores(self):
        if not (self.start_time and self.duration):
            return None
        # TODO: setup a way of caching or defining it as an attribute during scheduling
        elif self.observer:
            return {constraint: constraint(self.observer, self.target,
                                           times=[self.start_time, self.start_time + self.duration])
                    for constraint in self.constraints}

    @classmethod
    def from_exposures(cls, target, priority, time_per_exposure,
                       number_exposures, readout_time=0 * u.second,
                       configuration={}, constraints=None):
        duration = number_exposures * (time_per_exposure + readout_time)
        ob = cls(target, duration, priority, configuration, constraints)
        ob.time_per_exposure = time_per_exposure
        ob.number_exposures = number_exposures
        ob.readout_time = readout_time
        return ob


class Scorer(object):
    """
    Returns scores and score arrays from the evaluation of constraints on
    observing blocks
    """

    def __init__(self, blocks, observer, schedule, global_constraints=[]):
        """
        Parameters
        ----------
        blocks : list of `~astroplan.scheduling.ObservingBlock` objects
            list of blocks that need to be scored
        observer : `~astroplan.Observer`
            the observer
        schedule : `~astroplan.scheduling.Schedule`
            The schedule inside which the blocks should fit
        global_constraints : list of `~astroplan.Constraint` objects
            any ``Constraint`` that applies to all the blocks
        """
        self.blocks = blocks
        self.observer = observer
        self.schedule = schedule
        self.global_constraints = global_constraints
        self.targets = get_skycoord([block.target for block in self.blocks])

    def create_score_array(self, time_resolution=1*u.minute):
        """
        this makes a score array over the entire schedule for all of the
        blocks and each `~astroplan.Constraint` in the .constraints of
        each block and in self.global_constraints.

        Parameters
        ----------
        time_resolution : `~astropy.units.Quantity`
            the time between each scored time

        Returns
        -------
        score_array : `~numpy.ndarray`
            array with dimensions (# of blocks, schedule length/ ``time_resolution``
        """
        start = self.schedule.start_time
        end = self.schedule.end_time
        times = time_grid_from_range((start, end), time_resolution)
        score_array = np.ones((len(self.blocks), len(times)))
        for i, block in enumerate(self.blocks):
            # TODO: change the default constraints from None to []
            if block.constraints:
                for constraint in block.constraints:
                    applied_score = constraint(self.observer, block.target,
                                               times=times)
                    score_array[i] *= applied_score
        for constraint in self.global_constraints:
            score_array *= constraint(self.observer, self.targets, times,
                                      grid_times_targets=True)
        return score_array

    @classmethod
    def from_start_end(cls, blocks, observer, start_time, end_time,
                       global_constraints=[]):
        """
        for if you don't have a schedule/ aren't inside a scheduler
        """
        dummy_schedule = Schedule(start_time, end_time)
        sc = cls(blocks, observer, dummy_schedule, global_constraints)
        return sc


class TransitionBlock(object):
    """
    Parameterizes the "dead time", e.g. between observations, while the
    telescope is slewing, instrument is reconfiguring, etc.
    """

    def __init__(self, components, start_time=None):
        """
        Parameters
        ----------
        components : dict
            A dictionary mapping the reason for an observation's dead time to
            `~astropy.units.Quantity` objects with time units

        start_time : `~astropy.units.Quantity`
            Start time of observation
        """
        self._components = None
        self.duration = None
        self.start_time = start_time
        self.components = components

    def __repr__(self):
        orig_repr = object.__repr__(self)
        comp_info = ', '.join(['{0}: {1}'.format(c, t)
                               for c, t in self.components.items()])
        if self.start_time is None or self.end_time is None:
            return orig_repr.replace('object at', ' ({0}, unscheduled) at'.format(comp_info))
        else:
            s = '({0}, {1} to {2}) at'.format(comp_info, self.start_time, self.end_time)
            return orig_repr.replace('object at', s)

    @property
    def end_time(self):
        return self.start_time + self.duration

    @property
    def components(self):
        return self._components

    @components.setter
    def components(self, val):
        duration = 0*u.second
        for t in val.values():
            duration += t

        self._components = val
        self.duration = duration

    @classmethod
    @u.quantity_input(duration=u.second)
    def from_duration(cls, duration):
        # for testing how to put transitions between observations during
        # scheduling without considering the complexities of duration
        tb = TransitionBlock({'duration': duration})
        return tb


class Schedule(object):
    """
    An object that represents a schedule, consisting of a list of
    `~astroplan.scheduling.Slot` objects.
    """
    # as currently written, there should be no consecutive unoccupied slots
    # this should change to allow for more flexibility (e.g. dark slots, grey slots)

    def __init__(self, start_time, end_time, constraints=None):
        """
        Parameters
        -----------
        start_time : `~astropy.time.Time`
            The starting time of the schedule; the start of your
            observing window.
        end_time : `~astropy.time.Time`
           The ending time of the schedule; the end of your
           observing window
        constraints : sequence of `~astroplan.constraints.Constraint` s
           these are constraints that apply to the entire schedule
        """
        self.start_time = start_time
        self.end_time = end_time
        self.slots = [Slot(start_time, end_time)]
        self.observer = None

    def __repr__(self):
        return ('Schedule containing ' + str(len(self.observing_blocks)) +
                ' observing blocks between ' + str(self.slots[0].start.iso) +
                ' and ' + str(self.slots[-1].end.iso))

    @property
    def observing_blocks(self):
        return [slot.block for slot in self.slots if isinstance(slot.block, ObservingBlock)]

    @property
    def scheduled_blocks(self):
        return [slot.block for slot in self.slots if slot.block]

    @property
    def open_slots(self):
        return [slot for slot in self.slots if not slot.occupied]

    def to_table(self, show_transitions=True, show_unused=False):
        # TODO: allow different coordinate types
        target_names = []
        start_times = []
        end_times = []
        durations = []
        ra = []
        dec = []
        config = []
        for slot in self.slots:
            if hasattr(slot.block, 'target'):
                start_times.append(slot.start.iso)
                end_times.append(slot.end.iso)
                durations.append(slot.duration.to(u.minute).value)
                target_names.append(slot.block.target.name)
                ra.append(slot.block.target.ra)
                dec.append(slot.block.target.dec)
                config.append(slot.block.configuration)
            elif show_transitions and slot.block:
                start_times.append(slot.start.iso)
                end_times.append(slot.end.iso)
                durations.append(slot.duration.to(u.minute).value)
                target_names.append('TransitionBlock')
                ra.append('')
                dec.append('')
                changes = list(slot.block.components.keys())
                if 'slew_time' in changes:
                    changes.remove('slew_time')
                config.append(changes)
            elif slot.block is None and show_unused:
                start_times.append(slot.start.iso)
                end_times.append(slot.end.iso)
                durations.append(slot.duration.to(u.minute).value)
                target_names.append('Unused Time')
                ra.append('')
                dec.append('')
                config.append('')
        return Table([target_names, start_times, end_times, durations, ra, dec, config],
                     names=('target', 'start time (UTC)', 'end time (UTC)',
                            'duration (minutes)', 'ra', 'dec', 'configuration'))

    def new_slots(self, slot_index, start_time, end_time):
        """
        Create new slots by splitting a current slot.

        Parameters
        ----------
        slot_index : int
            The index of the slot to split

        start_time : `~astropy.time.Time`
            The start time for the slot to create

        end_time : `~astropy.time.Time`
            The end time for the slot to create

        Returns
        -------
        new_slots : list of `~astroplan.scheduling.Slot` s
            The new slots created
        """
        # this is intended to be used such that there aren't consecutive unoccupied slots
        new_slots = self.slots[slot_index].split_slot(start_time, end_time)
        return new_slots

    def insert_slot(self, start_time, block):
        """
        Insert a slot into schedule and associate a block to the new slot.

        Parameters
        ----------
        start_time : `~astropy.time.Time`
            The start time for the new slot.
        block : `~astroplan.scheduling.ObservingBlock`
            The observing block to insert into new slot.

        Returns
        -------
        slots : list of `~astroplan.scheduling.Slot` objects
            The new slots in the schedule.
        """
        # due to float representation, this will change block start time
        # and duration by up to 1 second in order to fit in a slot
        for j, slot in enumerate(self.slots):
            if ((slot.start < start_time or abs(slot.start-start_time) < 1*u.second)
                    and (slot.end > start_time + 1*u.second)):
                slot_index = j
        if (block.duration - self.slots[slot_index].duration) > 1*u.second:
            raise ValueError('longer block than slot')
        elif self.slots[slot_index].end - block.duration < start_time:
            start_time = self.slots[slot_index].end - block.duration

        if abs((self.slots[slot_index].duration - block.duration)) < 1 * u.second:
            # slot duration is very similar to block duration.
            # force equality so block fits
            block.duration = self.slots[slot_index].duration
            start_time = self.slots[slot_index].start
            end_time = self.slots[slot_index].end
        elif abs(self.slots[slot_index].start - start_time) < 1*u.second:
            # start time of block is very close to slot start time
            # force equality to avoid tiny gaps
            start_time = self.slots[slot_index].start
            end_time = start_time + block.duration
        elif abs(self.slots[slot_index].end - start_time - block.duration) < 1*u.second:
            # end time is very close to slot end time
            # force equality to avoid tiny gaps
            end_time = self.slots[slot_index].end
        else:
            end_time = start_time + block.duration

        if isinstance(block, ObservingBlock):
            # TODO: make it shift observing/transition blocks to fill small amounts of open space
            block.end_time = start_time+block.duration
        earlier_slots = self.slots[:slot_index]
        later_slots = self.slots[slot_index+1:]
        block.start_time = start_time
        new_slots = self.new_slots(slot_index, start_time, end_time)
        for new_slot in new_slots:
            if new_slot.middle:
                new_slot.occupied = True
                new_slot.block = block
        self.slots = earlier_slots + new_slots + later_slots
        return earlier_slots + new_slots + later_slots

    def change_slot_block(self, slot_index, new_block=None):
        """
        Change the block associated with a slot.

        This is currently designed to work for TransitionBlocks in PriorityScheduler
        The assumption is that the slot afterwards is open and that the start time
        will remain the same.

        If the block is changed to None, the slot is merged with the slot
        afterwards to make a longer slot.

        Parameters
        ----------
        slot_index : int
            The slot to edit
        new_block : `~astroplan.scheduling.TransitionBlock`, default None
            The new transition block to insert in this slot
        """
        if self.slots[slot_index + 1].block:
            raise IndexError('slot afterwards is full')
        if new_block is not None:
            new_end = self.slots[slot_index].start + new_block.duration
            self.slots[slot_index].end = new_end
            self.slots[slot_index].block = new_block
            self.slots[slot_index + 1].start = new_end
            return slot_index
        else:
            self.slots[slot_index + 1].start = self.slots[slot_index].start
            del self.slots[slot_index]
            return slot_index - 1


class Slot(object):
    """
    A time slot consisting of a start and end time
    """

    def __init__(self, start_time, end_time):
        """
        Parameters
        -----------
        start_time : `~astropy.time.Time`
            The starting time of the slot
        end_time : `~astropy.time.Time`
            The ending time of the slot
        """
        self.start = start_time
        self.end = end_time
        self.occupied = False
        self.middle = False
        self.block = None

    @property
    def duration(self):
        return self.end - self.start

    def split_slot(self, early_time, later_time):
        """
        Split this slot and insert a new one.

        Will return the new slots created, which can either
        be one, two or three slots depending on if there is
        space remaining before or after the inserted slot.

        Parameters
        ----------
        early_time : `~astropy.time.Time`
            The start time of the new slot to insert.
        later_time : `~astropy.time.Time`
            The end time of the new slot to insert.
        """
        # check if the new slot would overwrite occupied/other slots
        if self.occupied:
            raise ValueError('slot is already occupied')

        new_slot = Slot(early_time, later_time)
        new_slot.middle = True
        early_slot = Slot(self.start, early_time)
        late_slot = Slot(later_time, self.end)

        if early_time > self.start and later_time < self.end:
            return [early_slot, new_slot, late_slot]
        elif early_time > self.start:
            return [early_slot, new_slot]
        elif later_time < self.end:
            return [new_slot, late_slot]
        else:
            return [new_slot]


class Scheduler(object):
    """
    Schedule a set of `~astroplan.scheduling.ObservingBlock` objects
    """

    __metaclass__ = ABCMeta

    @u.quantity_input(gap_time=u.second, time_resolution=u.second)
    def __init__(self, constraints, observer, transitioner=None,
                 gap_time=5*u.min, time_resolution=20*u.second):
        """
        Parameters
        ----------
        constraints : sequence of `~astroplan.constraints.Constraint`
            The constraints to apply to *every* observing block.  Note that
            constraints for specific blocks can go on each block individually.
        observer : `~astroplan.Observer`
            The observer/site to do the scheduling for.
        transitioner : `~astroplan.scheduling.Transitioner` (required)
            The object to use for computing transition times between blocks.
            Leaving it as ``None`` will cause an error.
        gap_time : `~astropy.units.Quantity` with time units
            The maximum length of time a transition between ObservingBlocks
            could take.
        time_resolution : `~astropy.units.Quantity` with time units
            The smallest factor of time used in scheduling, all Blocks scheduled
            will have a duration that is a multiple of it.
        """
        self.constraints = constraints
        self.observer = observer
        self.transitioner = transitioner
        if not isinstance(self.transitioner, Transitioner):
            raise ValueError("A Transitioner is required")
        self.gap_time = gap_time
        self.time_resolution = time_resolution

    def __call__(self, blocks, schedule):
        """
        Schedule a set of `~astroplan.scheduling.ObservingBlock` objects.

        Parameters
        ----------
        blocks : list of `~astroplan.scheduling.ObservingBlock` objects
            The observing blocks to schedule.  Note that the input
            `~astroplan.scheduling.ObservingBlock` objects will *not* be
            modified - new ones will be created and returned.
        schedule : `~astroplan.scheduling.Schedule` object
            A schedule that the blocks will be scheduled in. At this time
            the ``schedule`` must be empty, only defined by a start and
            end time.

        Returns
        -------
        schedule : `~astroplan.scheduling.Schedule`
            A schedule objects which consists of `~astroplan.scheduling.Slot`
            objects with and without populated ``block`` objects containing either
            `~astroplan.scheduling.TransitionBlock` or `~astroplan.scheduling.ObservingBlock`
            objects with populated ``start_time`` and ``end_time`` or ``duration`` attributes
        """
        self.schedule = schedule
        self.schedule.observer = self.observer
        # these are *shallow* copies
        copied_blocks = [copy.copy(block) for block in blocks]
        schedule = self._make_schedule(copied_blocks)
        return schedule

    @abstractmethod
    def _make_schedule(self, blocks):
        """
        Does the actual business of scheduling. The ``blocks`` passed in should
        have their ``start_time` and `end_time`` modified to reflect the
        schedule. Any necessary `~astroplan.scheduling.TransitionBlock` should
        also be added.  Then the full set of blocks should be returned as a list
        of blocks, along with a boolean indicating whether or not they have been
        put in order already.

        Parameters
        ----------
        blocks : list of `~astroplan.scheduling.ObservingBlock` objects
            Can be modified as it is already copied by ``__call__``

        Returns
        -------
        schedule : `~astroplan.scheduling.Schedule`
            A schedule objects which consists of `~astroplan.scheduling.Slot`
            objects with and without populated ``block`` objects containing either
            `~astroplan.scheduling.TransitionBlock` or `~astroplan.scheduling.ObservingBlock`
            objects with populated ``start_time`` and ``end_time`` or ``duration`` attributes.
        """
        raise NotImplementedError
        return schedule

    @classmethod
    @u.quantity_input(duration=u.second)
    def from_timespan(cls, center_time, duration, **kwargs):
        """
        Create a new instance of this class given a center time and duration.

        Parameters
        ----------
        center_time : `~astropy.time.Time`
            Mid-point of time-span to schedule.

        duration : `~astropy.units.Quantity` or `~astropy.time.TimeDelta`
            Duration of time-span to schedule
        """
        start_time = center_time - duration / 2.
        end_time = center_time + duration / 2.
        return cls(start_time, end_time, **kwargs)


class SequentialScheduler(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.
    """

    def __init__(self, *args, **kwargs):
        super(SequentialScheduler, self).__init__(*args, **kwargs)

    def _make_schedule(self, blocks):
        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))
            b._duration_offsets = u.Quantity([0*u.second, b.duration/2,
                                              b.duration])
            b.observer = self.observer
        current_time = self.schedule.start_time
        while (len(blocks) > 0) and (current_time < self.schedule.end_time):
            # first compute the value of all the constraints for each block
            # given the current starting time
            block_transitions = []
            block_constraint_results = []
            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 = []
                    for constraint in b._all_constraints:
                        constraint_res.append(constraint(
                            self.observer, b.target, times))
                    # take the product over all the constraints *and* times
                    block_constraint_results.append(np.prod(constraint_res))

            # now identify the block that's the best
            bestblock_idx = np.argmax(block_constraint_results)

            if block_constraint_results[bestblock_idx] == 0.:
                # if even the best is unobservable, we need a gap
                current_time += self.gap_time
            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)
                    current_time += trans.duration

                # now assign the block itself times and add it to the schedule
                newb = blocks.pop(bestblock_idx)
                newb.start_time = current_time
                current_time += newb.duration
                newb.end_time = current_time
                newb.constraints_value = block_constraint_results[bestblock_idx]

                self.schedule.insert_slot(newb.start_time, newb)

        return self.schedule


class PriorityScheduler(Scheduler):
    """
    A scheduler that optimizes a prioritized list.  That is, it
    finds the best time for each ObservingBlock, in order of priority.
    """

    def __init__(self, *args, **kwargs):
        """

        """
        super(PriorityScheduler, self).__init__(*args, **kwargs)

    def _get_filled_indices(self, times):
        is_open_time = np.ones(len(times), bool)
        # close times that are already filled
        pre_filled = np.array([[block.start_time, block.end_time] for
                               block in self.schedule.scheduled_blocks if
                               isinstance(block, ObservingBlock)])
        for start_end in pre_filled:
            filled = np.where((start_end[0] < times) & (times < start_end[1]))
            if len(filled[0]) > 0:
                is_open_time[filled[0]] = False
                is_open_time[min(filled[0]) - 1] = False
        return is_open_time

    def _make_schedule(self, blocks):
        # Combine individual constraints with global constraints, and
        # retrieve priorities from each block to define scheduling order

        _all_times = []
        _block_priorities = np.zeros(len(blocks))

        # make sure we don't schedule below the horizon
        if self.constraints is None:
            self.constraints = [AltitudeConstraint(min=0 * u.deg)]
        else:
            self.constraints.append(AltitudeConstraint(min=0 * u.deg))

        for i, b in enumerate(blocks):
            b._duration_offsets = u.Quantity([0 * u.second, b.duration / 2, b.duration])
            _block_priorities[i] = b.priority
            _all_times.append(b.duration)
            b.observer = self.observer

        # Define a master schedule
        # Generate grid of time slots, and a mask for previous observations

        time_resolution = self.time_resolution
        times = time_grid_from_range([self.schedule.start_time, self.schedule.end_time],
                                     time_resolution=time_resolution)

        # generate the score arrays for all of the blocks
        scorer = Scorer(blocks, self.observer, self.schedule,
                        global_constraints=self.constraints)
        score_array = scorer.create_score_array(time_resolution)

        # Sort the list of blocks by priority
        sorted_indices = np.argsort(_block_priorities)

        unscheduled_blocks = []
        # Compute the optimal observation time in priority order
        for i in sorted_indices:
            b = blocks[i]
            # Compute possible observing times by combining object constraints
            # with the master open times mask
            constraint_scores = score_array[i]

            # Add up the applied constraints to prioritize the best blocks
            # And then remove any times that are already scheduled
            is_open_time = self._get_filled_indices(times)
            constraint_scores[~is_open_time] = 0

            # Select the most optimal time

            # calculate the number of time slots needed for this exposure
            _stride_by = np.int(np.ceil(float(b.duration / time_resolution)))

            # Stride the score arrays by that number
            _strided_scores = stride_array(constraint_scores, _stride_by)

            # Collapse the sub-arrays
            # (run them through scorekeeper again? Just add them?
            # If there's a zero anywhere in there, def. have to skip)
            good = np.all(_strided_scores > 1e-5, axis=1)
            sum_scores = np.zeros(len(_strided_scores))
            sum_scores[good] = np.sum(_strided_scores[good], axis=1)

            if np.all(constraint_scores == 0) or np.all(~good):
                # No further calculation if no times meet the constraints
                _is_scheduled = False
            else:
                # schedulable in principle, provided the transition
                # does not prevent us from fitting it in.
                # loop over valid times and see if it fits
                # TODO: speed up by searching multiples of time resolution?
                for idx in np.argsort(sum_scores)[::-1]:
                    if sum_scores[idx] <= 0.0:
                        # we've run through all optimal blocks
                        _is_scheduled = False
                        break
                    try:
                        start_time_idx = idx
                        new_start_time = times[start_time_idx]
                        # attempt to schedule block
                        _is_scheduled = self.attempt_insert_block(b, new_start_time, start_time_idx)
                        if _is_scheduled:
                            break
                    except IndexError:
                        # idx can extend past end of _strided_open_time
                        _is_scheduled = False
                        break

            if not _is_scheduled:
                unscheduled_blocks.append(b)

        return self.schedule

    def attempt_insert_block(self, b, new_start_time, start_time_idx):
        # set duration to be exact multiple of time resolution
        duration_indices = np.int(np.ceil(
            float(b.duration / self.time_resolution)))
        b.duration = duration_indices * self.time_resolution

        # add 1 second to the start time to allow for scheduling at the start of a slot
        slot_index = [q for q, slot in enumerate(self.schedule.slots)
                      if slot.start < new_start_time + 1*u.second < slot.end][0]
        slots_before = self.schedule.slots[:slot_index]
        slots_after = self.schedule.slots[slot_index + 1:]

        # now check if there's a transition block where we want to go
        # if so, we delete it. A new one will be added if needed
        delete_this_block_first = False
        if self.schedule.slots[slot_index].block:
            if isinstance(self.schedule.slots[slot_index].block, ObservingBlock):
                raise ValueError('block already occupied')
            else:
                delete_this_block_first = True

        # no slots yet, so we should be fine to just shove this in
        if not (slots_before or slots_after):
            b.end_idx = start_time_idx + duration_indices
            b.start_idx = start_time_idx
            if b.constraints is None:
                b.constraints = self.constraints
            elif self.constraints is not None:
                b.constraints = b.constraints + self.constraints
            try:
                self.schedule.insert_slot(new_start_time, b)
                return True
            except ValueError as error:
                # this shouldn't ever happen
                print('Failed to insert {} into schedule.\n{}'.format(
                        b.target.name, str(error)
                      ))
                return False

        # Other slots exist, so now we have to see if it will fit
        # if slots before or after, we need `TransitionBlock`s
        tb_before = None
        tb_before_already_exists = False
        tb_after = None
        if slots_before:
            if isinstance(
                    self.schedule.slots[slot_index - 1].block, ObservingBlock):
                # make a transitionblock
                tb_before = self.transitioner(
                    self.schedule.slots[slot_index - 1].block, b,
                    self.schedule.slots[slot_index - 1].end, self.observer)
            elif isinstance(self.schedule.slots[slot_index - 1].block, TransitionBlock):
                tb_before = self.transitioner(
                    self.schedule.slots[slot_index - 2].block, b,
                    self.schedule.slots[slot_index - 2].end, self.observer)
                tb_before_already_exists = True

        if slots_after:
            slot_offset = 2 if delete_this_block_first else 1
            if isinstance(
                    self.schedule.slots[slot_index + slot_offset].block, ObservingBlock):
                # make a transition object after the new ObservingBlock
                tb_after = self.transitioner(
                    b, self.schedule.slots[slot_index + slot_offset].block,
                    new_start_time + b.duration, self.observer)

        # tweak durations to exact multiple of time resolution
        for block in (tb_before, tb_after):
            if block is not None:
                block.duration = self.time_resolution * np.int(
                    np.ceil(float(block.duration / self.time_resolution))
                )

        # if we want to shift the OBs to minimise gaps, here is
        # where we should do it.
        # Find the smallest shift (forward or backward) to close gap
        # Check against tolerances (constraints must still be met)
        # Shift if OK and update new_start_time and start_time_idx

        # Now let's see if the block and transition can fit in the schedule
        if slots_before:
            # we're OK if the index at the end of the updated transition
            # is less than or equal to `start_time_idx`
            ob_offset = 2 if tb_before_already_exists else 1
            previous_ob = self.schedule.slots[slot_index - ob_offset]
            if tb_before:
                transition_indices = np.int(tb_before.duration / self.time_resolution)
            else:
                transition_indices = 0

            if start_time_idx < previous_ob.block.end_idx + transition_indices:
                # cannot schedule
                return False

        if slots_after:
            # we're OK if the index at end of OB (plus transition)
            # is smaller than the start_index of the slot after
            slot_offset = 2 if delete_this_block_first else 1
            next_ob = self.schedule.slots[slot_index + slot_offset].block
            end_idx = start_time_idx + duration_indices
            if tb_after:
                end_idx += np.int(tb_after.duration/self.time_resolution)
                if end_idx >= next_ob.start_idx:
                    # cannot schedule
                    return False

        # OK, we should be OK to schedule now!
        try:
            # delete this block if it's a TransitionBlock
            if delete_this_block_first:
                slot_index = self.schedule.change_slot_block(slot_index, new_block=None)
            if tb_before and tb_before_already_exists:
                self.schedule.change_slot_block(slot_index - 1, new_block=tb_before)
            elif tb_before:
                self.schedule.insert_slot(tb_before.start_time, tb_before)
            elif tb_before_already_exists and not tb_before:
                # we already have a TB here, but we no longer need it!
                self.schedule.change_slot_block(slot_index-1, new_block=None)

            b.end_idx = start_time_idx + duration_indices
            b.start_idx = start_time_idx
            if b.constraints is None:
                b.constraints = self.constraints
            elif self.constraints is not None:
                b.constraints = b.constraints + self.constraints
            self.schedule.insert_slot(new_start_time, b)

            if tb_after:
                self.schedule.insert_slot(tb_after.start_time, tb_after)

        except ValueError as error:
            # this shouldn't ever happen
            print('Failed to insert {} (dur: {}) into schedule.\n{}\n{}'.format(
                   b.target.name, b.duration, new_start_time.iso, str(error)
                  ))
            return False

        return True


class Transitioner(object):
    """
    A class that defines how to compute transition times from one block to
    another.
    """
    u.quantity_input(slew_rate=u.deg/u.second)

    def __init__(self, slew_rate=None, instrument_reconfig_times=None):
        """
        Parameters
        ----------
        slew_rate : `~astropy.units.Quantity` with angle/time units
            The slew rate of the telescope
        instrument_reconfig_times : dict of dicts or None
            If not None, gives a mapping from property names to another
            dictionary. The second dictionary maps 2-tuples of states to the
            time it takes to transition between those states (as an
            `~astropy.units.Quantity`), can also take a 'default' key
            mapped to a default transition time.
        """
        self.slew_rate = slew_rate
        self.instrument_reconfig_times = instrument_reconfig_times

    def __call__(self, oldblock, newblock, start_time, observer):
        """
        Determines the amount of time needed to transition from one observing
        block to another.  This uses the parameters defined in
        ``self.instrument_reconfig_times``.

        Parameters
        ----------
        oldblock : `~astroplan.scheduling.ObservingBlock` or None
            The initial configuration/target
        newblock : `~astroplan.scheduling.ObservingBlock` or None
            The new configuration/target to transition to
        start_time : `~astropy.time.Time`
            The time the transition should start
        observer : `astroplan.Observer`
            The observer at the time

        Returns
        -------
        transition : `~astroplan.scheduling.TransitionBlock` or None
            A transition to get from ``oldblock`` to ``newblock`` or `None` if
            no transition is necessary
        """
        components = {}
        if (self.slew_rate is not None and (oldblock is not None) and (newblock is not None)):
            # use the constraints cache for now, but should move that machinery
            # to observer
            from .constraints import _get_altaz
            from .target import get_skycoord
            if oldblock.target != newblock.target:
                from .target import get_skycoord
                targets = get_skycoord([oldblock.target, newblock.target])
                aaz = _get_altaz(start_time, observer, targets)['altaz']
                sep = aaz[0].separation(aaz[1])
                if sep/self.slew_rate > 1 * u.second:
                    components['slew_time'] = sep / self.slew_rate

        if self.instrument_reconfig_times is not None:
            components.update(self.compute_instrument_transitions(oldblock, newblock))

        if components:
            return TransitionBlock(components, start_time)
        else:
            return None

    def compute_instrument_transitions(self, oldblock, newblock):
        components = {}
        for conf_name, old_conf in oldblock.configuration.items():
            if conf_name in newblock.configuration:
                conf_times = self.instrument_reconfig_times.get(conf_name,
                                                                None)
                if conf_times is not None:
                    new_conf = newblock.configuration[conf_name]
                    ctime = conf_times.get((old_conf, new_conf), None)
                    def_time = conf_times.get('default', None)
                    if ctime is not None:
                        s = '{0}:{1} to {2}'.format(conf_name, old_conf,
                                                    new_conf)
                        components[s] = ctime
                    elif def_time is not None and not old_conf == new_conf:
                        s = '{0}:{1} to {2}'.format(conf_name, old_conf,
                                                    new_conf)
                        components[s] = def_time

        return components