forked from mfouesneau/eztables
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.py
829 lines (685 loc) · 25.6 KB
/
table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
"""
This module contains the base of any table regardless of their storage
"""
from __future__ import absolute_import
import numpy as np
from .core.odict import odict
from .core.helpers import *
from .core.tableheader import TableHeader
from .core.columnheader import ColumnHeader
import operator, cStringIO
from numpy.lib import recfunctions
from .registered_backends import *
from copy import deepcopy
from .core.decorators import warning
"""
Notes
a table is
a group of *Ordered* columns
a header for description of the table (incl. title, name)
a description of each column
"""
__all__ = ['Table', 'ColumnHeader', 'TableHeader']
#================================================================================
class Table(object):
""" This class implements a Table object which aims at being able to
manage dataset table independently of its storage format.
Tables allows row and column access using the __getitem__ intrinsic
method. Columns can be added to or deleted from the table.
Any columns can be described by its own header which includes units.
Besides Table object can be considered as dict objects and so are
iterable over the columns, Table's data are stored under np.recarray
format for memory footprint and flexibility.
reading and writing methods are not directly defined in this class but
apart using TableManager objects that are then registered with the
"register_extension" function.
"""
#================================================================================
def __init__(self, *args, **kwargs):
"""
Create a table instance
*args: Optional Arguments:
If no arguments are given, and empty table is created
If one or more arguments are given they are passed to the
Table.read() method.
**kwargs: Optional Keyword Arguments (independent of table type):
name: [ string ]
The table name
"""
self.__set_defaults__()
if len(args)>0:
if isinstance(args[0], self.__class__):
self.__set_from_table__(from_Table(*args, **kwargs))
elif (type(args[0]) in [ np.core.records.recarray, np.ndarray]):
self.__set_from_table__(from_ndArray(*args, **kwargs))
elif hasattr(args[0], 'iteritems'):
self.__set_from_table__(from_dict(*args, **kwargs))
else:
self.read(*args, **kwargs)
self.set_name( kwargs.get('name', None) )
def read(self, filename, type=None, manager=None, silent=False, **kwargs):
""" This function is a general function aiming at reading files.
it uses the registered extensions to use the appropriate reading
function.
inputs:
filename -- [ string | buffer ]
adress of the source file to be used
keywords:
type -- [ string ]
if specified, this will force the function
to use considered the file to be of this
type.
manager -- [ Backend ]
If specified, it will use this format
manager (even if not registered)
**kwargs are sent to the Backend.read function
"""
if type == None:
manager = determine_type(filename, verbose=not silent)
else:
manager = determine_type(type, verbose=False)
t = manager().read(filename, **kwargs)
self.data = t.data
self.header = t.header
self._aliases = t._aliases
self.columns = t.columns
def write(self, filename, type=None, manager=None, silent=False, **kwargs):
""" This function is a general function aiming at reading files.
it uses the registered extensions to use the appropriate reading
function.
inputs:
filename -- [ string | buffer ]
adress of the destination file to be used
keywords:
type -- [ string ]
if specified, this will force the function
to use considered the file to be of this
type.
manager -- [ Backend ]
If specified, it will use this format
manager (even if not registered)
**kwargs are sent to the Backend.read function
"""
if type == None:
manager = determine_type(filename, verbose=not silent)
else:
manager = determine_type(type, verbose=False)
return manager().write(self, filename, **kwargs)
def __set_from_table__(self, t):
"""
Set defaults from another Table obj
"""
for k,v in t.__dict__.iteritems():
self.__setattr__(k, v)
def __set_defaults__(self):
"""
Empty the table
"""
self.header = TableHeader()
self.columns = odict()
self._aliases = dict()
self.data = None
self._primary_key = None
def __call__(self, args=None):
if args is None:
return self.info()
else:
return self[args]
def keys(self):
return self.colnames
@property
def colnames(self):
return self.columns.keys()
@property
def ncols(self):
return len(self.colnames)
@property
def nrows(self):
if self.ncols > 0:
return self.data.shape[0]
else:
return 0
@property
def shape(self):
return (self.nrows, self.ncols)
def __len__(self):
return self.nrows
def set_name(self, name):
"""
Set table's name
name: [ string ] The table name
"""
self.header['NAME'] = name
def ravel(self, order='C'):
"""Return a flattened array.
see np.ravel
"""
return self.data.ravel(order=order)
@property
def dtype(self):
return self.data.dtype
def match(self, r2, key):
""" Returns the indices at which the tables match
matching uses 2 columns that are compared in values
INPUTS:
r2 [Table] second table to use
key [str] fields used for comparison.
OUTPUS:
tuple of both indices list where the two columns match.
"""
return np.where( np.equal.outer( self[key], r2[key] ) )
def join_by(self, r2, key, jointype='inner', r1postfix='1', r2postfix='2',
defaults=None, asrecarray=False, asTable=True):
"""
Join arrays `r1` and `r2` on key `key`.
The key should be either a string or a sequence of string corresponding
to the fields used to join the array.
An exception is raised if the `key` field cannot be found in the two input
arrays.
Neither `r1` nor `r2` should have any duplicates along `key`: the presence
of duplicates will make the output quite unreliable. Note that duplicates
are not looked for by the algorithm.
INPUTS:
key {str, seq} A string or a sequence of strings
corresponding to the fields used for comparison.
r2 [Table] Table to join with
KEYWORDS:
jointype [str] {'inner', 'outer', 'leftouter'}
'inner' : returns the elements common to both r1 and r2.
'outer' : returns the common elements as well as the elements
of r1 not in r2 and the elements of not in r2.
'leftouter' : returns the common elements and the elements of r1 not in r2.
r1postfix [str] String appended to the names of the fields of r1 that are present in r2
r2postfix [str] String appended to the names of the fields of r2 that are present in r1
defaults [dict] Dictionary mapping field names to the corresponding default values.
asrecarray [bool] Whether to return a recarray or just a flexible-type ndarray.
asTable [bool] Whether to return a Table (default).
*Notes*:
- The output is sorted along the key.
- A temporary array is formed by dropping the fields not in the key for the
two arrays and concatenating the result. This array is then sorted, and
the common entries selected. The output is constructed by filling the fields
with the selected entries. Matching is not preserved if there are some
duplicates...
"""
#TODO: return a Table by default
if asTable:
asrecarray = True
arr = recfunctions.join_by(key, self, r2, jointype=jointype,
r1postfix=r1postfix, r2postfix=r2postfix,
defaults=defaults, usemask=False,
asrecarray=asrecarray)
return arr
def dtype_for(self, cols):
"""
Return the dtype of a row of a subset of columns.
INPUTS:
cols [ iterable ] The subset of column names for which to return the dtype.
OUTPUTS:
dtype [ np.dtype ]
"""
return np.dtype([ (name, self.columns[name].dtype) for name in cols ])
def tolist(self):
return self.data.tolist()
def set_alias(self, alias, colname):
"""
Define an alias to a column
INPUTS:
alias [ string ] The new alias of the column
colname [ string ] The column being aliased
"""
assert (colname in self.colnames), "Column %s does not exist" % colname
self._aliases[alias] = colname
def reverse_alias(self, colname):
"""
Return aliases of a given column.
Given a colname, return a sequence of aliases associated to this column
Aliases are defined by using .define_alias()
"""
# User aliases
assert colname in self.colnames
return tuple([ k for k,v in self._aliases.iteritems() if (v == colname) ])
def resolve_alias(self, colname):
"""
Return the name of an aliased column.
Given an alias, return the column name it aliases. This
function is a no-op if the alias is a column name itself.
Aliases are defined by using .define_alias()
"""
# User aliases
if hasattr(colname, '__iter__'):
return [ self._aliases.get(k,k) for k in colname ]
else:
return self._aliases.get(colname, colname)
def add_empty_column(self, name, dtype, unit='', null='', description='', format=None,
shape=None, before=None, after=None, position=None, col_hdr=None):
'''
Add an empty column to the table. This only works if there
are already existing columns in the table.
INPUTS:
name [ string ] The name of the column to add
dtype [ np.dtype ] Numpy type of the column.
KEYWORDS:
unit [ string ] The unit of the values in the column
null [ datatype ] The values corresponding to 'null', if not NaN
description [ string ] A description of the content of the column
format [ string ] ASCII printing format
shape [ tuple ] like shape of ndarray (nrow x ncols)
before [ string ] Column before which the new column should be inserted
after [ string ] Column after which the new column should be inserted
position [ integer ] Position at which the new column should be inserted (0 = first)
col_hdr [ ColumnHeader ] The metadata from an existing column to copy over.
Metadata includes the unit, null value, description,
format, and dtype. For example, to create a column 'b'
with identical metadata to column 'a' in table 't', use:
>>> t.add_column('b', column_header=t.columns[a])
'''
if shape:
data = np.empty(shape, dtype=name2dtype(dtype))
elif self.__len__() > 0:
data = np.empty(self.__len__(), dtype=name2dtype(dtype))
else:
raise Exception("Table is empty, shape keyword is required for the first column")
self.add_column(name, data, unit=unit, null=null,
description=description, format=format,
before=before, after=after, position=position,
col_hdr=col_hdr)
def add_column(self, name, data, unit='', null='',
description='', format=None, dtype=None,
before=None, after=None, position=None, fill=None,
col_hdr=None ):
"""
Add a column to the table
INPUTS:
name [ string ] The name of the column to add
data [ np.ndarray ] The column data
KEYWORDS:
unit [ string ] The unit of the values in the column
null [ datatype ] The values corresponding to 'null', if not NaN
description [ string ] A description of the content of the column
format [ string ] ASCII printing format
dtype [ np.dtype ] Numpy type of the column.
before [ string ] Column before which the new column should be inserted
after [ string ] Column after which the new column should be inserted
position [ integer ] Position at which the new column should be inserted (0 = first)
col_hdr [ ColumnHeader ] The metadata from an existing column to copy over.
Metadata includes the unit, null value, description,
format, and dtype. For example, to create a column 'b'
with identical metadata to column 'a' in table 't', use:
>>> t.add_column('b', column_header=t.columns[a])
"""
_data = np.asarray(data)
if col_hdr is not None:
""" Priority to col_hdr """
dtype = column_header.dtype
unit = column_header.unit
null = column_header.null
description = column_header.description
format = column_header.format
else:
dtype = _data.dtype
# unknown type is converted to text
if dtype.type == np.object_:
if len(data) == 0:
longest = 0
else:
longest = len(max(data, key=len))
data = np.asarray(data, dtype='|%iS' % longest)
dtype = data.dtype
if data.ndim > 1:
newdtype = (str(name), data.dtype, (data.shape[1],))
else:
newdtype = (str(name), data.dtype)
# get position
if before:
try:
position = list(self.colnames).index(before)
except:
raise Exception("Column %s does not exist" % before)
elif after:
try:
position = list(self.colnames).index(after) + 1
except:
raise Exception("Column %s does not exist" % before)
if len(self.columns) > 0:
self.data = append_field(self.data, data, dtype=newdtype, position=position)
else:
self.data = np.array(data, dtype=[newdtype])
if not format or format in ['e', 'g', 'f']:
format = default_format[dtype.type]
# Backward compatibility with tuple-style format
if type(format) in [tuple, list]:
format = string.join([str(x) for x in format], "")
if format == 's':
format = '%is' % data.itemsize
column = ColumnHeader(dtype, unit=unit, description=description, null=null, format=format)
if not np.equal(position, None):
self.columns.insert(position, name, column)
else:
self.columns[name] = column
def sort(self, keys):
"""
Sort the table according to one or more keys. This operates
on the existing table (and does not return a new table).
INPUTS:
keys: [ string | list of strings ] The key(s) to order by
"""
if not type(keys) == list:
keys = [keys]
self.data.sort(order=keys)
@property
def empty_row(self):
""" Return an empty row array respecting the table format """
return np.rec.recarray(shape=(1,), dtype=self.data.dtype)
def append_row(self, iterable):
"""
Append set of rows in this table.
"""
assert( len(iterable) == self.ncols ), 'Expecting as many items as columns'
r = self.empty_row
for k,v in enumerate(iterable):
r[0][k] = v
self.stack(r)
def addLine(self, iterable):
"""
Append set of rows in this table.
"""
self.append_row(iterable)
def stack(self, r, defaults=None):
"""
Superposes arrays fields by fields
"""
self.data = recfunctions.stack_arrays ( [self.data, r], defaults, usemask=False, asrecarray=True)
def addCol(self, name, data, unit='', null='',
description='', format=None, dtype=None,
before=None, after=None, position=None, fill=None,
col_hdr=None ):
""" Add individual column to the table
See add_column
"""
self.add_column(name, data, unit=unit, null=null,
description=description, format=format, dtype=dtype,
before=before, after=after, position=position, fill=fill,
col_hdr=col_hdr)
def delCol(self, name):
""" Delete Table column
INPUTS:
name [ string ] Column to delete
"""
self.remove_columns([name])
def remove_column(self, name):
""" Delete Table column
INPUTS:
name [ string ] Column to delete
"""
self.remove_columns([name])
def remove_columns(self, names):
"""
Remove several columns from the table
INPUTS:
names [ list ] A list containing the names of the columns to remove
"""
self.pop_columns(names)
def pop_columns(self, names):
"""
Pop several columns from the table
INPUTS:
names [ list ] A list containing the names of the columns to remove
"""
if type(names) == str:
names = [names]
_names = []
for k in names:
if (k in self._aliases):
self._aliases.pop(k)
else:
map(self._aliases.pop, self.reverse_alias(k))
_names.append(k)
p = [self.columns.pop(name) for name in _names]
self.data = drop_fields(self.data, _names)
# Remove primary key if needed
if self._primary_key in _names:
self._primary_key = None
return p
def find_duplicate(self, index_only=False, values_only=False):
"""Find duplication in the table entries, return a list of duplicated elements
Only works at this time is 2 lines are *the same entry*
not if 2 lines have *the same values*
"""
dup = []
idd = []
for i in range(len(self.data)):
if (self.data[i] in self.data[i + 1:]):
if (self.data[i] not in dup):
dup.append(self.data[i])
idd.append(i)
if index_only:
return idd
elif values_only:
return dup
else:
return zip(idd, dup)
def __getitem__(self, v):
return self.data.__getitem__(self.keys()).__getitem__(self.resolve_alias(v))
def __setitem__(self, v):
return self.data.__getitem__(self.keys()).__setitem__(self.resolve_alias(v))
def __pretty_print__(self, idx=None, fields=None, ret=False):
""" Pretty print the table content
you can select the table parts to display using idx to
select the rows and fields to only display some columns
(ret is only for insternal use)"""
if fields is None:
fields = self.keys()
if isinstance(fields, basestring):
fields = fields.split(',')
nfields = len(fields)
fields = map ( self.resolve_alias, fields )
if idx == None:
if self.nrows < 10:
rows = [ [ str(self[k][rk]) for k in fields ] for rk in range(self.nrows)]
else:
_idx = range(6)
rows = [ [ str(self[k][rk]) for k in fields ] for rk in range(5) ]
if nfields > 1:
rows += [ ['...' for k in range(len(fields)) ] ]
else:
rows += [ ['...' for k in range(len(fields)) ] ]
rows += [ [ str(self[k][rk]) for k in fields ] for rk in range(-5,0)]
elif isinstance(idx, slice):
_idx = range(idx.start, idx.stop, idx.step or 1)
rows = [ [ str(self[k][rk]) for k in fields ] for rk in _idx]
else:
rows = [ [ str(self[k][rk]) for k in fields ] for rk in idx]
units = [ '(' + str( self.columns[k].unit or '') + ')' for k in fields ]
fmt = [ '%'+self.columns[k].format for k in self.keys() ]
#if nfields == 1:
# fields = [fields]
if (''.join(units) == ''.join(['()']*len(fields)) ):
out = __indent__([fields]+rows, hasHeader=True, hasUnits=False)
else:
out = __indent__([fields]+[units]+rows, hasHeader=True, hasUnits=True)
if ret == True :
return out
else:
print out
def __str__(self):
return self.__pretty_print__(ret=True)
def __repr__(self):
s = 'Table: %s, nrows=%i, ncols=%i, ' % (self.header['NAME'], self.nrows, self.ncols)
s += object.__repr__(self)
return s
def __getslice__(self, i,j):
return self.data.__getslice__(i,j)
def __contains__(self, k):
return (k in self.keys()) or (k in self._aliases)
def __iter__(self):
return self.data.__iter__()
def iterkeys(self):
return self.columns.iterkeys()
def itervalues(self):
return self.data.itervalues()
def info(self):
print self.header
print "Table contains: %i row(s) in %i column(s)\n" % (self.nrows, self.ncols)
if self._aliases is not None:
if len(self._aliases) > 0:
print "Table contains alias(es):"
for k,v in self._aliases.iteritems():
print '\t %s --> %s' % (k,v)
print ''
fields = 'columns unit format description'.split()
row = [ (k, self.columns[k].unit, self.columns[k].format, self.columns[k].description) for k in self.keys() ]
out = __indent__([fields]+row, hasHeader=True, hasUnits=False, delim=' ')
print out
def evalexpr(self, expr, exprvars=None, start=None, stop=None, step=None, dtype=float):
""" evaluate expression based on the data and external variables
all np function can be used (log, exp, pi...)
"""
_expr = expr
_globals = {}
for k in ( self.keys() + self._aliases.keys() ):
_globals[k] = self[k]
if exprvars is not None:
assert(hasattr(exprvars, 'keys') & hasattr(exprvars, '__getitem__' )),"Expecting a dictionary-like as condvars"
for k in ( exprvars.keys() ):
_globals[k] = self[k]
# evaluate expression, to obtain the final filter
r = np.empty( self.nrows , dtype=dtype)
r[:] = eval(expr, _globals, np.__dict__)
return r
def where(self, condition, condvars=None, start=None, stop=None, step=None, *args):
""" Read table data fulfilling the given `condition`.
Only the rows fulfilling the `condition` are included in the result.
INPUTS:
condition ndarray[dtype=bool]
OUTPUTS:
out ndarray/ tuple of ndarrays
Additional arguments are forwarded to np.where
"""
ind = np.where(self.evalexpr(condition, condvars, start=start, stop=stop, step=step, dtype=bool ), *args)
return ind
def selectWhere(self, fields, condition, condvars=None, **kwargs):
""" Read table data fulfilling the given `condition`.
Only the rows fulfilling the `condition` are included in the result.
"""
ind = self.where(condition, condvars, **kwargs)
tab = from_Table(self)
if fields.count(',')>0:
_fields = fields.split(',')
elif fields.count(' ')>0:
_fields = fields.split(' ')
else:
_fields = fields
if _fields == '*':
tab.data = tab.data[ind]
else:
tab.data = tab.data[tab.resolve_alias(_fields)][ind]
names = tab.data.dtype.names
#cleanup aliases and columns
for k in self.keys():
if k not in names:
al = self.reverse_alias(k)
for alk in al:
self.delCol(alk)
tab.columns.pop(k)
tab.header['COMMENT'] = 'SELECT %s FROM %s WHERE %s' % (','.join(_fields), self.header['NAME'], condition)
return tab
def setUnit(self, colName, unit):
""" Set the unit of a column referenced by its name """
self.columns[self.resolve_alias(colName)].unit = unit
def setComment(self, colName, comment):
""" Set the comment of a column referenced by its name """
self.columns[self.resolve_alias(colName)].description = comment
def setNull(self, colName, null):
""" Set the comment of a column referenced by its name """
self.columns[self.resolve_alias(colName)].null = null
def setFormat(self, colName, fmt):
""" Set the comment of a column referenced by its name """
self.columns[self.resolve_alias(colName)].format = fmt
def has_key(self, k):
return k in self
def __indent__(rows, hasHeader=False, hasUnits=False, headerChar='-', delim=' | ', justify='left',
separateRows=False, prefix='', postfix='', wrapfunc=lambda x:x):
"""Indents a table by column.
INPUTS:
rows [sequence or sequences of items] one sequence per row.
KEYWORDS:
hasHeader [bool] True if the first row consists of the columns' names
headerChar [char] Character to be used for the row separator line
delim [char] The column delimiter.
justify [str] { center | right | left } data justified in their column.
separateRows [bool] True if rows are to be separated by a line of 'headerChar's.
prefix [str] A string prepended to each printed row.
postfix [str] A string appended to each printed row.
wrapfunc [function] A function f(text) for wrapping text; each element in the
table is first wrapped by this function.
"""
# closure for breaking logical rows to physical, using wrapfunc
def rowWrapper(row):
newRows = [wrapfunc(item).split('\n') for item in row]
return [[substr or '' for substr in item] for item in map(None,*newRows)]
# break each logical row into one or more physical ones
logicalRows = [rowWrapper(row) for row in rows]
# columns of physical rows
columns = map(None,*reduce(operator.add,logicalRows))
# get the maximum of each column by the string length of its items
maxWidths = [max([len(str(item)) for item in column]) for column in columns]
rowSeparator = headerChar * (len(prefix) + len(postfix) + sum(maxWidths) + \
len(delim)*(len(maxWidths)-1))
# select the appropriate justify method
justify = {'center':str.center, 'right':str.rjust, 'left':str.ljust}[justify.lower()]
output=cStringIO.StringIO()
if separateRows: print >> output, rowSeparator
for physicalRows in logicalRows:
for row in physicalRows:
print >> output, \
prefix \
+ delim.join([justify(str(item),width) for (item,width) in zip(row,maxWidths)]) \
+ postfix
if separateRows:
print >> output, rowSeparator
elif hasHeader & (not hasUnits):
print >> output, rowSeparator
elif (not hasHeader) & hasUnits:
print >> output, rowSeparator
hasUnits=False
hasHeader=False
return output.getvalue()
#==============================================================================
def from_dict(obj, **kwargs):
""" Generate a table from a recArray or numpy array """
#==============================================================================
assert( hasattr(obj, 'iteritems') ), "expecting obj has iteritem attribute (dict-like)"
tab = Table()
for k,v in obj.iteritems():
_v = np.asarray(v)
tab.add_column( k, _v, dtype = _v.dtype )
return tab
#==============================================================================
def from_ndArray(obj, **kwargs):
""" Generate a table from a recArray or numpy array """
#==============================================================================
supported_types = [ np.core.records.recarray, np.ndarray ]
assert( type(obj) in supported_types ), "expecting recArray, got %s " % type(obj)
tab = Table()
if obj.dtype.names is not None:
for k in obj.dtype.names:
tab.add_column( k, obj[k], dtype = obj.dtype[k] )
else:
for i in range(obj.shape[1]):
tab.add_column( 'f%d' % i, obj[:,i], dtype = obj.dtype )
return tab
#==============================================================================
def from_Table(obj, **kwargs):
""" Generate a new table fr om a Table obj """
#==============================================================================
assert( isinstance(obj, Table)), "Expecting Table object, got %s" % type(obj)
return deepcopy(obj)
#==============================================================================
def copyTable(tab, **kwargs):
""" Copy a Table """
#==============================================================================
return deepcopy(tab)
@warning(message='Deprecated function. Use Table class constructor instead.')
def load(*args, **kwargs):
return Table(*args, **kwargs)