import os from earthdiagnostics.box import Box from earthdiagnostics.diagnostic import Diagnostic from earthdiagnostics.utils import Utils, TempFile class AverageSection(Diagnostic): """ Compute an average of a given zone. The variable MUST be in a regular grid :original author: Virginie Guemas :contributor: Javier Vegas-Regidor :created: March 2012 :last modified: June 2016 """ def __init__(self, data_manager, startdate, member, chunk, variable, domain, box): Diagnostic.__init__(self, data_manager) self.startdate = startdate self.member = member self.chunk = chunk self.variable = variable self.domain = domain self.box = box def __str__(self): return 'Average section Startdate: {0} Member: {1} Chunk: {2} Box: {3} ' \ 'Variable: {4}:{5}'.format(self.startdate, self.member, self.chunk, self.box, self.domain, self.variable) @classmethod def generate_jobs(cls, diags, options): """ Creates a job for each chunk to compute the diagnostic :param diags: Diagnostics manager class :type diags: Diags :param options: variable, minimun longitude, maximun longitude, minimum latitude, maximum latitude, domain=ocean :type options: List[str] :return: """ num_options = len(options) - 1 if num_options < 5: raise Exception('You must specify the variable and the box to average') if num_options > 6: raise Exception('You must specify between 5 and 6 parameters for the section average diagnostic') variable = options[1] box = Box() box.min_lon = int(options[2]) box.max_lon = int(options[3]) box.min_lat = int(options[4]) box.max_lat = int(options[5]) if num_options >= 6: domain = options[6] else: domain = 'ocean' job_list = list() for startdate in diags.startdates: for member in diags.members: for chunk in range(1, diags.chunks + 1): job_list.append(AverageSection(diags.data_manager, startdate, member, chunk, variable, domain, box)) return job_list def compute(self): temp = TempFile.get() variable_file = self.data_manager.get_file(self.domain, self.variable, self.startdate, self.member, self.chunk, grid='regular') Utils.cdo.zonmean(input='-sellonlatbox,{0},{1},{2},{3} {4}'.format(self.box.min_lon, self.box.max_lon, self.box.min_lat, self.box.max_lat, variable_file), output=temp) os.remove(variable_file) self.data_manager.send_file(temp, self.domain, self.variable + 'mean', self.startdate, self.member, self.chunk, box=self.box, grid='regular')