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]))
|
59
|
78 except ValueError:
|
|
79 skip=1
|
|
80 break
|
31
|
81 raise ValueError( "col invalid type %s on line %d" % (row[i], linenum))
|
|
82 else:
|
|
83 if isOptional:
|
|
84 setattr(r, col, None)
|
|
85 else:
|
|
86 print row
|
52
|
87 skip =1 # ignore bad lines
|
|
88 break
|
31
|
89 raise InvalidFormat("missing colum " + col)
|
52
|
90 if skip:
|
|
91 continue
|
|
92
|
31
|
93 if not self.groupKey:
|
|
94 if self.secondKey is not None:
|
|
95 key1 = getattr(r, self.firstKey )
|
|
96 key2 = getattr(r, self.secondKey )
|
|
97 if key1 not in storeMap:
|
|
98 storeMap[key1] = {}
|
|
99 storeMap[key1][key2] = r
|
|
100 else:
|
|
101 storeMap[ getattr(r, self.firstKey ) ] = r
|
|
102 else:
|
|
103 key1 = getattr(r, self.firstKey )
|
|
104 if self.secondKey is not None:
|
|
105 key2 = getattr(r, self.secondKey )
|
|
106 if key1 not in storeMap:
|
|
107 storeMap[key1] = {}
|
|
108 if key2 not in storeMap[key1]:
|
|
109 storeMap[key1][key2] = []
|
|
110 storeMap[key1][key2].append(r)
|
|
111 else:
|
|
112 if key1 not in storeMap:
|
|
113 storeMap[key1] = []
|
|
114 storeMap[key1].append(r)
|
|
115 self.loaded = True
|
|
116
|
|
117 """
|
|
118 def __getattr__(self, item):
|
|
119 if not self.loaded:
|
|
120 self.load()
|
|
121
|
|
122 if item == "get_" + self.firstKey + "_list":
|
|
123 return self.__get_firstmap__().keys
|
|
124 if item == "get_by_" + self.firstKey:
|
|
125 return self.__get_firstmap__().__getitem__
|
|
126 if item == "get_" + self.firstKey + "_values":
|
|
127 return self.__get_firstmap__().values
|
|
128 if item == "get_" + self.firstKey + "_map":
|
|
129 return self.__get_firstmap__
|
|
130 if item == "has_" + self.firstKey:
|
|
131 return self.__get_firstmap__().__contains__
|
|
132 raise AttributeError(item)
|
|
133 """
|
|
134
|
|
135 def get_key_list(self):
|
|
136 """
|
|
137 List keys
|
|
138 """
|
|
139 if not self.loaded:
|
|
140 self.load()
|
|
141 return self.__get_firstmap__().keys()
|
|
142
|
|
143 def get_by(self, key):
|
|
144 """
|
|
145 get by key
|
|
146 """
|
|
147 if not self.loaded:
|
|
148 self.load()
|
|
149 return self.__get_firstmap__().__getitem__(key)
|
|
150
|
|
151 def get_values(self):
|
|
152 """
|
|
153 get values
|
|
154 """
|
|
155 if not self.loaded:
|
|
156 self.load()
|
|
157 return self.__get_firstmap__().values()
|
|
158
|
|
159 def get_map(self):
|
|
160 """
|
|
161 get key map
|
|
162 """
|
|
163 if not self.loaded:
|
|
164 self.load()
|
|
165 return self.__get_firstmap__()
|
|
166
|
|
167 def has_key(self, key):
|
|
168 """
|
|
169 Does the table have a key
|
|
170 """
|
|
171 if not self.loaded:
|
|
172 self.load()
|
|
173 return self.__get_firstmap__().__contains__(key)
|
|
174 def __get_firstmap__(self):
|
|
175 return getattr(self, self.firstKey + "_map")
|
|
176
|
|
177 def init_blank(self):
|
|
178 self.free()
|
|
179 self['cgdata'] = { 'type' : self['cgformat']['name'] }
|
|
180 self.loaded = True
|
|
181
|
|
182 def insert(self, name, vals):
|
|
183 storeMap = getattr(self, self.firstKey + "_map")
|
|
184 cols = self['cgformat']['columnOrder']
|
|
185 r = self.__row_class__()
|
|
186 for col in cols:
|
|
187 isOptional = False
|
|
188 if 'columnDef' in self['cgformat'] and col in self['cgformat']['columnDef'] and 'optional' in self['cgformat']['columnDef'][col]:
|
|
189 isOptional = self['cgformat']['columnDef'][col]['optional']
|
|
190 if col in vals:
|
|
191 setattr(r, col, vals[col])
|
|
192 else:
|
|
193 if isOptional:
|
|
194 setattr(r, col, None)
|
|
195 else:
|
|
196 raise InvalidFormat("missing colum " + col)
|
|
197
|
|
198 if not self.groupKey:
|
|
199 if self.secondKey is not None:
|
|
200 key1 = getattr(r, self.firstKey )
|
|
201 key2 = getattr(r, self.secondKey )
|
|
202 if key1 not in storeMap:
|
|
203 storeMap[key1] = {}
|
|
204 storeMap[key1][key2] = r
|
|
205 else:
|
|
206 storeMap[ getattr(r, self.firstKey ) ] = r
|
|
207 else:
|
|
208 key1 = getattr(r, self.firstKey )
|
|
209 if self.secondKey is not None:
|
|
210 key2 = getattr(r, self.secondKey )
|
|
211 if key1 not in storeMap:
|
|
212 storeMap[key1] = {}
|
|
213 if key2 not in storeMap[key1]:
|
|
214 storeMap[key1][key2] = []
|
|
215 storeMap[key1][key2].append(r)
|
|
216 else:
|
|
217 if key1 not in storeMap:
|
|
218 storeMap[key1] = []
|
|
219 storeMap[key1].append(r)
|
|
220
|
|
221 def write(self, handle):
|
|
222 writer = csv.writer(handle, delimiter="\t", lineterminator="\n")
|
|
223 for row in self.row_iter():
|
|
224 orow = []
|
|
225 for col in self['cgformat']['columnOrder']:
|
|
226 orow.append( getattr(row, col) )
|
|
227 writer.writerow(orow)
|
|
228
|
|
229
|
|
230 def row_iter(self):
|
|
231 if not self.groupKey:
|
|
232 keyMap = getattr(self, self.firstKey + "_map")
|
|
233 for rowKey in keyMap:
|
|
234 yield keyMap[rowKey]
|
|
235 else:
|
|
236 keyMap = getattr(self, self.firstKey + "_map")
|
|
237 for rowKey in keyMap:
|
|
238 for elem in keyMap[rowKey]:
|
|
239 yield elem
|
|
240
|
|
241 def __get_firstmap__(self):
|
|
242 return getattr(self, self.firstKey + "_map")
|