Blame view

src/core/pyros_django/scheduling/A_Scheduler.py 32.7 KB
6cd48351   Etienne Pallier   AgentScheduler is...
1
#!/usr/bin/env python3
df477bca   Alain Klotz   New scheduler
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# To launch this agent from the root of Pyros:
#
# Linux console:
# cd /srv/develop/pyros/docker
# ./PYROS_DOCKER_START.sh
#
# Launch from Power Shell:
# To go from docker to Powershell: pyros_user@ORION:~/app$ exit (or Ctrl+d)
# Prompt is now PS ...>
# cd \srv\develop\pyros
# .\PYROS -t new-start -o tnc -fg -a A_Scheduler
#
# Launch from docker:
# To go from Powershell to docker: PS ...> .\PYROS_DOCKER_SHELL
# Prompt is now pyros_user@ORION:~/app$
# ./PYROS -t new-start -o tnc -fg -a A_Scheduler
6bc582b5   Alain Klotz   Big debug at Guit...
19
20
#
# To use debug
df477bca   Alain Klotz   New scheduler
21
22
# ./PYROS -d -t new-start -o tnc -fg -a A_Scheduler
#
3825738b   Alain Klotz   Debug Scheduler.
23
# ./PYROS -d -t start -o tnc -fg A_Scheduler
df477bca   Alain Klotz   New scheduler
24
# ---------------------------------------------------
6cd48351   Etienne Pallier   AgentScheduler is...
25
26

import sys
6cd48351   Etienne Pallier   AgentScheduler is...
27
import time
df477bca   Alain Klotz   New scheduler
28
29
30
31
import argparse
import os
import pickle
import socket
82400cb8   Etienne Pallier   simplification im...
32

df477bca   Alain Klotz   New scheduler
33
34
35
pwd = os.environ['PROJECT_ROOT_PATH']
if pwd not in sys.path:
    sys.path.append(pwd)
6cd48351   Etienne Pallier   AgentScheduler is...
36

df477bca   Alain Klotz   New scheduler
37
38
short_paths = ['src', 'src/core/pyros_django']
for short_path in short_paths:
e5cec6d9   Alain Klotz   Update scheduler
39
    path = os.path.abspath(os.path.join(pwd, short_path))
df477bca   Alain Klotz   New scheduler
40
41
    if path not in sys.path:
        sys.path.insert(0, path)
6cd48351   Etienne Pallier   AgentScheduler is...
42

82400cb8   Etienne Pallier   simplification im...
43
44
#from src.core.pyros_django.majordome.agent.Agent import Agent, build_agent, log, parse_args
from majordome.agent.Agent import Agent, build_agent, log, parse_args
b95a693f   Alexis Koralewski   restructuration d...
45
from seq_submit.models import Sequence
df477bca   Alain Klotz   New scheduler
46
from user_mgmt.models import Period, ScientificProgram, SP_Period
a8cce62b   Alain Klotz   Json bdd and sche...
47
from scheduling.models import PredictiveSchedule, EffectiveSchedule
df477bca   Alain Klotz   New scheduler
48
49
50
51
52
53
54
55
# = Specials
import glob
import shutil
import guitastro
import datetime
from decimal import Decimal
import zoneinfo
import numpy as np
6cd48351   Etienne Pallier   AgentScheduler is...
56

7fd005b5   Alain Klotz   New scheduler
57
class A_Scheduler(Agent):
6cd48351   Etienne Pallier   AgentScheduler is...
58

19813230   Alain Klotz   New DATA structur...
59
    DPRINT = True
df477bca   Alain Klotz   New scheduler
60
    
6bc582b5   Alain Klotz   Big debug at Guit...
61
62
63
    # - Sampling of the night arrays (bins/night)
    BINS_NIGHT = 86400
    
df477bca   Alain Klotz   New scheduler
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    # - status of the sequence after schedule computation
    SEQ_NOT_PROCESSED = 0
    SEQ_SCHEDULED = 1
    SEQ_SCHEDULED_OVER_QUOTA = 2
    SEQ_REJECTED_NO_QUOTA_ENOUGH = -1
    SEQ_REJECTED_NO_SLOT_AVAILABLE = -2
    
    # - enum of the matrix line
    SEQ_K = 0
    SEQ_SEQ_ID = 1
    SEQ_KOBS0 = 2
    SEQ_SP_ID = 3
    SEQ_PRIORITY = 4
    SEQ_DURATION = 5
    SEQ_STATUS = 6
    NB_SEQ = 7
    
    # - All possible running states
    RUNNING_NOTHING = 0
    RUNNING_SCHEDULE_PROCESSING = 1
6cd48351   Etienne Pallier   AgentScheduler is...
84

df477bca   Alain Klotz   New scheduler
85
86
87
88
89
    _AGENT_SPECIFIC_COMMANDS = {
        # Format : “cmd_name” : (timeout, exec_mode)
        "do_compute_schedule_1" : (60, Agent.EXEC_MODE.SEQUENTIAL, ''),
        "do_create_seq_1" : (60, Agent.EXEC_MODE.SEQUENTIAL, ''),
    }
6cd48351   Etienne Pallier   AgentScheduler is...
90

19813230   Alain Klotz   New DATA structur...
91
    # Test scenario to be executed (option -t)
