persist.py
Go to the documentation of this file.
1 import json
2 import numpy
3 
4 from schema import FieldResponse, PlaneResponse, PathResponse
5 
6 
7 def todict(obj):
8  '''
9  Return a dictionary for the object which is marked up for type.
10  '''
11  for typename in ['FieldResponse', 'PlaneResponse', 'PathResponse']:
12  if typename == type(obj).__name__:
13  cname = obj.__class__.__name__
14  return {cname: {k: todict(v) for k, v in obj._asdict().items()}}
15  if isinstance(obj, numpy.ndarray):
16  shape = list(obj.shape)
17  elements = obj.flatten().tolist()
18  return dict(array=dict(shape=shape, elements=elements))
19  if isinstance(obj, list):
20  return [todict(ele) for ele in obj]
21 
22  return obj
23 
24 
25 def fromdict(obj):
26  '''
27  Undo `todict()`.
28  '''
29  if isinstance(obj, dict):
30 
31  if 'array' in obj:
32  ret = numpy.asarray(obj['array']['elements'])
33  return ret.reshape(obj['array']['shape'])
34 
35  for typ in [FieldResponse, PlaneResponse, PathResponse]:
36  tname = typ.__name__
37  if tname in obj:
38  return typ(**{k: fromdict(v) for k, v in obj[tname].items() if k not in ["pitchdir","wiredir"]})
39 
40  if isinstance(obj, list):
41  return [fromdict(ele) for ele in obj]
42 
43  return obj
44 
45 
46 def dumps(obj):
47  '''
48  Dump object to JSON text.
49  '''
50  return json.dumps(todict(obj), indent=2)
51 
52 
53 def loads(text):
54  '''
55  Load object from JSON text.
56  '''
57  return fromdict(json.loads(text))
58 
59 
60 def dump(filename, obj):
61  '''
62  Save a response object (typically response.schema.FieldResponse)
63  to a file of the given name.
64  '''
65  text = dumps(obj)
66  if filename.endswith(".json"):
67  open(filename, 'w').write(text)
68  return
69  if filename.endswith(".json.bz2"):
70  import bz2
71  bz2.BZ2File(filename, 'w').write(text)
72  return
73  if filename.endswith(".json.gz"):
74  import gzip
75  gzip.open(filename, "wb").write(text)
76  return
77  raise ValueError("unknown file format: %s" % filename)
78 
79 
80 def load(filename):
81  '''
82  Return response.schema object representation of the data in the
83  file of the given name.
84  '''
85  if filename.endswith(".json"):
86  return loads(open(filename, 'r').read())
87 
88  if filename.endswith(".json.bz2"):
89  import bz2
90  return loads(bz2.BZ2File(filename, 'r').read())
91 
92  if filename.endswith(".json.gz"):
93  import gzip
94  return loads(gzip.open(filename, "rb").read())
95 
96  raise ValueError("unknown file format: %s" % filename)
int open(const char *, int)
Opens a file descriptor.
def dump(filename, obj)
Definition: persist.py:60
int read(int, char *, size_t)
Read bytes from a file descriptor.
def write(rflist, outputfile="wire-cell-garfield-response.json.bz2")
Definition: __init__.py:681