Coverage for /usr/local/lib/python3.9/site-packages/lccalib/ntuple.py: 0%

1"""

2 Tools to read SNLS catalogs, extracted from croaks.NTuple

3"""

4

5 import numpy as np

6

7

8 def 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

22

23

24 def 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

38

39

40 def 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