df477bca   Alain Klotz   New scheduler
92
93
94
95
96
    # "self do_stop_current_processing"
    # AgentCmd.CMD_STATUS_CODE.CMD_EXECUTED
    _TEST_COMMANDS_LIST = [
        # Format : ("self cmd_name cmd_args", timeout, "expected_result", expected_status),
        (True, "self do_create_seq_1 6", 200, '', Agent.CMD_STATUS.CMD_EXECUTED),
19813230   Alain Klotz   New DATA structur...
97
        (True, "self do_stop asap", 500, "STOPPING", Agent.CMD_STATUS.CMD_EXECUTED),
bd4b900a   Etienne Pallier   update replan
98
    ]
6cd48351   Etienne Pallier   AgentScheduler is...
99

6cd48351   Etienne Pallier   AgentScheduler is...
100
101
    """
    =================================================================
df477bca   Alain Klotz   New scheduler
102
        Methods running inside main thread
6cd48351   Etienne Pallier   AgentScheduler is...
103
104
    =================================================================
    """
df477bca   Alain Klotz   New scheduler
105
    def __init__(self, name:str=None,simulated_computer=None):
6cd48351   Etienne Pallier   AgentScheduler is...
106
107
        if name is None:
            name = self.__class__.__name__
df477bca   Alain Klotz   New scheduler
108
        super().__init__(simulated_computer=simulated_computer)
0bcd6dd5   Etienne Pallier   renamed Agent met...
109
    
0bcd6dd5   Etienne Pallier   renamed Agent met...
110
111
    def _init(self):
        super()._init()
df477bca   Alain Klotz   New scheduler
112
113
        log.debug("end super init()")
        log.info(f"self.TEST_MODE = {self.TEST_MODE}")
6cd48351   Etienne Pallier   AgentScheduler is...
114

df477bca   Alain Klotz   New scheduler
115
116
117
        # === Get the config object
        self.config = self._oc['config']
        self.pconfig = self._oc['pyros_config']
6bc582b5   Alain Klotz   Big debug at Guit...
118

df477bca   Alain Klotz   New scheduler
119
120
121
122
123
124
        # === Get agent_alias
        hostname = socket.gethostname()
        log.info(f"{hostname=}")
        log.info(f"{self.name=}")
        agent_alias = self.config.get_agent_real_name(self.name, hostname)
        log.info(f"{agent_alias=}")
6cd48351   Etienne Pallier   AgentScheduler is...
125

1cd8d8dd   Alain Klotz   Ephem sun and Moon.
126
        # === Get all file contexts from pyros config
d3e71677   Alexis Koralewski   Put seq & eph fn_...
127
        self._fn = self.config.fn
19813230   Alain Klotz   New DATA structur...
128
        log.info(f"=== List of file name contexts available for the unit")
1cd8d8dd   Alain Klotz   Ephem sun and Moon.
129
130
        self.check_contexts(True)
        log.info(f"{self._fn.longitude=}")
df477bca   Alain Klotz   New scheduler
131

9b6af71d   Alain Klotz   Update version Sc...
132
133
134
        # TBD duskelev a parametrer from obsconfig (yml)
        self._duskelev = -7
        
df477bca   Alain Klotz   New scheduler
135
136
137
        # === Status of routine processing
        self._routine_running = self.RUNNING_NOTHING
        log.debug("end init()")
e5cec6d9   Alain Klotz   Update scheduler
138
        ##### TBD suppress redondant paths in print(f"=>=>=> {sys.path=}")
6cd48351   Etienne Pallier   AgentScheduler is...
139
140
141

    # Note : called by _routine_process() in Agent
    # @override
547df0ef   Etienne Pallier   routine_process_b...
142
    def _routine_process_iter_start_body(self):
739c899f   Etienne Pallier   Ajout routine_pro...
143
        log.debug("in routine_process_before_body()")
739c899f   Etienne Pallier   Ajout routine_pro...
144
145
146

    # Note : called by _routine_process() in Agent
    # @override
547df0ef   Etienne Pallier   routine_process_b...
147
    def _routine_process_iter_end_body(self):
739c899f   Etienne Pallier   Ajout routine_pro...
148
        log.debug("in routine_process_after_body()")
df477bca   Alain Klotz   New scheduler
149
150
151
152
153
154
        # TODO EP est-ce utile ?
        if self._routine_running == self.RUNNING_NOTHING:
            # Get files to process
            # - Thread TODO
            self._routine_running = self.RUNNING_SCHEDULE_PROCESSING
            self.do_compute_schedule_1()
6cd48351   Etienne Pallier   AgentScheduler is...
155

df477bca   Alain Klotz   New scheduler
156
157
158
159
160
161
    """
    =================================================================
        Methods of specific commands
    =================================================================
    """

e5cec6d9   Alain Klotz   Update scheduler
162
    def do_create_seq_1(self, nb_seq:int):
df477bca   Alain Klotz   New scheduler
163
        """Create sequences to debug
16da961d   Alain Klotz   First update for ...
164
165
        :raises ExceptionType: Some multi-line
            exception description.
df477bca   Alain Klotz   New scheduler
166
        """
19813230   Alain Klotz   New DATA structur...
167
168
169
170
        try:
            self._create_seq_1(nb_seq)
        except Exception as e:
            self.dprint(f"ERROR {e}")
df477bca   Alain Klotz   New scheduler
171
172
173
174
175
176
177
178
179
180
181
182
183
184

    def do_compute_schedule_1(self):
        """Compute a schedule
        
        According the current time, select the night directory.
        List the *.p file list (.p for sequences)
        Read the *.p, *.f file contents (.f for ephemeris)
        Compute the schedule
        
        Output is a matrix to unpack in the database.
        Each line of the matrix is a sequence
        Columns are defined by the enum SEQ_* (see the python code itself).
        
        """
