variable.py 4.04 KB
Newer Older
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
# coding=utf-8
import csv

import os
from autosubmit.config.log import Log

from earthdiagnostics.constants import Basins


class Variable(object):
    """
    Class to characterize a CMOR variable. It also contains the static method to make the match between thje original
    name and the standard name. Requires cmor_table.csv to work.
    """
    _dict_variables = None

    def __init__(self, line):
        self.short_name = line[1].strip()
        self.standard_name = line[2].strip()
        self.long_name = line[3].strip()
        self.basin = Basins.parse(line[5])
        self.units = line[6].strip()
        self.valid_min = line[7].strip()
        self.valid_max = line[8].strip()
    def get_variable(cls, original_name, silent=False):
        """
        Returns the cmor variable instance given a variable name

        :param original_name: original variable's name
        :type original_name: str
        :param silent: if True, omits log warning when variable is not found
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
        :type silent: bool
        :return: CMOR variable
        :rtype: Variable
        """
        try:
            return cls._dict_variables[original_name.lower()]
        except KeyError:
            if not silent:
                Log.warning('Variable {0} is not defined in the CMOR table. Please add it'.format(original_name))
            return None

    @classmethod
    def load_variables(cls):
        """
        Loads the cmor_table.csv and creates the variables dictionary
        """
        Variable._dict_variables = dict()
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'cmor_table.csv'), 'rb') as csvfile:
            reader = csv.reader(csvfile, dialect='excel')
            for line in reader:
                if line[0] == 'Variable':
                    continue

                var = Variable(line)
                if not var.short_name:
                    continue
                for old_name in line[0].split(':'):
                    Variable._dict_variables[old_name.lower()] = var
                Variable._dict_variables[var.short_name.lower()] = var
    @staticmethod
    def parse(domain_name):
        if isinstance(domain_name, Domain):
            return domain_name
        return Domain(domain_name)

    def __init__(self, domain_name):
        domain_name = domain_name.lower()
        if domain_name == 'seaice':
            self.name = 'seaIce'
        elif domain_name == 'landice':
            self.name = 'landIce'
        elif domain_name in ['ocean', 'atmos', 'land']:
            self.name = domain_name
        else:
            raise ValueError('Domain {0} not recognized!'.format(domain_name))

    def __eq__(self, other):
        return other.__class__ == Domain and self.name == other.name

    def __str__(self):
        return self.name

    def get_table_name(self, frequency):
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
        """
        Returns the table name for a domain-frequency pair
        :param frequency: variable's frequency
        :type frequency: str
        :return: variable's table name
        :rtype: str
        """
        if frequency in ('mon', 'clim'):
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
            else:
                prefix = self.name[0].upper()
            table_name = prefix + frequency
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
        elif frequency == '6hr':
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
        else:
            table_name = 'day'
        return table_name


class Domains(object):
    seaIce = Domain('seaice')
    ocean = Domain('ocean')
    landIce = Domain('landIce')
Javier Vegas-Regidor's avatar
Javier Vegas-Regidor committed
    atmos = Domain('atmos')

class VarType(object):
    MEAN = 1
    STATISTIC = 2

    @staticmethod
    def to_str(vartype):
        if vartype == VarType.MEAN:
            return 'mean'
        elif vartype == VarType.STATISTIC:
        else:
            raise ValueError('Variable type {0} not supported'.format(vartype))