utils.py 2.41 KB
Newer Older
from autosubmit.config.log import Log
from cdo import Cdo
from nco import Nco
import tempfile
import os


class Utils(object):
    scratch_folder = '/scratch/Earth/jvegas'

    nco = Nco()
    cdo = Cdo()
    files = list()

    @staticmethod
    def setminmax(filename, variable_list):
        Log.info('Getting max and min values for {0}', ' '.join(variable_list))
        dataset = Utils.nco.readCdf(filename)
        for variable in variable_list:
            var = dataset.variables[variable]
            values = [np.max(var), np.min(var)]
            Utils.nco.ncatted(input=filename, output=filename,
                              options='-h -a valid_max,{0},m,f,{1}'.format(variable, values[0]))
            Utils.nco.ncatted(input=filename, output=filename,
                              options='-h -a valid_min,{0},m,f,{1}'.format(variable, values[1]))

    @staticmethod
    def get_temp_file():
        temp_file = tempfile.mkstemp(dir=Utils.scratch_folder, prefix='diag', suffix='.nc')[1]
        Utils.files.append(temp_file)
        return temp_file

    @staticmethod
    def get_scratch_file(filename):
        return os.path.join(Utils.scratch_folder, filename)

    @staticmethod
    def clean():
        for temp_file in Utils.files:
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
            if os.path.exists(temp_file):
                os.remove(temp_file)
        Utils.files = list()
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed

    @staticmethod
    def rename_variable(filename, old_name, new_name, must_exist=True, rename_dimension=False):
        if must_exist:
            dot = ''
        else:
            dot = '.'
        options = '-v {0}{1},{2}'.format(dot, old_name, new_name)
        if rename_dimension:
            options += ' -d {0}{1},{2}'.format(dot, old_name, new_name)
        Utils.nco.ncrename(input=filename, output=filename, options=options)
        return os.path.join(Utils.scratch_folder, filename)

    @staticmethod
    def rename_variables(filename, dic_names, must_exist=True, rename_dimension=False):
        if must_exist:
            dot = ''
        else:
            dot = '.'
        options = ''
        for old_name, new_name in dic_names.items():
            options += '-v {0}{1},{2} '.format(dot, old_name, new_name)
            if rename_dimension:
                options += ' -d {0}{1},{2} '.format(dot, old_name, new_name)
        Utils.nco.ncrename(input=filename, output=filename, options=options)
        return os.path.join(Utils.scratch_folder, filename)