| 1 |
""" |
| 2 |
A grammar wrapping spacepy to parse files in the Common Data Format (CDF), |
| 3 |
http://cdf.gsfc.nasa.gov. |
| 4 |
""" |
| 5 |
|
| 6 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 7 |
#c |
| 8 |
#c This program is free software, covered by the GNU GPL. See the |
| 9 |
#c COPYING file in the source distribution. |
| 10 |
|
| 11 |
|
| 12 |
from gavo import base |
| 13 |
from gavo.grammars.common import Grammar, RowIterator, MapKeys |
| 14 |
|
| 15 |
|
| 16 |
class CDFHeaderIterator(RowIterator): |
| 17 |
"""an iterator for headers of CDF files. |
| 18 |
""" |
| 19 |
def _iterRows(self): |
| 20 |
try: |
| 21 |
from spacepy import pycdf |
| 22 |
except ImportError: |
| 23 |
raise base.ui.logOldExc( |
| 24 |
base.ReportableError("cdfHeaderGrammar needs the external" |
| 25 |
" spacepy package. You can obtain it from" |
| 26 |
" http://spacepy.lanl.gov.")) |
| 27 |
|
| 28 |
cdfStruct = pycdf.CDF(self.sourceToken) |
| 29 |
|
| 30 |
res = {} |
| 31 |
for key, value in cdfStruct.attrs.items(): |
| 32 |
if self.grammar.autoAtomize and value.max_idx()==0: |
| 33 |
res[key] = value[0] |
| 34 |
else: |
| 35 |
res[key] = value[:] |
| 36 |
yield res |
| 37 |
|
| 38 |
|
| 39 |
class CDFHeaderGrammar(Grammar): |
| 40 |
"""A grammar that returns the header dictionary of a CDF file |
| 41 |
(global attributes). |
| 42 |
|
| 43 |
This grammar yields a single dictionary per file, which corresponds |
| 44 |
to the global attributes. The values in this dictionary may have |
| 45 |
complex structure; in particular, sequences are returned as lists. |
| 46 |
|
| 47 |
To use this grammar, additional software is required that (by 2014) |
| 48 |
is not packaged for Debian. See |
| 49 |
https://pythonhosted.org/SpacePy/install.html |
| 50 |
for installation |
| 51 |
instructions. Note that you must install the CDF library itself as |
| 52 |
described further down on that page; the default installation |
| 53 |
instructions do not install the library in a public place, so if |
| 54 |
you use these, you'll have to set CDF_LIB to the right value, too, |
| 55 |
before running dachs imp. |
| 56 |
""" |
| 57 |
name_ = "cdfHeaderGrammar" |
| 58 |
|
| 59 |
_mapKeys = base.StructAttribute("mapKeys", childFactory=MapKeys, |
| 60 |
default=None, copyable=True, description="Prescription for how to" |
| 61 |
" map labels keys to grammar dictionary keys") |
| 62 |
_autoAtomize = base.BooleanAttribute("autoAtomize", |
| 63 |
default=False, copyable=True, description="Unpack 1-element" |
| 64 |
" lists to their first value.") |
| 65 |
|
| 66 |
|
| 67 |
rowIterator = CDFHeaderIterator |
| 68 |
|
| 69 |
def onElementComplete(self): |
| 70 |
if self.mapKeys is None: |
| 71 |
self.mapKeys = base.makeStruct(MapKeys) |
| 72 |
super().onElementComplete() |