changed Object<->Dictionary functions and added dictToRecArray

This commit is contained in:
marco cammarata 2016-11-23 10:41:29 +01:00
parent 9e24059104
commit 4c6418d794
1 changed files with 30 additions and 4 deletions

View File

@ -733,9 +733,19 @@ def loadRecArray(fname,hasVectorHeader=True,asObj=False):
ret = np.core.records.fromarrays(a.transpose(),names=",".join(names))
return ret
def dictToRecArray(mydict):
shapes = np.asarray([v.shape[0] for v in mydict.values()] )
assert np.all( shapes==shapes[0] )
names = list(mydict.keys())
formats = [ mydict[p].dtype for p in names ]
arr = np.empty(shapes[0], dtype={'names':names, 'formats':formats})
for n in names: arr[n] = mydict[n]
return arr
def prepareRecArrayFromDict( mydict,n=1,leaveEmpty=True ):
names = mydict.keys()
names = list(mydict.keys())
formats = [ type(mydict[p]) for p in names ]
if leaveEmpty:
array_kind = np.empty
@ -1178,6 +1188,14 @@ def insertInSortedArray(a,v):
### Objects ###
def objToDict(o):
""" convert a dropObject to a dictionary (useful for saving); it should work for other objects too """
if isinstance(o,dict): return o
d = dict()
for k in o.__dict__.keys(): d[k] = getattr(o,k)
return d
class dropObject(object):
pass
@ -1200,11 +1218,16 @@ class dropObject(object):
k.sort()
return k
def asdict(self):
""" return a dictionary representation (useful for saving) """
return objToDict(self)
def __repr__(self):
return self.__str__()
def dict2class(d,recursive=True,cleanNames=True):
def dictToObj(d,recursive=True,cleanNames=True):
"""Return a class that has same attributes/values and
dictionaries key/value
"""
@ -1220,7 +1243,7 @@ def dict2class(d,recursive=True,cleanNames=True):
except:
pass
if recursive and isinstance(d[elem],dict):
c.__dict__[key] = dict2class(d[elem])
c.__dict__[key] = dictToObj(d[elem])
else:
c.__dict__[key] = d[elem]
return c
@ -1241,6 +1264,9 @@ def Hdf5ToObj(h5):
ret._add(name,h5hande[h])
return ret
def dict2obj(d,recursive=True,cleanNames=True):
print("DEPRECATED: use dictToObj")
return dictToObj(d,recursive=recursive,cleanNames=cleanNames)
def fac(n):
import math
@ -1273,7 +1299,7 @@ def define_colors(fname="colorbrewer_all_schemes.json"):
ff = open(fname,"r")
f = json.load( ff )
ff.close()
colors = dict2class(f)
colors = dictToObj(f)
for t1 in colors.keys():
for seq in colors[t1].keys():
for nc in colors[t1][seq].keys():