19813230   Alain Klotz   New DATA structur...
185
186
187
188
        try:
            self._compute_schedule_1()
        except Exception as e:
            self.dprint(f"ERROR {e}")
df477bca   Alain Klotz   New scheduler
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

    """
    =================================================================
        Methods called by commands or routine. Overload these methods
    =================================================================
    # ---
    # osp = ScientificProgram.objects.get(id=scientific_program_id)
    # --- ospperiod is the SP object
    # ospperiod = SP_Period.objects.get(period = period_id, scientific_program = osp)
    # print(f"dir(ospperiod)={dir(ospperiod)}")
    # dir(spperiod)=['DoesNotExist', 
    # 'IS_VALID', 'IS_VALID_ACCEPTED', 'IS_VALID_REJECTED', 
    # 'MultipleObjectsReturned', 'SP_Period_Guests', 'SP_Period_Users', 
    # 'STATUSES', 'STATUSES_ACCEPTED', 'STATUSES_DRAFT', 
    # 'STATUSES_EVALUATED', 'STATUSES_REJECTED', 'STATUSES_SUBMITTED', 
    # 'VISIBILITY_CHOICES', 'VISIBILITY_NO', 'VISIBILITY_YES', 
    # 'VOTES', 'VOTES_NO', 'VOTES_TO_DISCUSS', 'VOTES_YES', 
    # 'can_submit_sequence', 'check', 'clean', 'clean_fields', 
    # 'date_error_message', 'delete', 'from_db', 'full_clean', 
    # 'get_constraints', 'get_deferred_fields', 'get_is_valid_display', 
    # 'get_public_visibility_display', 'get_status_display', 
    # 'get_vote_referee1_display', 'get_vote_referee2_display', 
    # 'id', 'is_currently_active', 'is_valid', 'objects', 
    # 'over_quota_duration', 'over_quota_duration_allocated', 
    # 'over_quota_duration_remaining', 'period', 'period_id', 
    # 'pk', 'prepare_database_save', 'priority', 'public_visibility', 
    # 'quota_allocated', 'quota_minimal', 'quota_nominal', 
    # 'quota_remaining', 'reason_referee1', 'reason_referee2', 
    # 'referee1', 'referee1_id', 'referee2', 'referee2_id', 
    # 'refresh_from_db', 'save', 'save_base', 'scientific_program', 
    # 'scientific_program_id', 'serializable_value', 'status', 'token', 
    # 'token_allocated', 'token_remaining', 'unique_error_message', 
    # 'validate_constraints', 'validate_unique', 'vote_referee1', 
    # 'vote_referee2'
    """
    
2d4bb4d6   Alexis Koralewski   add quota managem...
225
226
227
228
229
230

    def update_db_quota_sequence(sequence, quota_attributes, id_period, night_id, d_total=sequence_info['duration']):
        sequence_quota = sequence.quota
        sp_quota = sequence.scientific_program
        institute_quota = 

df477bca   Alain Klotz   New scheduler
231
232
233
234
235
236
237
    def _compute_schedule_1(self):
        """Simple scheduler based on selection-insertion one state algorithm.
        
        Quotas are available only fo the night.
        No token.
        """
        t0 = time.time()
e5cec6d9   Alain Klotz   Update scheduler
238
        self.DPRINT = True
df477bca   Alain Klotz   New scheduler
239
240
241
242
        # --- Get the incoming directory of the night
        info = self.get_infos()
        rootdir = info['rootdir']
        subdir = info['subdir']
6bc582b5   Alain Klotz   Big debug at Guit...
243
244
        # --- Get the night
        night = info['night']
9b6af71d   Alain Klotz   Update version Sc...
245
246
247
248
249
250
251
252
        # --- Get ephemeris informations of the night and initialize quotas
        night_info = self.update_sun_moon_ephems()
        quota_total_period = night_info['total'][1]
        quota_total_night_start = night_info[night][0]
        quota_total_night_end = night_info[night][1]
        self.dprint(f"{quota_total_period=}")
        self.dprint(f"{quota_total_night_start=}")
        self.dprint(f"{quota_total_night_end=}")        
df477bca   Alain Klotz   New scheduler
253
254
255
256
257
258
        # --- Build the wildcard to list the sequences
        wildcard = os.path.join(rootdir, subdir, "*.p")
        self.dprint(f"{wildcard=}")
        # --- List the sequences from the incoming directory
        seqfiles = glob.glob(wildcard)
        log.info(f"{len(seqfiles)} file sequences to process")
6bc582b5   Alain Klotz   Big debug at Guit...
259
260
261
262
263
264
265
266
        # --- Initialize the predictive schedule from start of the night (=all the night)
        schedule_sequence_id = np.zeros(self.BINS_NIGHT, dtype=int) -1
        schedule_binary = np.ones(self.BINS_NIGHT, dtype=int)
        schedule_visibility = np.zeros(self.BINS_NIGHT, dtype=float)
        schedule_order = np.zeros(self.BINS_NIGHT, dtype=int) -1
        schedule_jd = np.zeros(self.BINS_NIGHT, dtype=float)
        schedule_scientific_programm_id = np.zeros(self.BINS_NIGHT, dtype=int) -1
        # --- Initialize the predictive schedule by the effective schedule from start of the current instant (=index)
