variable.py 2 KB
Newer Older
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.domain = line[4].strip()
        self.basin = Basins.parse(line[5])
        self.units = line[6].strip()
        self.valid_min = line[7].strip()
        self.valid_max = line[8].strip()

    @classmethod
    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
        :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