Blame view

src/core/pyros_django/scheduling/A_Scheduler.py 34.2 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
23
# ./PYROS -d -t new-start -o tnc -fg -a A_Scheduler
#
# ---------------------------------------------------
6cd48351   Etienne Pallier   AgentScheduler is...
24
25

import sys
6cd48351   Etienne Pallier   AgentScheduler is...
26
import time
df477bca   Alain Klotz   New scheduler
27
28
29
30
31
32
33
import argparse
import os
import pickle
import socket
pwd = os.environ['PROJECT_ROOT_PATH']
if pwd not in sys.path:
    sys.path.append(pwd)
6cd48351   Etienne Pallier   AgentScheduler is...
34

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

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

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

19813230   Alain Klotz   New DATA structur...
56
    DPRINT = True
df477bca   Alain Klotz   New scheduler
57
    
6bc582b5   Alain Klotz   Big debug at Guit...
58
59
60
    # - Sampling of the night arrays (bins/night)
    BINS_NIGHT = 86400
    
df477bca   Alain Klotz   New scheduler
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    # - 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...
81

df477bca   Alain Klotz   New scheduler
82
83
84
85
86
    _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...
87

19813230   Alain Klotz   New DATA structur...
88
    # Test scenario to be executed (option -t)
df477bca   Alain Klotz   New scheduler
89
90
91
92
93
    # "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...
94
        (True, "self do_stop asap", 500, "STOPPING", Agent.CMD_STATUS.CMD_EXECUTED),
bd4b900a   Etienne Pallier   update replan
95
    ]
6cd48351   Etienne Pallier   AgentScheduler is...
96

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

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

df477bca   Alain Klotz   New scheduler
116
117
118
119
120
121
        # === 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...
122

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

        # === Status of routine processing
        self._routine_running = self.RUNNING_NOTHING
        log.debug("end init()")
e5cec6d9   Alain Klotz   Update scheduler
132
        ##### TBD suppress redondant paths in print(f"=>=>=> {sys.path=}")
6cd48351   Etienne Pallier   AgentScheduler is...
133
134
135

    # Note : called by _routine_process() in Agent
    # @override
547df0ef   Etienne Pallier   routine_process_b...
136
    def _routine_process_iter_start_body(self):
739c899f   Etienne Pallier   Ajout routine_pro...
137
        log.debug("in routine_process_before_body()")
739c899f   Etienne Pallier   Ajout routine_pro...
138
139
140

    # Note : called by _routine_process() in Agent
    # @override
547df0ef   Etienne Pallier   routine_process_b...
141
    def _routine_process_iter_end_body(self):
739c899f   Etienne Pallier   Ajout routine_pro...
142
        log.debug("in routine_process_after_body()")
df477bca   Alain Klotz   New scheduler
143
144
145
146
147
148
        # 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...
149

df477bca   Alain Klotz   New scheduler
150
151
152
153
154
155
    """
    =================================================================
        Methods of specific commands
    =================================================================
    """

e5cec6d9   Alain Klotz   Update scheduler
156
    def do_create_seq_1(self, nb_seq:int):
df477bca   Alain Klotz   New scheduler
157
158
        """Create sequences to debug
        """
19813230   Alain Klotz   New DATA structur...
159
160
161
162
        try:
            self._create_seq_1(nb_seq)
        except Exception as e:
            self.dprint(f"ERROR {e}")
df477bca   Alain Klotz   New scheduler
163
164
165
166
167
168
169
170
171
172
173
174
175
176

    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...
177
178
179
180
        try:
            self._compute_schedule_1()
        except Exception as e:
            self.dprint(f"ERROR {e}")
df477bca   Alain Klotz   New scheduler
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

    """
    =================================================================
        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'
    """
    
    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
224
        self.DPRINT = True
df477bca   Alain Klotz   New scheduler
225
226
227
228
        # --- Get the incoming directory of the night
        info = self.get_infos()
        rootdir = info['rootdir']
        subdir = info['subdir']
6bc582b5   Alain Klotz   Big debug at Guit...
229
230
        # --- Get the night
        night = info['night']
df477bca   Alain Klotz   New scheduler
231
232
233
234
235
236
        # --- 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...
237
238
239
240
241
242
243
244
        # --- 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...
245
        try:
6bc582b5   Alain Klotz   Big debug at Guit...
246
247
248
249
250
251
252
            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...
253
            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...
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
            # --- 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...
271
        #print(f"{schedule_jd=}")
e5cec6d9   Alain Klotz   Update scheduler
272

df477bca   Alain Klotz   New scheduler
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
        # ===================================================================
        # --- 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...
316
                # --- TODO manage the case the sequence is before the current time (because of the effective schedule)
df477bca   Alain Klotz   New scheduler
317
318
319
320
321
322
323
324
325
326
327
328
                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)
            else:
                sequence_info['error'] = f"File {ephfile} not exists"
            sequence_infos.append(sequence_info)