a8cce62b   Alain Klotz   Json bdd and sche...
267
        try:
6bc582b5   Alain Klotz   Big debug at Guit...
268
269
270
271
272
273
274
            last_schedule = EffectiveSchedule.objects.last()
        except EffectiveSchedule.DoesNotExist:
            self.dprint(f"No effective schedule in the database (table is void)")
        # --- Get the numpy matrix of the effective schedule from the database (via Json)
        if last_schedule != None:
            input_matrix = last_schedule.conv_numpy()
            # --- Unpack the matrix to effective schedule arrays
def6f098   Alain Klotz   Fix bug in the bd...
275
            schedule_eff_jd, schedule_eff_binary, schedule_eff_sequence_id, schedule_eff_scientific_programm_id, schedule_eff_order, schedule_eff_visibility = input_matrix
6bc582b5   Alain Klotz   Big debug at Guit...
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
            # --- Get the index of the current instant in the night
            nownight, index = self._fn.date2night("now", self.BINS_NIGHT)
            self.dprint(f"{nownight=} {index=}")
            # --- Add all ever observed sequences from 0 to index
            if nownight == night and (index >= 0 or index < self.BINS_NIGHT):
                schedule_sequence_id[0:index] = schedule_eff_sequence_id[0:index]
                schedule_binary[0:index] = schedule_eff_binary[0:index]
                schedule_visibility[0:index] = schedule_eff_visibility[0:index]
                schedule_order[0:index] = schedule_eff_order[0:index]
                schedule_jd[0:index] = schedule_eff_jd[0:index]
                schedule_scientific_programm_id[0:index] = schedule_eff_scientific_programm_id[0:index]  
            else:
                # --- Case when there is not ever effective schedule for this night
                print(f"No effective schedule for this night {night}")
        else:
            # --- Case of invalid entry in the database
            print(f"Invalid entry in the database")
def6f098   Alain Klotz   Fix bug in the bd...
293
        #print(f"{schedule_jd=}")
e5cec6d9   Alain Klotz   Update scheduler
294

df477bca   Alain Klotz   New scheduler
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
        # ===================================================================
        # --- Loop over the sequences of the night to extract useful infos
        # ===================================================================
        self.dprint("\n" + "="*70 + f"\n=== Read {len(seqfiles)} sequence files of the night {info['night']}\n" + "="*70 + "\n")
        sequence_infos = []
        # --- Initialize the list of scientific_program_ids
        scientific_program_ids = []
        kseq  = 0
        for seqfile in seqfiles:
            # --- seqfile = sequence file name
            kseq += 1
            sequence_info = {}
            sequence_info['id'] = -1 # TBD replace by idseq of the database
            sequence_info['seqfile'] = seqfile
            sequence_info['error'] = ""
            sequence_info['kobs0'] = -1
            # --- ephfile = ephemeris file name
            ephfile = os.path.splitext(seqfile)[0] + ".f"
            # --- If ephemeris file exists, read files
            if os.path.exists(ephfile):
                self.dprint(f"Read file {seqfile}")
                # --- seq_info = sequence dictionary
                # --- eph_info = ephemeris dictionary
                seq_info = pickle.load(open(seqfile,"rb"))
                #print("="*20 + "\n" + f"{seq_info=}")
                eph_info = pickle.load(open(ephfile,"rb"))
                #print("="*20 + "\n" + f"{eph_info=}")
                # ---
                param = self._fn.naming_get(seqfile)
                sequence_info['id'] = int(param['id_seq'])
                # --- scientific_program_id is an integer
                scientific_program_id = seq_info['sequence']['scientific_program']
                # --- Dictionary of informations about the sequence
                sequence_info['seq_dico'] = seq_info # useful for duration
                # --- Search the last time when the start of the sequence is observable (visibility > 0)
                visibility_duration = eph_info['visibility_duration']
                kobss = np.where(visibility_duration > 0)
                kobss = list(kobss[0])
                if len(kobss) == 0:
                    self.dprint("  Sequence has no visibility")
                    sequence_info['error'] = f"Sequence has no visibility_duration"
                    sequence_infos.append(sequence_info)
                    continue
6bc582b5   Alain Klotz   Big debug at Guit...
338
                # --- TODO manage the case the sequence is before the current time (because of the effective schedule)
df477bca   Alain Klotz   New scheduler
339
340
341
342
343
344
345
346
347
                kobs0 = kobss[0]
                sequence_info['kobs0'] = kobs0    
                sequence_info['visibility'] = eph_info['visibility'] # total slots
                sequence_info['visibility_duration'] = visibility_duration # total slots - duration
                sequence_info['duration'] = seq_info['sequence']['duration']
                sequence_info['scientific_program_id'] = scientific_program_id
                self.dprint(f"  {scientific_program_id=} range to start={len(kobss)}")
                if scientific_program_id not in scientific_program_ids:
                    scientific_program_ids.append(scientific_program_id)
16da961d   Alain Klotz   First update for ...
348
349
                # --- TODO
                # update_db_quota_sequence( id_period, night_id, d_total=sequence_info['duration'] )                
df477bca   Alain Klotz   New scheduler
350
351
352
            else:
                sequence_info['error'] = f"File {ephfile} not exists"
            sequence_infos.append(sequence_info)
a8cce62b   Alain Klotz   Json bdd and sche...
353
354
355
356
        try:
            schedule_jd = eph_info['jd']
        except:
            pass
