StrategyBuilder.py 2.14 KB
from common.RequestBuilder import RequestBuilder
import xml.etree.ElementTree as ET
import os
from pyrosapp.models import *

JD1 = 0
JD2 = 9000000

class StrategyBuilder():
    '''
        Reads a strategy file and creates a new request with it
        
        ENTRY POINT :
            - create_request_from_strategy
    '''

    def create_request_from_strategy(self, strategy_file, pyros_user, scientific_program, name):
        '''
            Reads the strategy file, and creates the request, saving everything in DB
            
            :param : strategy_file, the name of the strategy file with .xml but without the path
            :param : pyros_user, the user associated with the existing alert
            :param : scientific_program, the sci prog of the existing alert
            :param : name, the name of the existing request + name of the strategy
            :returns : the created request
        '''

        tree = ET.parse(os.path.join('alert_manager', 'strategies', strategy_file))
        request = tree.getroot()

        for strategy in StrategyObs.objects.all():
            if (len(strategy.name) + 1) <= len(name):
                if name[-len(strategy.name):] == strategy.name:
                    name = name[:-(len(strategy.name) + 1)]
                    break
        name = name + '_' + strategy_file[:-4]
        self.rb = RequestBuilder()
        self.rb.start_new_request(pyros_user, scientific_program, True, name)
        for sequence in request:
            self.add_sequence(sequence, scientific_program.priority)
        self.rb.validate_request()
        return self.rb.request

    def add_sequence(self, sequence, priority):
        sequence_id = self.rb.add_sequence(priority, JD1, JD2, -1, sequence.get('name'))
        for album in sequence:
            self.add_album(album, sequence_id)

    def add_album(self, album, sequence_id):
        album_id = self.rb.add_album(sequence_id, album.get('detector'))
        for plan in album:
            self.add_plan(plan, album_id)

    def add_plan(self, plan, album_id):
        self.rb.add_plan(album_id, plan.get('filter'), plan.get('duration'),
                         plan.get('nb_images'))