Coverage for src/lccalib/ntuple.py: 0%
38 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-23 12:30 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-23 12:30 +0000
1"""
2Tools to read SNLS catalogs, extracted from croaks.NTuple
3"""
5import numpy as np
8def read_header(fh):
9 """ Return keys, values from file header.
10 """
11 keys = {}
12 names = []
13 for line in fh:
14 if line.startswith("#"):
15 if line[1:].strip() == "end":
16 break
17 names.append(line[1:].split(":")[0].strip())
18 elif line.startswith("@"):
19 l = line[1:].split()
20 keys[l[0]] = convert(" ".join(l[1:]))
21 return keys, names
24def convert(value):
25 """ Convert into python type.
26 """
27 value = value.strip()
28 if not value:
29 value = "nan"
30 try:
31 value = int(value)
32 except ValueError:
33 try:
34 value = float(value)
35 except ValueError:
36 pass
37 return value
40def fromtxt(filename):
41 """Return catalog as recarray."""
42 #pylint: disable=unspecified-encoding
43 comments = set(["#", "\n"])
44 with open(filename, "r") as fid:
45 keys, names = read_header(fid)
46 records = []
47 for line in fid:
48 if line[0] in comments:
49 continue
50 vals = line.split()
51 records.append([convert(v) for v in vals])
52 nt = np.rec.fromrecords(records, names=names) # .view(NTuple)
53 nt.keys = keys
54 return nt