a8cce62b   Alain Klotz   Json bdd and sche...
329
330
331
332
        try:
            schedule_jd = eph_info['jd']
        except:
            pass
df477bca   Alain Klotz   New scheduler
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
            
        # ===================================================================
        # --- 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
388
            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
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
            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
414
415
416
417
        kseq_sorted = -1
        for seq_sorted in seq_sorteds:
            kseq_sorted += 1

df477bca   Alain Klotz   New scheduler
418
            # --- Unpack the sequence
e5cec6d9   Alain Klotz   Update scheduler
419
            k, sequence_id, kobs0, scientific_program_id, priority, duration, seq_status = seq_sorted
df477bca   Alain Klotz   New scheduler
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
            
            # --- 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
475
            schedule_sequence_id[k1:k2] = sequence_id
df477bca   Alain Klotz   New scheduler
476
            schedule_binary[k1:k2] = 0
e5cec6d9   Alain Klotz   Update scheduler
477
478
479
            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
480
481
482
483
            
            # --- Update the scientific program dict
            quota_remaining -= duration
            scientific_program_infos[str(scientific_program_id)]['quota_remaining'] = quota_remaining
e5cec6d9   Alain Klotz   Update scheduler
484
                        
df477bca   Alain Klotz   New scheduler
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

        # ===================================================================
        # --- 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...
500
501
502
        # --- 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
503
        fpathname = os.path.join(rootdir, subdir, "scheduler_schedule.txt")
a8cce62b   Alain Klotz   Json bdd and sche...
504
505
        np.savetxt(fpathname, ouput_matrix.T)
        # --- Save the numpy matrix in database (via Json)
6bc582b5   Alain Klotz   Big debug at Guit...
506
507
        v = PredictiveSchedule.objects.last()
        if v == None:
def6f098   Alain Klotz   Fix bug in the bd...
508
            v = PredictiveSchedule()
19813230   Alain Klotz   New DATA structur...
509
        #log.info(f"{v=}")
a8cce62b   Alain Klotz   Json bdd and sche...
510
511
512
        v.scheduler_matrix = ouput_matrix
        v.save()
        # --- Save the numpy matrix in database (via Json)
6bc582b5   Alain Klotz   Big debug at Guit...
513
514
        v = EffectiveSchedule.objects.last()
        if v==None:
def6f098   Alain Klotz   Fix bug in the bd...
515
            v = EffectiveSchedule()
a8cce62b   Alain Klotz   Json bdd and sche...
516
517
        v.scheduler_matrix = ouput_matrix
        v.save()
df477bca   Alain Klotz   New scheduler
518
519
        # --- Update the running state
        self._routine_running = self.RUNNING_NOTHING
19813230   Alain Klotz   New DATA structur...
520
        log.info(f"_compute_schedule_1 finished in {time.time() - t0:.2f} seconds")
6cd48351   Etienne Pallier   AgentScheduler is...
521

19813230   Alain Klotz   New DATA structur...
522
    def _create_seq_1(self, nb_seq: int):
df477bca   Alain Klotz   New scheduler
523
524
        t0 = time.time()
        self.dprint("Debut _create_seq_1")
19813230   Alain Klotz   New DATA structur...
525
        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
526
        # decode general variables info a dict info 
df477bca   Alain Klotz   New scheduler
527
528
529
        info = self.get_infos()
        rootdir = info['rootdir']
        subdir = info['subdir']
19813230   Alain Klotz   New DATA structur...
530
        
df477bca   Alain Klotz   New scheduler
531
532
533
534
535
        # --- Prepare ephemeris object
        # TBD duskelev a parametrer from obsconfig (yml)
        duskelev = -7
        eph = guitastro.Ephemeris()
        eph.set_home(self.config.getHome())
19813230   Alain Klotz   New DATA structur...
536
        
1cd8d8dd   Alain Klotz   Ephem sun and Moon.
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
        """ A placer dans Agent
        def ephem_target2night(target->str) -> dict:
            fcontext0 = self._oc['config'].fn.fcontext
            # --- Build the path and file name of the sun ephemeris
            self._oc['config'].fn.fcontext = "pyros_eph"
            night = self._oc['config'].fn.date2night("now")
            fn_param = {
                "period" : f"{info['period_id']}",
                "date": night,
                "version": "1",
                "unit": self._oc['config'].unit_name,
                "target": target
            }
            fname = self._fn.naming_set(fn_param)
            eph_file = self._fn.joinabs(fname)
            # --- Compute the sun ephemeris if needed. Save it as pickle.
            if not os.path.exists(eph_file):
                ephem_target = eph.target2night(target, night, None, None)
                os.makedirs(os.path.dirname(eph_file), exist_ok=True)
                pickle.dump(ephem_sun, open(eph_file,"wb"))
            else:
                ephem_target = pickle.load(open(eph_file,"rb"))
            self._oc['config'].fn.fcontext = fcontext0
            return ephem_target
        """

