#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
LFA:
Contains the class to handle LFA format.
"""
__all__ = ['LFA']
import os
import numpy
from footprints import FPDict
import epygram
from epygram import epygramError, config, util
from epygram import arpifs4py
from epygram.base import Resource
from epygram.fields import MiscField
[docs]class LFA(Resource):
"""Class implementing all specificities for LFA resource format."""
_footprint = dict(
attr=dict(
format=dict(
values=set(['LFA']),
default='LFA')
)
)
def __init__(self, *args, **kwargs):
"""
Constructor. See its footprint for arguments.
"""
self.isopen = False
super(LFA, self).__init__(*args, **kwargs)
if not self.fmtdelayedopen:
self.open()
[docs] def open(self, openmode=None):
"""
Opens the LFA in Fortran sense.
- *openmode*: optional, to open with a specific openmode, eventually
different from the one specified at initialization.
"""
super(LFA, self).open(openmode=openmode)
if self.openmode in ('r', 'a'):
# open, getting logical unit
if self.openmode == 'r':
self._unit = arpifs4py.wlfaouv(self.container.abspath, 'R')
elif self.openmode == 'a':
self._unit = arpifs4py.wlfaouv(self.container.abspath, 'A')
self.isopen = True
self.empty = False
elif self.openmode == 'w':
# open
self._unit = arpifs4py.wlfaouv(self.container.abspath, 'W')
self.isopen = True
self.empty = True
[docs] def close(self):
"""Closes a LFA properly."""
if self.isopen:
try:
arpifs4py.wlfafer(self._unit)
except Exception:
raise IOError("closing " + self.container.abspath)
self.isopen = False
# Cleanings
if self.openmode == 'w' and self.empty:
os.remove(self.container.abspath)
################
# ABOUT FIELDS #
################
[docs] def find_fields_in_resource(self, seed=None):
"""
Returns a list of the fields from resource whose name match the given
*seed*.
- *seed*: might be a regular expression, a list of regular expressions
or *None*. If *None* (default), returns the list of all fields in
resource.
"""
if seed == None:
fieldslist = self.listfields()
elif isinstance(seed, str):
fieldslist = util.find_re_in_list(seed, self.listfields())
elif isinstance(seed, list):
fieldslist = []
for s in seed:
fieldslist += util.find_re_in_list(s, self.listfields())
if fieldslist == []:
raise epygramError("no field matching '" + seed + \
"' was found in resource " + \
self.container.abspath)
return fieldslist
@Resource._openbeforedelayed
[docs] def readfield(self, fieldname, getdata=True):
"""Reads a field in resource."""
field = MiscField(fid=FPDict({'LFA':fieldname}))
if getdata:
(fieldtype, fieldlength) = arpifs4py.wlfacas(self._unit, fieldname)
if fieldtype[0] == 'R':
(data, fieldlength) = arpifs4py.wlfalecr(self._unit, fieldname,
fieldlength)
elif fieldtype[0] == 'I':
(data, fieldlength) = arpifs4py.wlfaleci(self._unit, fieldname,
fieldlength)
elif fieldtype[0] == 'C':
(data, fieldlength) = arpifs4py.wlfalecc(self._unit, fieldname,
fieldlength,
config.LFA_maxstrlen)
data = [data[i].strip() for i in range(fieldlength)]
field.setdata(numpy.array(data))
return field
@Resource._openbeforedelayed
[docs] def writefield(self, field):
"""Writes a Field in resource."""
#TOBECHECKED: writing not tested
raise epygramError("writefield routine has not been tested...\
If you need to, you might face problems...")
if not isinstance(field, epygram.base.Field):
raise epygramError("'field' argument has to be a\
epygram.base.Field.")
data = numpy.array(field.data)
if len(data.shape) != 1:
raise epygramError("LFA can only hold 1D arrays.")
if data.dtype[0:5] == 'float':
arpifs4py.wlfaecrr(self._unit, field.fid['LFA'], data)
elif data.dtype[0:3] == 'int':
arpifs4py.wlfaecri(self._unit, field.fid['LFA'], data)
elif data.dtype[0:3] == 'str':
arpifs4py.wlfaecrc(self._unit, field.fid['LFA'], data)
else:
raise epygramError("LFA can only hold float, int or str arrays.")
[docs] def listfields(self):
"""
Returns a list containing the LFA identifiers of all the fields of
the resource.
"""
return super(LFA, self).listfields()
@Resource._openbeforedelayed
def _listfields(self):
"""
Returns a list containing the names of the fields in LFA.
"""
(list_length, fieldslist) = arpifs4py.wlfalaft(self._unit, config.LFA_max_num_fields, config.LFA_maxstrlen)
fieldslist = [fieldslist[i].strip() for i in range(list_length)]
return fieldslist