df477bca   Alain Klotz   New scheduler
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
            
        # ===================================================================
        # --- Get informations of priority and quota from scientific programs
        # ===================================================================
        self.dprint("\n" + "="*70 + f"\n=== Get information from {len(scientific_program_ids)} scientific programs of the night\n" + "="*70 + "\n")
        scientific_program_infos = {}
        period_id = info['operiod'].id
        self.dprint(f"{scientific_program_ids=}")
        for scientific_program_id in scientific_program_ids:
            scientific_program_info = {}
            try:
                osp = ScientificProgram.objects.get(id=scientific_program_id)
                # --- ospperiod is the SP object
                ospperiod = SP_Period.objects.get(period = period_id, scientific_program = osp)
                scientific_program_info['priority'] = ospperiod.priority
                scientific_program_info['over_quota_duration'] = ospperiod.over_quota_duration
                scientific_program_info['over_quota_duration_allocated'] = ospperiod.over_quota_duration_allocated
                scientific_program_info['over_quota_duration_remaining'] = ospperiod.over_quota_duration_remaining             
                scientific_program_info['quota_allocated'] = ospperiod.quota_allocated
                scientific_program_info['quota_minimal'] = ospperiod.quota_minimal
                scientific_program_info['quota_nominal'] = ospperiod.quota_nominal
                scientific_program_info['quota_remaining'] = ospperiod.quota_remaining           
                scientific_program_info['token_allocated'] = ospperiod.token_allocated
                scientific_program_info['token_remaining'] = ospperiod.token_allocated
            except:
                # --- simulation
                scientific_program_info['priority'] = 0
            if scientific_program_info['priority'] == 0:
                # --- simulation
                priority = 50 + scientific_program_id*5
                scientific_program_info['priority'] = priority
                scientific_program_info['quota_allocated'] = 12000
                scientific_program_info['quota_remaining'] = 12000  
            scientific_program_infos[str(scientific_program_id)] = scientific_program_info
            self.dprint(f"{scientific_program_id=} priority={scientific_program_info['priority']} quota={scientific_program_info['quota_remaining']}")
            
        # ===================================================================
        # --- Build the numpy matrix seqs to make rapid computations
        # ===================================================================
        self.dprint("\n" + "="*70 + f"\n=== Build the matrix for scheduling {len(sequence_infos)} sequences\n" + "="*70 + "\n")
        self.dprint("Order ID_seq K_start ID_sp Priority Duration Status\n")
        nseq = len(sequence_infos)
        if nseq == 0:
            self._routine_running = self.RUNNING_NOTHING
            return
        seqs = np.zeros((nseq, self.NB_SEQ), dtype=int)
        k = 0
        for sequence_info in sequence_infos:
            if 'scientific_program_id' not in sequence_info.keys():
                self.dprint(f"No scientific program for ID sequence {sequence_info['id']}")
                continue
            scientific_program_id = sequence_info['scientific_program_id']
            scientific_program_info = scientific_program_infos[str(scientific_program_id)]
            priority = scientific_program_info['priority']
            # Order of the following list refers to the enum
e5cec6d9   Alain Klotz   Update scheduler
412
            seq = [ k, sequence_info['id'], sequence_info['kobs0'], scientific_program_id, priority, int(np.ceil(sequence_info['duration'])), self.SEQ_NOT_PROCESSED] 
df477bca   Alain Klotz   New scheduler
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
            self.dprint(f"{seq=}")
            seqs[k] = seq
            k += 1
        seqs = seqs[:k]
        # --- Save the matrix sequence
        #print(f"{seqs=}")
        fpathname = os.path.join(rootdir, subdir, "scheduler_seq_matrix1.txt")
        np.savetxt(fpathname, seqs)
        
        # ===================================================================
        # --- Compute the matrix seq_sorteds (priority and chronology)
        # ===================================================================        
        self.dprint("\n" + "="*70 + "\n=== Sort the matrix for scheduling by priority and chronology\n" + "="*70 + "\n")
        # --- Sort the matrix sequence: priority=SEQ_PRIORITY (decreasing -1) and then chronology=SEQ_KOBS0 (increasing +1)
        seq_sorteds = seqs[np.lexsort(([1,-1]*seqs[:,[self.SEQ_KOBS0, self.SEQ_PRIORITY]]).T)]
        # --- Save the matrix sequence
        self.dprint("Order ID_seq K_start ID_sp Priority Duration Status\n")
        self.dprint(f"{seq_sorteds=}")
        fpathname = os.path.join(rootdir, subdir, "scheduler_seq_matrix2.txt")
        np.savetxt(fpathname, seq_sorteds)

        # ===================================================================
        # --- Insert sequences in the schedule. Respecting priority and quota
        # ===================================================================
        self.dprint("\n" + "="*70 + "\n=== Insertion of the sequences in the schedule respecting priority and quota\n" + "="*70 + "\n")
e5cec6d9   Alain Klotz   Update scheduler
438
439
440
441
        kseq_sorted = -1
        for seq_sorted in seq_sorteds:
            kseq_sorted += 1

df477bca   Alain Klotz   New scheduler
442
            # --- Unpack the sequence
e5cec6d9   Alain Klotz   Update scheduler
443
            k, sequence_id, kobs0, scientific_program_id, priority, duration, seq_status = seq_sorted