19813230   Alain Klotz   New DATA structur...
563
564
565
566
567
568
569
570
571
572
573
574
575
        # --- Build the path and file name of the sun ephemeris
        self._fn.fcontext = "pyros_eph"
        fn_param = {
            "period" : f"{info['period_id']}",
            "date": info['night'],
            "version": "1",
            "unit": self.config.unit_name,
            "target": "sun"
        }
        fname = self._fn.naming_set(fn_param)
        eph_file = self._fn.joinabs(fname)
        # --- Compute the sun ephemeris if needed. Save it as pickle.
        if not os.path.exists(eph_file):
e5cec6d9   Alain Klotz   Update scheduler
576
            ephem_sun = eph.target2night("sun", info['night'], None, None)
19813230   Alain Klotz   New DATA structur...
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
            os.makedirs(os.path.dirname(eph_file), exist_ok=True)
            pickle.dump(ephem_sun, open(eph_file,"wb"))
        else:
            ephem_sun = pickle.load(open(eph_file,"rb"))
        self._fn.fcontext = "pyros_seq"

        # --- Build the path and file name of the moon ephemeris
        self._fn.fcontext = "pyros_eph"
        fn_param = {
            "period" : f"{info['period_id']}",
            "date": info['night'],
            "version": "1",
            "unit": self.config.unit_name,
            "target": "moon"
        }
        fname = self._fn.naming_set(fn_param)
        eph_file = self._fn.joinabs(fname)
        # --- Compute the moon ephemeris if needed. Save it as pickle.
        if not os.path.exists(eph_file):
            ephem_moon = eph.target2night("moon", info['night'], None, None)
            os.makedirs(os.path.dirname(eph_file), exist_ok=True)
            pickle.dump(ephem_moon, open(eph_file,"wb"))
        else:
            ephem_moon = pickle.load(open(eph_file,"rb"))
        self._fn.fcontext = "pyros_seq"

df477bca   Alain Klotz   New scheduler
603
        # --- Horizon (TBD get from config)
19813230   Alain Klotz   New DATA structur...
604
        self.dprint("Debut _create_seq_1 Horizon")
df477bca   Alain Klotz   New scheduler
605
606
        hor = guitastro.Horizon(eph.home)
        hor.horizon_altaz = [ [0,0], [360,0] ]
19813230   Alain Klotz   New DATA structur...
607
        
df477bca   Alain Klotz   New scheduler
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
        # --- 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...
628
629
                
        # --- Create new sequences
df477bca   Alain Klotz   New scheduler
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
        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...
660
661
            fn_param["id_seq"] = int("999" + f"{k:07d}")
            self.dprint(f"{k} : {self._fn.fcontext=}")
df477bca   Alain Klotz   New scheduler
662
            self._fn.fname = self._fn.naming_set(fn_param)
19813230   Alain Klotz   New DATA structur...
663
            self.dprint(f"{k} : {self._fn.fname=}")
df477bca   Alain Klotz   New scheduler
664
            seq_file = self._fn.join(self._fn.fname)
19813230   Alain Klotz   New DATA structur...
665
            self.dprint(f"{k} : {seq_file=}")
df477bca   Alain Klotz   New scheduler
666
667
668
            # --- 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...
669
            self.dprint(f"{k} : {seq_file=}")
df477bca   Alain Klotz   New scheduler
670
671
672
673
674
            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:
df477bca   Alain Klotz   New scheduler
675
676
677
678
679
680
681
682
683
684
                ephem = eph.target2night(seq["sequence"]["config_attributes"]["target"], info['night'], ephem_sun, ephem_moon, preference=seq['sequence']['start_expo_pref'], duskelev=duskelev, horizon=hor, duration=duration)
            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...
685
686
687
            #dprint(f"{errors=}")
            #dprint("C"*20)
        log.info(f"_create_seq_1 finished in {time.time() - t0:.2f} seconds")
df477bca   Alain Klotz   New scheduler
688
689
690
691
        
    def load_sequence(self):
        sequence = ""
        return sequence
6cd48351   Etienne Pallier   AgentScheduler is...
692

df477bca   Alain Klotz   New scheduler
693
    def get_infos(self):
19813230   Alain Klotz   New DATA structur...
694
        self._fn.fcontext = "pyros_seq"
df477bca   Alain Klotz   New scheduler
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
        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
        period_id = str(operiod.id)
        if len(str(operiod.id)) < 3:
            while len(period_id) < 3:
                period_id = "0" + period_id
        period_id = "P" + period_id
        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...
718
            log.info(*args, **kwargs)
df477bca   Alain Klotz   New scheduler
719
        
6cd48351   Etienne Pallier   AgentScheduler is...
720
721
if __name__ == "__main__":

7fd005b5   Alain Klotz   New scheduler
722
    agent = build_agent(A_Scheduler)
6cd48351   Etienne Pallier   AgentScheduler is...
723
724
    print(agent)
    agent.run()