31
|
1
|
|
2 from CGData import CGObjectBase
|
|
3
|
|
4 import csv
|
|
5 import types
|
|
6
|
|
7 class TableRow(object):
|
|
8 def __init__(self):
|
|
9 pass
|
|
10
|
|
11 def __str__(self):
|
|
12 return "<" + ",".join( "%s=%s" % (col, getattr(self,col)) for col in self.__format__['columnOrder']) + ">"
|
|
13
|
|
14 class InvalidFormat(Exception):
|
|
15 def __init__(self, txt):
|
|
16 Exception.__init__(self, txt)
|
|
17
|
|
18 class BaseTable(CGObjectBase):
|
|
19 def __init__(self):
|
|
20 super(BaseTable,self).__init__()
|
|
21 self.__row_class__ = type( "TableRow_" + self['cgformat']['name'], (TableRow,), dict(__format__=self.__format__) )
|
|
22 self.free()
|
|
23
|
|
24 def free(self):
|
|
25 self.firstKey = None
|
|
26 self.secondKey = None
|
|
27 self.groupKey = None
|
|
28 self.loaded = False
|
|
29 if 'primaryKey' in self['cgformat']:
|
|
30 self.firstKey = self['cgformat']['primaryKey']
|
|
31 setattr(self, self['cgformat']['primaryKey'] + "_map", {} )
|
|
32 self.groupKey = False
|
|
33
|
|
34 #setup the map for groupKeys
|
|
35 if 'groupKey' in self['cgformat']:
|
|
36 self.firstKey = self['cgformat']['groupKey']
|
|
37 setattr(self, self['cgformat']['groupKey'] + "_map", {} )
|
|
38 self.groupKey = True
|
|
39
|
|
40 if 'secondaryKey' in self['cgformat']:
|
|
41 self.secondKey = self['cgformat']['secondaryKey']
|
|
42
|
|
43 def read(self, handle):
|
|
44 cols = self['cgformat']['columnOrder']
|
|
45 colType = {}
|
|
46 for col in cols:
|
|
47 if 'columnDef' in self['cgformat'] and col in self['cgformat']['columnDef'] and 'type' in self['cgformat']['columnDef'][col]:
|
|
48 if self['cgformat']['columnDef'][col]['type'] == 'float':
|
|
49 colType[col] = float
|
|
50 elif self['cgformat']['columnDef'][col]['type'] == 'int':
|
|
51 colType[col] = int
|
|
52 else:
|
|
53 colType[col] = str
|
|
54 else:
|
|
55 colType[col] = str
|
|
56
|
|
57 read = csv.reader(handle, delimiter="\t")
|
|
58
|
|
59 storeMap = getattr(self, self.firstKey + "_map")
|
|
60 comment = None
|
|
61 if 'comment' in self['cgformat']:
|
|
62 comment = self['cgformat']['comment']
|
|
63 linenum = 0
|
|
64 for row in read:
|
|
65 linenum += 1
|
52
|
66 if linenum ==1: #ignore header line
|
|
67 continue
|
31
|
68 r = self.__row_class__()
|
50
|
69 if (comment is None or not row[0].startswith(comment)) and not row[0].startswith("#"):
|
31
|
70 for i, col in enumerate(cols):
|
52
|
71 skip =0
|
31
|
72 isOptional = False
|
|
73 if 'columnDef' in self['cgformat'] and col in self['cgformat']['columnDef'] and 'optional' in self['cgformat']['columnDef'][col]:
|
|
74 isOptional = self['cgformat']['columnDef'][col]['optional']
|
|
75 if len(row) > i:
|
|
76 try:
|
|
77 setattr(r, col, colType[col](row[i]))
|
52
|
78 except ValueError:
|
31
|
79 raise ValueError( "col invalid type %s on line %d" % (row[i], linenum))
|
|
80 else:
|
|
81 if isOptional:
|
|
82 setattr(r, col, None)
|
|
83 else:
|
|
84 print row
|
52
|
85 skip =1 # ignore bad lines
|
|
86 break
|
31
|
87 raise InvalidFormat("missing colum " + col)
|
52
|
88 if skip:
|
|
89 continue
|
|
90
|
31
|
91 if not self.groupKey:
|
|
92 if self.secondKey is not None:
|
|
93 key1 = getattr(r, self.firstKey )
|
|
94 key2 = getattr(r, self.secondKey )
|
|
95 if key1 not in storeMap:
|
|
96 storeMap[key1] = {}
|
|
97 storeMap[key1][key2] = r
|
|
98 else:
|
|
99 storeMap[ getattr(r, self.firstKey ) ] = r
|
|
100 else:
|
|
101 key1 = getattr(r, self.firstKey )
|
|
102 if self.secondKey is not None:
|
|
103 key2 = getattr(r, self.secondKey )
|
|
104 if key1 not in storeMap:
|
|
105 storeMap[key1] = {}
|
|
106 if key2 not in storeMap[key1]:
|
|
107 storeMap[key1][key2] = []
|
|
108 storeMap[key1][key2].append(r)
|
|
109 else:
|
|
110 if key1 not in storeMap:
|
|
111 storeMap[key1] = []
|
|
112 storeMap[key1].append(r)
|
|
113 self.loaded = True
|
|
114
|
|
115 """
|
|
116 def __getattr__(self, item):
|
|
117 if not self.loaded:
|
|
118 self.load()
|
|
119
|
|
120 if item == "get_" + self.firstKey + "_list":
|
|
121 return self.__get_firstmap__().keys
|
|
122 if item == "get_by_" + self.firstKey:
|
|
123 return self.__get_firstmap__().__getitem__
|
|
124 if item == "get_" + self.firstKey + "_values":
|
|
125 return self.__get_firstmap__().values
|
|
126 if item == "get_" + self.firstKey + "_map":
|
|
127 return self.__get_firstmap__
|
|
128 if item == "has_" + self.firstKey:
|
|
129 return self.__get_firstmap__().__contains__
|
|
130 raise AttributeError(item)
|
|
131 """
|
|
132
|
|
133 def get_key_list(self):
|
|
134 """
|
|
135 List keys
|
|
136 """
|
|
137 if not self.loaded:
|
|
138 self.load()
|
|
139 return self.__get_firstmap__().keys()
|
|
140
|
|
141 def get_by(self, key):
|
|
142 """
|
|
143 get by key
|
|
144 """
|
|
145 if not self.loaded:
|
|
146 self.load()
|
|
147 return self.__get_firstmap__().__getitem__(key)
|
|
148
|
|
149 def get_values(self):
|
|
150 """
|
|
151 get values
|
|
152 """
|
|
153 if not self.loaded:
|
|
154 self.load()
|
|
155 return self.__get_firstmap__().values()
|
|
156
|
|
157 def get_map(self):
|
|
158 """
|
|
159 get key map
|
|
160 """
|
|
161 if not self.loaded:
|
|
162 self.load()
|
|
163 return self.__get_firstmap__()
|
|
164
|
|
165 def has_key(self, key):
|
|
166 """
|
|
167 Does the table have a key
|
|
168 """
|
|
169 if not self.loaded:
|
|
170 self.load()
|
|
171 return self.__get_firstmap__().__contains__(key)
|
|
172 def __get_firstmap__(self):
|
|
173 return getattr(self, self.firstKey + "_map")
|
|
174
|
|
175 def init_blank(self):
|
|
176 self.free()
|
|
177 self['cgdata'] = { 'type' : self['cgformat']['name'] }
|
|
178 self.loaded = True
|
|
179
|
|
180 def insert(self, name, vals):
|
|
181 storeMap = getattr(self, self.firstKey + "_map")
|
|
182 cols = self['cgformat']['columnOrder']
|
|
183 r = self.__row_class__()
|
|
184 for col in cols:
|
|
185 isOptional = False
|
|
186 if 'columnDef' in self['cgformat'] and col in self['cgformat']['columnDef'] and 'optional' in self['cgformat']['columnDef'][col]:
|
|
187 isOptional = self['cgformat']['columnDef'][col]['optional']
|
|
188 if col in vals:
|
|
189 setattr(r, col, vals[col])
|
|
190 else:
|
|
191 if isOptional:
|
|
192 setattr(r, col, None)
|
|
193 else:
|
|
194 raise InvalidFormat("missing colum " + col)
|
|
195
|
|
196 if not self.groupKey:
|
|
197 if self.secondKey is not None:
|
|
198 key1 = getattr(r, self.firstKey )
|
|
199 key2 = getattr(r, self.secondKey )
|
|
200 if key1 not in storeMap:
|
|
201 storeMap[key1] = {}
|
|
202 storeMap[key1][key2] = r
|
|
203 else:
|
|
204 storeMap[ getattr(r, self.firstKey ) ] = r
|
|
205 else:
|
|
206 key1 = getattr(r, self.firstKey )
|
|
207 if self.secondKey is not None:
|
|
208 key2 = getattr(r, self.secondKey )
|
|
209 if key1 not in storeMap:
|
|
210 storeMap[key1] = {}
|
|
211 if key2 not in storeMap[key1]:
|
|
212 storeMap[key1][key2] = []
|
|
213 storeMap[key1][key2].append(r)
|
|
214 else:
|
|
215 if key1 not in storeMap:
|
|
216 storeMap[key1] = []
|
|
217 storeMap[key1].append(r)
|
|
218
|
|
219 def write(self, handle):
|
|
220 writer = csv.writer(handle, delimiter="\t", lineterminator="\n")
|
|
221 for row in self.row_iter():
|
|
222 orow = []
|
|
223 for col in self['cgformat']['columnOrder']:
|
|
224 orow.append( getattr(row, col) )
|
|
225 writer.writerow(orow)
|
|
226
|
|
227
|
|
228 def row_iter(self):
|
|
229 if not self.groupKey:
|
|
230 keyMap = getattr(self, self.firstKey + "_map")
|
|
231 for rowKey in keyMap:
|
|
232 yield keyMap[rowKey]
|
|
233 else:
|
|
234 keyMap = getattr(self, self.firstKey + "_map")
|
|
235 for rowKey in keyMap:
|
|
236 for elem in keyMap[rowKey]:
|
|
237 yield elem
|
|
238
|
|
239 def __get_firstmap__(self):
|
|
240 return getattr(self, self.firstKey + "_map")
|