df477bca   Alain Klotz   New scheduler
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
            
            # --- Get the quota remaining of the scientific program
            quota_remaining = scientific_program_infos[str(scientific_program_id)]['quota_remaining']
            self.dprint('-'*70 + "\n" + f"Process {sequence_id=} {kobs0=} {duration=} sp_id={scientific_program_id} {quota_remaining=}")
            
            # --- Verify if duration < quota_remaining
            if duration > quota_remaining: 
                # --- No remaining quota to insert this sequence
                self.dprint(f"{sequence_id=} cannot be inserted because no quota enough")
                seqs[k][self.SEQ_STATUS] = self.SEQ_REJECTED_NO_QUOTA_ENOUGH
                continue
                
            # --- Compute the remaining visibility and list (k1s) of the best observation start
            # =0 if not possible to start observation
            # =value with the highest value for the best observation start
            
            # --- Visibility*schedule_binary are transformed into binary
            sequence_info = sequence_infos[k]
            vis_binarys = sequence_info['visibility'].copy() * schedule_binary
            vis_binarys[vis_binarys > 0] = 1
            
            # --- Cumulative sum + offset by -duration to prepare the start_binary computation
            obs_starts = np.cumsum(vis_binarys)
            obs_ends = obs_starts.copy()
            obs_ends[0:-duration] = obs_ends[duration:]
            obs_ends[-duration:] = 0

            # --- Difference and binarisation to get starts with duration
            start_binary = obs_ends - obs_starts
            start_binary[start_binary < duration] = 0
            start_binary[start_binary == duration] = 1
            
            # --- Compute the remaining visibility (float)
            remaining_visibility = sequence_info['visibility'] * start_binary
            
            # --- Check the remaining visibility
            if np.sum(remaining_visibility) == 0:
                # --- No remaining slot to insert this sequence
                self.dprint(f"{sequence_id=} cannot inserted because no more slots available")
                seqs[k][self.SEQ_STATUS] = self.SEQ_REJECTED_NO_SLOT_AVAILABLE
                continue
                
            # --- From the index of the highest value of remaining visibility to the index of the lowest value of remaining visibility
            k1s = np.flip(np.argsort(remaining_visibility))
            self.dprint(f"{k1s=} => Start elevation {sequence_info['visibility'][k1s[0]]:+.2f}")
            
            # --- Get k1 as the highest value of remaining visibility
            k1 = k1s[0]
            k2 = k1 + duration
            self.dprint(f"{k} : {sequence_id=} {scientific_program_id=} {priority=} inserted in the slot {k1=} {k2=} (remaining {quota_remaining - duration} s)")
            
            # --- Update the seqs matrix
            seqs[k][self.SEQ_STATUS] = self.SEQ_SCHEDULED
            
            # --- Update the schedule arrays
e5cec6d9   Alain Klotz   Update scheduler
499
            schedule_sequence_id[k1:k2] = sequence_id
df477bca   Alain Klotz   New scheduler
500
            schedule_binary[k1:k2] = 0
e5cec6d9   Alain Klotz   Update scheduler
501
502
503
            schedule_visibility[k1:k2] = sequence_info['visibility'][k1:k2]
            schedule_order[k1:k2] = kseq_sorted
            schedule_scientific_programm_id[k1:k2] = scientific_program_id
df477bca   Alain Klotz   New scheduler
504
505
506
507
            
            # --- Update the scientific program dict
            quota_remaining -= duration
            scientific_program_infos[str(scientific_program_id)]['quota_remaining'] = quota_remaining
e5cec6d9   Alain Klotz   Update scheduler
508
                        
df477bca   Alain Klotz   New scheduler
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523

        # ===================================================================
        # --- Insert sequences in the schedule. Respecting priority but over quota
        # ===================================================================
        # self.dprint("\n" + "="*70 + "\n=== Insertion of the sequences in the schedule respecting priority but over quota\n" + "="*70 + "\n")
        # TBD
        # where are remaining free slots
        # scan sequences to insert in these free slots
            
        # ===================================================================
        # --- Save the schedule
        # ===================================================================
        self.dprint("\n" + "="*70 + "\n=== Save the schedule\n" + "="*70 + "\n")
        self.dprint("Order ID_seq K_start ID_sp Priority Duration Status\n")
        self.dprint(f"{seqs=}")
a8cce62b   Alain Klotz   Json bdd and sche...
524
525
526
        # --- Prepare the output matrix
        ouput_matrix = np.array([schedule_jd, schedule_binary, schedule_sequence_id, schedule_scientific_programm_id, schedule_order, schedule_visibility])
        # --- Save the numpy matrix in ASCII
df477bca   Alain Klotz   New scheduler
527
        fpathname = os.path.join(rootdir, subdir, "scheduler_schedule.txt")
a8cce62b   Alain Klotz   Json bdd and sche...
528
529
        np.savetxt(fpathname, ouput_matrix.T)
        # --- Save the numpy matrix in database (via Json)
6bc582b5   Alain Klotz   Big debug at Guit...
530
531
        v = PredictiveSchedule.objects.last()
        if v == None:
def6f098   Alain Klotz   Fix bug in the bd...
532
            v = PredictiveSchedule()
19813230   Alain Klotz   New DATA structur...
533
        #log.info(f"{v=}")
a8cce62b   Alain Klotz   Json bdd and sche...
534
535
536
        v.scheduler_matrix = ouput_matrix
        v.save()
        # --- Save the numpy matrix in database (via Json)
6bc582b5   Alain Klotz   Big debug at Guit...
537
538
        v = EffectiveSchedule.objects.last()
        if v==None:
def6f098   Alain Klotz   Fix bug in the bd...
539
            v = EffectiveSchedule()
a8cce62b   Alain Klotz   Json bdd and sche...
540
541
        v.scheduler_matrix = ouput_matrix
        v.save()
df477bca   Alain Klotz   New scheduler
542
543
        # --- Update the running state
        self._routine_running = self.RUNNING_NOTHING
19813230   Alain Klotz   New DATA structur...
544
        log.info(f"_compute_schedule_1 finished in {time.time() - t0:.2f} seconds")
6cd48351   Etienne Pallier   AgentScheduler is...
545

19813230   Alain Klotz   New DATA structur...
546
    def _create_seq_1(self, nb_seq: int):
df477bca   Alain Klotz   New scheduler
547
548
        t0 = time.time()
        self.dprint("Debut _create_seq_1")
19813230   Alain Klotz   New DATA structur...
549
        seq_template = {'sequence': {'id': 4, 'start_expo_pref': 'IMMEDIATE', 'pyros_user': 2, 'scientific_program': 1, 'name': 'seq_20230628T102140', 'desc': None, 'last_modified_by': 2, 'is_alert': False, 'status': 'TBP', 'with_drift': False, 'priority': None, 'analysis_method': None, 'moon_min': None, 'alt_min': None, 'type': None, 'img_current': None, 'img_total': None, 'not_obs': False, 'obsolete': False, 'processing': False, 'flag': None, 'period': 1, 'start_date': datetime.datetime(2023, 6, 28, 10, 21, 40, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'end_date': datetime.datetime(2023, 6, 28, 10, 21, 40, 999640, tzinfo=datetime.timezone.utc), 'jd1': Decimal('0E-8'), 'jd2': Decimal('0E-8'), 'tolerance_before': '1s', 'tolerance_after': '1min', 'duration': -1.0, 'overhead': Decimal('0E-8'), 'submitted': False, 'config_attributes': {'tolerance_before': '1s', 'tolerance_after': '1min', 'target': 'RADEC 0H10M -15D', 'conformation': 'WIDE', 'layout': 'Altogether'}, 'ra': None, 'dec': None, 'complete': True, 'night_id': '20230627'}, 'albums': {'Altogether': {'plans': [{'id': 4, 'album': 4, 'duration': 0.0, 'nb_fnges': 1, 'config_attributes': {'binnings': {'binxy': [1, 1], 'readouttime': 6}, 'exposuretime': 1.0}, 'complete': True}]}}}
e5cec6d9   Alain Klotz   Update scheduler
550
        # decode general variables info a dict info 
df477bca   Alain Klotz   New scheduler
551
552
553
        info = self.get_infos()
        rootdir = info['rootdir']
        subdir = info['subdir']
19813230   Alain Klotz   New DATA structur...
554
        
9b6af71d   Alain Klotz   Update version Sc...
555
        # --- Read or create the sun ephemeris
3825738b   Alain Klotz   Debug Scheduler.
556
        ephem_sun = self.ephem_target2night("sun")
19813230   Alain Klotz   New DATA structur...
557

9b6af71d   Alain Klotz   Update version Sc...
558
        # --- Read or create the moon ephemeris
3825738b   Alain Klotz   Debug Scheduler.
559
        ephem_moon = self.ephem_target2night("moon")
19813230   Alain Klotz   New DATA structur...
560

9b6af71d   Alain Klotz   Update version Sc...
561
562
563
564
        # --- Prepare ephemeris object
        eph = guitastro.Ephemeris()
        eph.set_home(self.config.getHome())

df477bca   Alain Klotz   New scheduler
565
        # --- Horizon (TBD get from config)
19813230   Alain Klotz   New DATA structur...
566
        self.dprint("Debut _create_seq_1 Horizon")
df477bca   Alain Klotz   New scheduler
567
        hor = guitastro.Horizon(eph.home)
3825738b   Alain Klotz   Debug Scheduler.
568
        hor.horizon_altaz = self.config.getHorizonLine(self.config.unit_name)
19813230   Alain Klotz   New DATA structur...
569
        
df477bca   Alain Klotz   New scheduler
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
        # --- Delete all existing *.p and *.f files in the night directory
        fn_param = {
            "period" : f"{info['period_id']}",
            "version": "1",
            "unit": self.config.unit_name,
            "date": info['night'],
            "id_seq": 0
        }
        fname = self._fn.naming_set(fn_param)
        self.dprint(f":: {fname=}")
        seq_file = self._fn.join(fname)
        path_night = os.path.dirname(seq_file)
        cards = ['*.p', '*.f']
        for card in cards:
            wildcard = os.path.join(path_night, card)
            seq_dfiles = glob.glob(wildcard)
            #print(f"::: {seq_dfiles=}")
            for seq_dfile in seq_dfiles:
                #print(f":::.1 : os.remove {seq_dfile=}")
                os.remove(seq_dfile)
19813230   Alain Klotz   New DATA structur...
590
591
                
        # --- Create new sequences
df477bca   Alain Klotz   New scheduler
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
        for k in range(nb_seq):
            #print("B"*20 + f" {info['operiod'].id} {info['night']} {k}")
            time.sleep(1)
            seq = seq_template.copy()
            seq['sequence']['period'] = info['operiod'].id # int
            seq['sequence']['night_id'] = info['night'] # str
            seq['sequence']['config_attributes']['target'] = k # int
            # ---
            start_expo_pref = "BESTELEV" #"IMMEDIATE"
            scientific_program = int(k/2)
            start_date = datetime.datetime(2023, 6, 28, 10, 21, 40)
            end_date = datetime.datetime(2023, 6, 28, 10, 21, 40, 999640, tzinfo=datetime.timezone.utc)
            jd1 = Decimal('0E-8')
            jd2 = Decimal('0E-8')
            tolerance_before = '1s'
            tolerance_after = '1min'
            duration =  3000.0
            target = f"RADEC {k}h {10+2*k}d"
            # ---
            seq['sequence']['start_expo_pref'] = start_expo_pref
            seq['sequence']['scientific_program'] = scientific_program
            seq['sequence']['start_date'] = start_date
            seq['sequence']['end_date'] = end_date
            seq['sequence']['jd1'] = jd1
            seq['sequence']['jd2'] = jd2
            seq['sequence']['tolerance_before'] = tolerance_before
            seq['sequence']['tolerance_after'] = tolerance_after
            seq['sequence']['duration'] = duration
            seq['sequence']['config_attributes']['target'] = target
            # --- Build the path and file name of the sequence file
19813230   Alain Klotz   New DATA structur...
622
623
            fn_param["id_seq"] = int("999" + f"{k:07d}")
            self.dprint(f"{k} : {self._fn.fcontext=}")
df477bca   Alain Klotz   New scheduler
624
            self._fn.fname = self._fn.naming_set(fn_param)
19813230   Alain Klotz   New DATA structur...
625
            self.dprint(f"{k} : {self._fn.fname=}")
df477bca   Alain Klotz   New scheduler
626
            seq_file = self._fn.join(self._fn.fname)
19813230   Alain Klotz   New DATA structur...
627
            self.dprint(f"{k} : {seq_file=}")
df477bca   Alain Klotz   New scheduler
628
629
630
            # --- Build the path and file name of the ephemeris file
            eph_file = f"{seq_file[:-2]}.f"
            # --- Create directory if it doesn't exist
19813230   Alain Klotz   New DATA structur...
631
            self.dprint(f"{k} : {seq_file=}")
df477bca   Alain Klotz   New scheduler
632
633
634
635
636
            os.makedirs(os.path.dirname(seq_file), exist_ok=True)
            # --- Compute the ephemeris of the sequence and manage errors
            #print(f"{k} : TRY")
            errors = []
            try:
9b6af71d   Alain Klotz   Update version Sc...
637
                ephem = eph.target2night(seq["sequence"]["config_attributes"]["target"], info['night'], ephem_sun, ephem_moon, preference=seq['sequence']['start_expo_pref'], duskelev=self._duskelev, horizon=hor, duration=duration)
df477bca   Alain Klotz   New scheduler
638
639
640
641
642
643
644
645
646
            except ValueError:
                errors.append("Target value is not valid")
            except guitastro.ephemeris.EphemerisException as ephemException:
                errors.append(str(ephemException))
            if len(errors) == 0 and np.sum(ephem["visibility"]) == 0 :
                errors.append("Target is not visible.")
            if len(errors) == 0:
                pickle.dump(ephem, open(eph_file,"wb"))
                pickle.dump(seq, open(seq_file,"wb"))
19813230   Alain Klotz   New DATA structur...
647
648
649
            #dprint(f"{errors=}")
            #dprint("C"*20)
        log.info(f"_create_seq_1 finished in {time.time() - t0:.2f} seconds")
df477bca   Alain Klotz   New scheduler
650
651
652
653
        
    def load_sequence(self):
        sequence = ""
        return sequence
9b6af71d   Alain Klotz   Update version Sc...
654
        
df477bca   Alain Klotz   New scheduler
655
    def get_infos(self):
19813230   Alain Klotz   New DATA structur...
656
        self._fn.fcontext = "pyros_seq"
df477bca   Alain Klotz   New scheduler
657
658
659
660
661
662
        rootdir = self._fn.rootdir
        operiod = Period.objects.exploitation_period()
        if operiod == None:
            log.info("No period valid in the database")
            self._routine_running = self.RUNNING_NOTHING
            return
9b6af71d   Alain Klotz   Update version Sc...
663
        # retourne un str -> id de la période sous le format Pxxx
ca4a0ec6   Alain Klotz   Scheduler bugfix.
664
        period_id = operiod.get_id_as_str() 
9b6af71d   Alain Klotz   Update version Sc...
665
 
df477bca   Alain Klotz   New scheduler
666
667
668
669
670
671
672
673
674
675
676
677
        night_id = self._fn.date2night("now")
        subdir = os.path.join(period_id, night_id)
        dico = {}
        dico['rootdir'] = rootdir
        dico['subdir'] = subdir
        dico['operiod'] = operiod # object
        dico['period_id'] = period_id # str formated (P000)
        dico['night'] = night_id # str (YYYYMMDD)
        return dico
        
    def dprint(self, *args, **kwargs):
        if self.DPRINT:
19813230   Alain Klotz   New DATA structur...
678
            log.info(*args, **kwargs)
df477bca   Alain Klotz   New scheduler
679
        
6cd48351   Etienne Pallier   AgentScheduler is...
680
681
if __name__ == "__main__":

7fd005b5   Alain Klotz   New scheduler
682
    agent = build_agent(A_Scheduler)
6cd48351   Etienne Pallier   AgentScheduler is...
683
684
    print(agent)
    agent.run()