# coding=utf-8
"""Set attributtes in netCDF files"""
from earthdiagnostics.general.fix_file import FixFile
from earthdiagnostics.utils import Utils
from earthdiagnostics.diagnostic import DiagnosticDomainOption, DiagnosticVariableOption, DiagnosticOption, \
DiagnosticComplexStrOption
[docs]class Attribute(FixFile):
"""
Set the value of an attribute
Can be useful to correct wrong metadata
:original author: Javier Vegas-Regidor<javier.vegas@bsc.es>
:created: July 2016
:param data_manager: data management object
:type data_manager: DataManager
:param startdate: startdate
:type startdate: str
:param member: member number
:type member: int
:param chunk: chunk's number
:type chunk: int
:param variable: variable's name
:type variable: str
:param domain: variable's domain
:type domain: ModelingRealm
"""
alias = 'att'
"Diagnostic alias for the configuration file"
def __init__(self, data_manager, startdate, member, chunk, domain, variable, grid,
attributte_name, attributte_value):
FixFile.__init__(self, data_manager, startdate, member, chunk, domain, variable, grid)
self.attributte_name = attributte_name
self.attributte_value = attributte_value
def __str__(self):
return 'Write attributte output Startdate: {0.startdate} Member: {0.member} Chunk: {0.chunk} ' \
'Variable: {0.domain}:{0.variable} Attributte: {0.attributte_name}:{0.attributte_value} ' \
'Grid: {0.grid}'.format(self)
def __eq__(self, other):
if self._different_type(other):
return False
return self.startdate == other.startdate and self.member == other.member and self.chunk == other.chunk and \
self.domain == other.domain and self.variable == other.variable and self.grid == other.grid and \
self.attributte_name == other.attributte_name and self.attributte_value == other.attributte_value
[docs] @classmethod
def generate_jobs(cls, diags, options):
"""
Create a job for each chunk to compute the diagnostic
:param diags: Diagnostics manager class
:type diags: Diags
:param options: variable, domain, grid
:type options: list[str]
:return:
"""
options_available = (DiagnosticDomainOption(),
DiagnosticVariableOption(diags.data_manager.config.var_manager),
DiagnosticOption('name'),
DiagnosticComplexStrOption('value'),
DiagnosticOption('grid', ''))
options = cls.process_options(options, options_available)
job_list = list()
for startdate, member, chunk in diags.config.experiment.get_chunk_list():
job_list.append(Attribute(diags.data_manager, startdate, member, chunk,
options['domain'], options['variable'], options['grid'], options['name'],
options['value']))
return job_list
[docs] def compute(self):
"""Run the diagnostic"""
variable_file = self.variable_file.local_file
handler = Utils.open_cdf(variable_file)
handler.setncattr(self.attributte_name, self.attributte_value)
handler.close()
if not Utils.check_netcdf_file(variable_file):
raise Exception('Attribute {0} can not be set correctly to {1}'.format(self.attributte_name,
self.attributte_value))
self.corrected.set_local_file(variable_file, self)