StrategyBuilder.py 2.34 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 index, sequence in enumerate(request):
            self.add_sequence(sequence, scientific_program.priority, name + "_" + str(index))
        return self.rb.request

    def add_sequence(self, sequence, priority, name):
        sequence_id = self.rb.add_sequence(priority, JD1, JD2, -1, name=name)
        for index, album in enumerate(sequence):
            self.add_album(album, sequence_id, name + str(index))

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

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

    def validate(self):
        self.rb.validate_request()
        return self.rb.request