Newer
Older
from tkinter.tix import Form
from enum import Enum, IntEnum
class Formats(IntEnum):
'''File Format Indicators (FFI)
'''
FFI_1001 = 1001
FFI_2110 = 2110
# FFI_2310 = 2310
class VariableType(Enum):
IVAR = 1
IBVAR = 2
DVAR = 3
class KeywordComment():
def __init__(self, key, na_allowed):
self.key = key
self.na_allowed = na_allowed
self.data = []
def append(self, data):
self.data.append(data)
def __str__(self):
d = "\n".join(self.data) if not self.data is [] else "N/A"
return self.key + ": " + d
@property
def nlines(self):
# "+ 1" -> shortnames line, and keywords might be multiline...
return len(self.freeform) + 1 + sum([ len(k.data) for k in self.keywords.values() ])
return self.freeform + [ str(s) for s in self.keywords.values() ] + [ self.shortnames ]
def ingest(self, raw):
# last line is always shortname
self.shortnames = raw.pop()
# per standard: The free-form text section consists of the lines
# between the beginning of the normal comments section
# and the first required keyword. [...] The required “KEYWORD: value” pairs block
# starts with the line that begins with the first required keyword
# and must include all required “KEYWORD: value” pairs
# in the order listed in the ICARTT documentation.
current_keyword = None
# import pdb; pdb.set_trace()
if possible_keyword in self.keywords or re.match("R[a-zA-Z0-9]{1,2}[ ]*", possible_keyword):
current_keyword = possible_keyword
if not current_keyword in self.keywords: # for the revisions only...
self.keywords[current_keyword] = KeywordComment(current_keyword, False)
if current_keyword is None:
self.keywords[current_keyword].append( l.replace(l.split(":")[0] + ":", "").strip() )
for key in self.keywords:
if self.keywords[key].data == []:
warnings.warn("Normal comments: required keyword {:s} is missing.".format(key))
required_keywords = (
"PI_CONTACT_INFO",
"PLATFORM",
"LOCATION",
"ASSOCIATED_DATA",
"INSTRUMENT_INFO",
"DATA_INFO",
"UNCERTAINTY",
"ULOD_FLAG",
"ULOD_VALUE",
"LLOD_FLAG",
"LLOD_VALUE",
"DM_CONTACT_INFO",
"PROJECT_INFO",
"STIPULATIONS_ON_USE",
"OTHER_COMMENTS",
"REVISION"
)
self.keywords = { k: KeywordComment(k, True) for k in required_keywords }
self.keywords["UNCERTAINTY"].na_allowed = False
self.keywords["REVISION"].na_allowed = False
'''An ICARTT variable description with name, units, scale and missing value.
:param shortname: Short name of the variable
:type shortname: str
:param units: Units of the variable
:type units: str
:param standardname: Standard name of the variable
:type standardname: str
:param longname: Long name of the variable
:type longname: str
:param vartype: Variable type (unbounded/bounded independent or dependent)
:type vartype: enum:`icartt.Formats`, defaults to VariableType.DVAR
:param scale: Scaling factor for the variable
:type scale: float, defaults to 1.0
:param miss: Missing value for the variable
:type miss: float, defaults to -99999.0
:param splitChar: Split character for text representation
:type splitChar: str, defaults to ","
def desc(self, splitChar=","):
'''Variable description string as it appears in an ICARTT file
:return: description string
:rtype: str
descstr = [ str(self.shortname), str(self.units) ]
if not self.standardname is None:
descstr += [ str(self.standardname) ]
if not self.longname is None:
descstr += [ str(self.longname) ]
return splitChar.join(descstr)
'''Append data to a variable. Depending on type (independent, dependent variable),
all identifying (bounded and unbounded) independent variables need to be given.
:param ivar: value of the independent (unbounded) variable
:type ivar: float
:param ibvar: value of the independent (bounded) variable
:type ibvar: float, optional
:param dvar: value of the dependent variable
:type dvar: float, optional
def sanitized(z): return float(z) if not float(z) == float(self.miss) else float('NaN')
v = [sanitized(y) for y in argv]
x = (tuple([y for y in v[:-1]]), v[-1])
x = (v[0])
self.data.append(x)
def is_valid_variablename(self, name):
# ICARTT Standard v2 2.1.1 2)
# Variable short names and variable standard names:
# Uppercase and lowercase ASCII alphanumeric characters
# and underscores.
def is_ascii_alpha_or_underscore(x):
return re.match("[a-zA-Z0-9_]", x)
all_are_alpha_or_underscore = all( [ is_ascii_alpha_or_underscore(x) for x in name ] )
# The first character must be a letter,
first_is_alpha = bool( re.match("[a-zA-Z]", name[0]) )
# and the name can be at most 31 characters in length.
less_than_31_chars = len(name) <= 31
return (all_are_alpha_or_underscore and first_is_alpha and less_than_31_chars)
def __init__(self, shortname, units, standardname, longname, vartype=VariableType.DVAR, scale=1.0, miss=-99999.0, splitChar=","):
if not self.is_valid_variablename(shortname):
warnings.warn("Variable short name {:s} does not comply with ICARTT standard v2".format(shortname))
self.shortname = shortname
self.units = units
self.standardname = standardname
self.longname = longname
self.vartype = vartype
self.scale = scale
self.miss = miss
self.data = []
'''An ICARTT dataset that can be created from scratch or read from a file,
:param f: file path or file handle to use
:type f: str or file handle or stream object, defaults to None
:param loadData: load data as well (or only header if False)?
:type loadData: bool, defaults to "True"
:param splitChar: splitting character used to separate fields in a line
:type splitChar: str, defaults to ","
'''Header line count
:return: line count
:rtype: int
if self.format == Formats.FFI_1001:
total = 14 + len(self.DVARS) + len(self.SCOM) + self.NCOM.nlines
if self.format == Formats.FFI_2110:
total = 16 + 2 + len(self.AUXVARS) + len(self.DVARS) +\
len(self.SCOM) + self.NCOM.nlines
'''Names of variables (independent and dependent)
:return: list of variable names
:rtype: list
return [x for x in self.VARS.keys()]
'''Time steps of the data
:return: list of time steps
:rtype: list
return [self.dateValid + datetime.timedelta(seconds=x) for x in self.IVAR]
@property
def VARS(self):
'''Variables (independent + dependent + auxiliary)
:return: dictionary of all variables
:rtype: dict of Variable(s)
'''
vars = {self.IVAR.name: self.IVAR, **self.DVARS}
if self.format == Formats.FFI_2110:
vars = {self.IBVAR.name: self.IBVAR, **vars, **self.AUXVARS}
'''Shortcut to enable access to variable data by name
:return: variable data
:rtype: list
'''Write header
:param f: handle to write to
:type f: file handle or StringIO stream, defaults to sys.stdout
def prnt(txt):
f.write(str(txt) + "\n")
# Number of lines in header, file format index (most files use 1001) - comma delimited.
versInfo = [ self.nheader, self.format.value ]
versInfo.append( self.version )
txt = self.splitChar.join( [ str(x) for x in versInfo ] )
# PI last name, first name/initial.
prnt(self.PI)
# Organization/affiliation of PI.
prnt(self.organization)
# Data source description (e.g., instrument name, platform name, model name, etc.).
prnt(self.dataSource)
# Mission name (usually the mission acronym).
prnt(self.mission)
# File volume number, number of file volumes (these integer values are used when the data require more than one file per day; for data that require only one file these values are set to 1, 1) - comma delimited.
prnt(self.splitChar.join([str(self.volume), str(self.nvolumes)]))
# UTC date when data begin, UTC date of data reduction or revision - comma delimited (yyyy, mm, dd, yyyy, mm, dd).
prnt(self.splitChar.join([datetime.datetime.strftime(x, self.splitChar.join(
["%Y", "%m", "%d"])) for x in [self.dateValid, self.dateRevised]]))
# Data Interval (This value describes the time spacing (in seconds) between consecutive data records. It is the (constant) interval between values of the independent variable. For 1 Hz data the data interval value is 1 and for 10 Hz data the value is 0.1. All intervals longer than 1 second must be reported as Start and Stop times, and the Data Interval value is set to 0. The Mid-point time is required when it is not at the average of Start and Stop times. For additional information see Section 2.5 below.).
prnt(self.splitChar.join( [ str(x) for x in self.dataInterval ] ) )
if self.format == Formats.FFI_2110:
# Description or name of independent (bound) variable (This is the name chosen for the start time. It always refers to the number of seconds UTC from the start of the day on which measurements began. It should be noted here that the independent variable should monotonically increase even when crossing over to a second day.).
prnt(self.IBVAR.desc(self.splitChar))
# Description or name of independent variable (This is the name chosen for the start time. It always refers to the number of seconds UTC from the start of the day on which measurements began. It should be noted here that the independent variable should monotonically increase even when crossing over to a second day.).
prnt(self.IVAR.desc(self.splitChar))
# Number of variables (Integer value showing the number of dependent variables: the total number of columns of data is this value plus one.).
# Scale factors (1 for most cases, except where grossly inconvenient) - comma delimited.
prnt(self.splitChar.join(
["{:.1g}".format(DVAR.scale) for DVAR in self.DVARS.values()]))
# Missing data indicators (This is -9999 (or -99999, etc.) for any missing data condition, except for the main time (independent) variable which is never missing) - comma delimited.
prnt(self.splitChar.join([str(DVAR.miss)
for DVAR in self.DVARS.values()]))
# Variable names and units (Short variable name and units are required, and optional long descriptive name, in that order, and separated by commas. If the variable is unitless, enter the keyword "none" for its units. Each short variable name and units (and optional long name) are entered on one line. The short variable name must correspond exactly to the name used for that variable as a column header, i.e., the last header line prior to start of data.).
nul = [prnt(DVAR.desc(self.splitChar)) for DVAR in self.DVARS.values()]
if self.format == Formats.FFI_2110:
# Number of variables (Integer value showing the number of dependent variables: the total number of columns of data is this value plus one.).
# Scale factors (1 for most cases, except where grossly inconvenient) - comma delimited.
prnt(self.splitChar.join(
["{:.1g}".format(AUXVAR.scale) for AUXVAR in self.AUXVARS.values()]))
# Missing data indicators (This is -9999 (or -99999, etc.) for any missing data condition, except for the main time (independent) variable which is never missing) - comma delimited.
prnt(self.splitChar.join([str(AUXVAR.miss)
for AUXVAR in self.AUXVARS.values()]))
# Variable names and units (Short variable name and units are required, and optional long descriptive name, in that order, and separated by commas. If the variable is unitless, enter the keyword "none" for its units. Each short variable name and units (and optional long name) are entered on one line. The short variable name must correspond exactly to the name used for that variable as a column header, i.e., the last header line prior to start of data.).
nul = [prnt(AUXVAR.desc(self.splitChar)) for AUXVAR in self.AUXVARS.values()]
# Number of SPECIAL comment lines (Integer value indicating the number of lines of special comments, NOT including this line.).
# Special comments (Notes of problems or special circumstances unique to this file. An example would be comments/problems associated with a particular flight.).
nul = [prnt(x) for x in self.SCOM]
# Number of Normal comments (i.e., number of additional lines of SUPPORTING information: Integer value indicating the number of lines of additional information, NOT including this line.).
# Normal comments (SUPPORTING information: This is the place for investigators to more completely describe the data and measurement parameters. The supporting information structure is described below as a list of key word: value pairs. Specifically include here information on the platform used, the geo-location of data, measurement technique, and data revision comments. Note the non-optional information regarding uncertainty, the upper limit of detection (ULOD) and the lower limit of detection (LLOD) for each measured variable. The ULOD and LLOD are the values, in the same units as the measurements that correspond to the flags -7777s and -8888s within the data, respectively. The last line of this section should contain all the short variable names on one line. The key words in this section are written in BOLD below and must appear in this section of the header along with the relevant data listed after the colon. For key words where information is not needed or applicable, simply enter N/A.).
nul = [prnt(x) for x in self.NCOM]
def _write_data_1001(self, prnt=lambda x: sys.stdout.write(x)):
def p(val, var):
return var.miss if math.isnan(val) else val
for i in range(len(self.IVAR)):
prnt([p(self.IVAR[i], self.IVAR)] + [p(DVAR[i][1], DVAR)
for DVAR in self.DVARS.values()])
def _write_data_2110(self, prnt=lambda x: sys.stdout.write(x)):
def p(val, var):
return var.miss if math.isnan(val) else val
for ival in self.IVAR:
prnt([p(ival, self.IVAR)] + [p(auxval[1], AUXVAR)
for AUXVAR in self.AUXVARS.values() for auxval in AUXVAR if auxval[0] == ival])
for ibval in [b[1] for b in self.IBVAR if b[0] == ival]:
prnt([p(ibval, self.IBVAR)] + [p(dval[1], DVAR) for DVAR in self.DVARS.values()
for dval in DVAR if (dval[0][0] == ival) and (dval[0][1] == ibval)])
'''Write data
:param f: handle to write to
:type f: file handle or StringIO stream, defaults to sys.stdout
f.write(str(self.splitChar.join([str(x) for x in vars])) + "\n")
if self.format == Formats.FFI_1001:
elif self.format == Formats.FFI_2110:
warnings.warn("Unknown file format {:d}".format(self.format))
'''Write header and data
:param f: handle to write to
:type f: file handle or StringIO stream, defaults to sys.stdout
'''Create ICARTT-compliant file name based on the information contained in the dataset
:param date_format: date format to use when parsing
:type date_format: str, defaults to '%Y%m%d'
:return: file name generated
:rtype: string
fn = self.dataID + "_" + self.locationID + "_" + \
datetime.datetime.strftime(self.dateValid, date_format)
fn += "_R" + str(self.revision) if not self.revision is None else ""
fn += "_L" + str(self.launch) if not self.launch is None else ""
fn += "_V" + str(self.volume) if self.nvolumes > 1 else ""
def is_valid_filename(self, name):
# ICARTT standard v2 2.1.1 3)
# Filename: Uppercase and lowercase ASCII alphanumeric
# characters (i.e. A-Z, a-z, 0-9), underscore, period,
# and hyphen. File names can be a maximum 127
# characters in length.
def is_ascii_alpha(x):
return re.match("[a-zA-Z0-9-_.]", x)
all_ascii_alpha = all( [ is_ascii_alpha(x) for x in name ] )
less_than_128_characters = len(name) < 128
return all_ascii_alpha and less_than_128_characters
class Filehandle_with_linecounter:
def __init__(self, f, splitChar):
self.f = f
self.line = 0
dmp = self.f.readline().replace('\n', '').replace('\r', '')
dmp = [word.strip(' ')
for word in dmp.split(self.splitChar)]
if self.input_fhandle.closed:
self.input_fhandle = open(self.input_fhandle.name)
try:
f = Filehandle_with_linecounter(self.input_fhandle, self.splitChar)
self._read_header(f)
del f
except:
a = 1
finally:
self.input_fhandle.close()
def _read_header(self, f):
# line 1 - Number of lines in header, file format index (most files use
# 1001) - comma delimited.
try:
self.format = Formats(int(dmp[1]))
except:
raise ValueError(
"ICARTT format {:d} not implemented".format( dmp[1] ))
# line 4 - Data source description (e.g., instrument name, platform name,
# model name, etc.).
# line 6 - File volume number, number of file volumes (these integer values
# are used when the data require more than one file per day; for data that
# require only one file these values are set to 1, 1) - comma delimited.
self.volume = int(dmp[0])
# line 7 - UTC date when data begin, UTC date of data reduction or revision
# - comma delimited (yyyy, mm, dd, yyyy, mm, dd).
self.dateValid = datetime.datetime.strptime(
"".join(["{:s}".format(x) for x in dmp[0:3]]), '%Y%m%d')
self.dateRevised = datetime.datetime.strptime(
"".join(["{:s}".format(x) for x in dmp[3:6]]), '%Y%m%d')
# line 8 - Data Interval (This value describes the time spacing (in seconds)
# between consecutive data records. It is the (constant) interval between
# values of the independent variable. For 1 Hz data the data interval value
# is 1 and for 10 Hz data the value is 0.1. All intervals longer than 1
# second must be reported as Start and Stop times, and the Data Interval
# value is set to 0. The Mid-point time is required when it is not at the
# average of Start and Stop times. For additional information see Section
# 2.5 below.).
dmp = f.readline()
# might have multiple entries for 2110
self.dataInterval = [ float(x) for x in dmp ]
# line 9 - Description or name of independent variable (This is the name
# chosen for the start time. It always refers to the number of seconds UTC
# from the start of the day on which measurements began. It should be noted
# here that the independent variable should monotonically increase even when
# crossing over to a second day.
def extract_vardesc(dmp):
shortname = dmp[0]
units = dmp[1]
standardname = dmp[2] if len(dmp) > 2 else None
longname = dmp[3] if len(dmp) > 3 else None
return shortname, units, standardname, longname
if self.format == Formats.FFI_2110:
shortname, units, standardname, longname = extract_vardesc(dmp)
self.IBVAR = Variable(shortname, units, standardname, longname,
splitChar=self.splitChar)
shortname, units, standardname, longname = extract_vardesc(dmp)
self.IVAR = Variable(shortname, units, standardname, longname,
splitChar=self.splitChar)
# line 10 - Number of variables (Integer value showing the number of
# dependent variables: the total number of columns of data is this value
# plus one.).
# line 11- Scale factors (1 for most cases, except where grossly
# inconvenient) - comma delimited.
vscale = [float(x) for x in f.readline()]
# line 12 - Missing data indicators (This is -9999 (or -99999, etc.) for
# any missing data condition, except for the main time (independent)
# variable which is never missing) - comma delimited.
vmiss = [float(x) for x in f.readline()]
# no float casting here, as we need to do string comparison lateron when reading data...
# line 13 - Variable names and units (Short variable name and units are
# required, and optional long descriptive name, in that order, and separated
# by commas. If the variable is unitless, enter the keyword "none" for its
# units. Each short variable name and units (and optional long name) are
# entered on one line. The short variable name must correspond exactly to
# the name used for that variable as a column header, i.e., the last header
# line prior to start of data.).
dmp = f.readline()
shortname, units, standardname, longname = extract_vardesc(dmp)
vshortname = [ shortname ]
vunits = [ units ]
vstandardname = [ standardname ]
vlongname = [ longname ]
shortname, units, standardname, longname = extract_vardesc(dmp)
vshortname += [ shortname ]
vunits += [ units ]
vstandardname += [ standardname ]
vlongname += [ longname ]
return {shortname: Variable(shortname, unit, standardname, longname, scale=scale, miss=miss, splitChar=self.splitChar) for shortname, unit, standardname, longname, scale, miss in zip(vshortname, vunits, vstandardname, vlongname, vscale, vmiss)}
if self.format == Formats.FFI_2110:
# line 14 + nvar - Number of SPECIAL comment lines (Integer value
# indicating the number of lines of special comments, NOT including this
# line.).
# line 15 + nvar - Special comments (Notes of problems or special
# circumstances unique to this file. An example would be comments/problems
# associated with a particular flight.).
self.SCOM = [f.readline(do_split=False) for i in range(0, nscom)]
# line 16 + nvar + nscom - Number of Normal comments (i.e., number of
# additional lines of SUPPORTING information: Integer value indicating the
# number of lines of additional information, NOT including this line.).
# line 17 + nvar + nscom - Normal comments (SUPPORTING information: This is
# the place for investigators to more completely describe the data and
# measurement parameters. The supporting information structure is described
# below as a list of key word: value pairs. Specifically include here
# information on the platform used, the geo-location of data, measurement
# technique, and data revision comments. Note the non-optional information
# regarding uncertainty, the upper limit of detection (ULOD) and the lower
# limit of detection (LLOD) for each measured variable. The ULOD and LLOD
# are the values, in the same units as the measurements that correspond to
# the flags -7777's and -8888's within the data, respectively. The last line
# of this section should contain all the "short" variable names on one line.
# The key words in this section are written in BOLD below and must appear in
# this section of the header along with the relevant data listed after the
# colon. For key words where information is not needed or applicable, simply
# enter N/A.).
raw_ncom = [f.readline(do_split=False) for i in range(0, nncom)]
self.NCOM = StandardNormalComments(raw_ncom)
warnings.warn("Number of header lines suggested in line 1 ({:d}) do not match actual header lines read ({:d})".format(
nheader_suggested, self.nheader))
for cur in range(len(raw)):
self.IVAR.append(raw[cur][0])
nul = [self.DVARS[key].append(
raw[cur][0], raw[cur][i+1]) for i, key in enumerate(self.DVARS)]
cur = 0
num_var_name = list(self.AUXVARS.keys())[0]
while cur < len(raw):
self.IVAR.append(raw[cur][0])
nul = [self.AUXVARS[key].append(
raw[cur][0], raw[cur][i+1]) for i, key in enumerate(self.AUXVARS)]
nprimary = int(self.AUXVARS[num_var_name][-1][1])
for i in range(nprimary):
self.IBVAR.append(raw[cur][0], raw[cur+i+1][0])
nul = [self.DVARS[key].append(
raw[cur][0], raw[cur+i+1][0], raw[cur+i+1][j+1]) for j, key in enumerate(self.DVARS)]
if self.input_fhandle.closed:
self.input_fhandle = open(self.input_fhandle.name)
try:
nul = [self.input_fhandle.readline() for i in range(self.nheader_file)]
raw = [line.split(self.splitChar) for line in self.input_fhandle]
if self.format == Formats.FFI_1001:
nul = self._extract_items_1001(raw)
elif self.format == Formats.FFI_2110:
nul = self._extract_items_2110(raw)
else:
warnings.warn(
"Unknown file format: {:d}, could not read data.".format(self.format))
except:
a = 1
finally:
self.input_fhandle.close()
def __del__(self):
try:
if not self.input_fhandle.closed:
self.input_fhandle.close()
except:
pass
def __init__(self, f=None, loadData=True, splitChar=",", format=Formats.FFI_1001):
self.format = format
self.version = None
self.dataID = 'dataID'
self.locationID = 'locationID'
self.revision = 0
self.launch = None
self.volume = 1
self.nvolumes = 1
self.PI = 'Mustermann, Martin'
self.dataSource = 'Musterdatenprodukt'
self.mission = 'MUSTEREX'
self.dateValid = datetime.datetime.today()
self.dateRevised = datetime.datetime.today()
self.dataInterval = [ 0.0 ]
self.IVAR = Variable('Time_Start',
'seconds_from_0_hours_on_valid_date',
vartype=VariableType.IVAR,
scale=1.0, miss=-9999999, splitChar=splitChar)
self.IBVAR = None
self.AUXVARS = {}
self.DVARS = {
'Time_Stop':
Variable('Time_Stop',
'seconds_from_0_hours_on_valid_date',
scale=1.0, miss=-9999999, splitChar=splitChar),
'Some_Variable':
Variable('Some_Variable',
'ppbv',
scale=1.0, miss=-9999999, splitChar=splitChar)
}
self.SCOM = []
self.NCOM = []
self.splitChar = splitChar
# Standard v2.0 for normal comments requires all keywords present,
# might not be the case - then reading data will fail
self.nheader_file = -1
self.input_fhandle = open(f, 'r')
else:
self.input_fhandle = f
self.read_header()
if loadData:
self.read_data()