forked from mfouesneau/ezmist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simpletable.py
2843 lines (2328 loc) · 89.6 KB
/
simpletable.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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" This file implements a Table class
that is designed to be the basis of any format
Requirements
------------
* FIT format:
* astropy:
provides a replacement to pyfits
pyfits can still be used instead but astropy is now the default
* HDF5 format:
* pytables
RuntimeError will be raised when writing to a format associated with missing
package.
.. code-block::python
>>> t = SimpleTable('path/mytable.csv')
# get a subset of columns only
>>> s = t.get('M_* logTe logLo U B V I J K')
# set some aliases
>>> t.set_alias('logT', 'logTe')
>>> t.set_alias('logL', 'logLLo')
# make a query on one or multiple column
>>> q = s.selectWhere('logT logL', '(J > 2) & (10 ** logT > 5000)')
# q is also a table object
>>> q.plot('logT', 'logL', ',')
# makes a simple plot
>>> s.write('newtable.fits')
# export the initial subtable to a new file
"""
from __future__ import (absolute_import, division, print_function)
__version__ = '3.0'
__all__ = ['AstroHelpers', 'AstroTable', 'SimpleTable', 'stats']
import sys
import math
from copy import deepcopy
import re
import itertools
from functools import wraps, partial
import numpy as np
from numpy import deg2rad, rad2deg, sin, cos, sqrt, arcsin, arctan2
from numpy.lib import recfunctions
try:
from astropy.io import fits as pyfits
except ImportError:
try:
import pyfits
except:
pyfits = None
try:
import tables
except ImportError:
tables = None
# ==============================================================================
# Python 3 compatibility behavior
# ==============================================================================
# remap some python 2 built-ins on to py3k behavior or equivalent
# Most of them become generators
import operator
PY3 = sys.version_info[0] > 2
if PY3:
iteritems = operator.methodcaller('items')
itervalues = operator.methodcaller('values')
basestring = (str, bytes)
else:
range = xrange
from itertools import izip as zip
iteritems = operator.methodcaller('iteritems')
itervalues = operator.methodcaller('itervalues')
basestring = (str, unicode)
# ==============================================================================
# Specials -- special functions
# ==============================================================================
def pretty_size_print(num_bytes):
"""
Output number of bytes in a human readable format
keywords
--------
num_bytes: int
number of bytes to convert
returns
-------
output: str
string representation of the size with appropriate unit scale
"""
if num_bytes is None:
return
KiB = 1024
MiB = KiB * KiB
GiB = KiB * MiB
TiB = KiB * GiB
PiB = KiB * TiB
EiB = KiB * PiB
ZiB = KiB * EiB
YiB = KiB * ZiB
if num_bytes > YiB:
output = '%.3g YB' % (num_bytes / YiB)
elif num_bytes > ZiB:
output = '%.3g ZB' % (num_bytes / ZiB)
elif num_bytes > EiB:
output = '%.3g EB' % (num_bytes / EiB)
elif num_bytes > PiB:
output = '%.3g PB' % (num_bytes / PiB)
elif num_bytes > TiB:
output = '%.3g TB' % (num_bytes / TiB)
elif num_bytes > GiB:
output = '%.3g GB' % (num_bytes / GiB)
elif num_bytes > MiB:
output = '%.3g MB' % (num_bytes / MiB)
elif num_bytes > KiB:
output = '%.3g KB' % (num_bytes / KiB)
else:
output = '%.3g Bytes' % (num_bytes)
return output
def _fits_read_header(hdr):
"""
Convert pyfits header into dictionary with relevant values
Parameters
----------
hdr: pyftis.Header
fits unit
Returns
-------
header: dict
header dictionary
alias: dict
aliases
units: dict
units
comments: dict
comments/description of keywords
"""
header = {}
alias = {}
units = {}
comments = {}
# generic cards
genTerms = ['XTENSION', 'BITPIX', 'NAXIS', 'NAXIS1',
'NAXIS2', 'PCOUNT', 'GCOUNT', 'TFIELDS',
'EXTNAME']
fieldTerms = ['TTYPE', 'TFORM', 'TUNIT', 'ALIAS']
# read col comments
for k, name, comment in hdr.ascard['TTYPE*']:
comments[name] = comment
u = hdr.get(k.replace('TYPE', 'UNIT'), None)
if u is not None:
units[name] = u
for k, val, _ in hdr.ascard['ALIAS*']:
al, orig = val.split('=')
alias[al] = orig
# other specific keywords: COMMENT, HISTORY
header_comments = []
header_history = []
for k, v in hdr.items():
if (k not in genTerms) and (k[:5] not in fieldTerms):
if (k == 'COMMENT'):
header_comments.append(v)
elif (k == 'HISTORY'):
header_history.append(v)
else:
header[k] = v
# COMMENT, HISTORY polish
if len(header_comments) > 0:
header['COMMENT'] = '\n'.join(header_comments)
if len(header_history) > 0:
header['HISTORY'] = '\n'.join(header_history)
if 'EXTNAME' in hdr:
header['NAME'] = hdr['EXTNAME']
return header, alias, units, comments
def _fits_generate_header(tab):
""" Generate the corresponding fits Header that contains all necessary info
Parameters
----------
tab: SimpleTable instance
table
Returns
-------
hdr: pyfits.Header
header instance
"""
# get column cards
cards = []
# names units and comments
for e, k in enumerate(tab.keys()):
cards.append(('TTYPE{0:d}'.format(e + 1), k, tab._desc.get(k, '')))
u = tab._units.get(k, '')
if u not in ['', 'None', None]:
cards.append(('TUNIT{0:d}'.format(e + 1), tab._units.get(k, ''),
'unit of {0:s}'.format(k)))
# add aliases
for e, v in enumerate(tab._aliases.items()):
cards.append( ('ALIAS{0:d}'.format(e + 1), '='.join(v), '') )
if tab.header['NAME'] not in ['', 'None', None, 'No Name']:
cards.append(('EXTNAME', tab.header['NAME'], ''))
hdr = pyfits.Header(cards)
for k, v in tab.header.items():
if (v not in ['', 'None', None]) & (k != 'NAME'):
if (k != 'COMMENT') & (k != 'HISTORY'):
hdr.update(k, v)
else:
txt = v.split('\n')
for j in txt:
if k == 'COMMENT':
hdr.add_comment(j)
elif k == 'HISTORY':
hdr.add_history(j)
return hdr
def _fits_writeto(filename, data, header=None, output_verify='exception',
clobber=False, checksum=False):
"""
Create a new FITS file using the supplied data/header.
Patched version of pyfits to correctly include provided header
Parameters
----------
filename : file path, file object, or file like object
File to write to. If opened, must be opened in a writeable binary
mode such as 'wb' or 'ab+'.
data : array, record array, or groups data object
data to write to the new file
header : `Header` object, optional
the header associated with ``data``. If `None`, a header
of the appropriate type is created for the supplied data. This
argument is optional.
output_verify : str
Output verification option. Must be one of ``"fix"``, ``"silentfix"``,
``"ignore"``, ``"warn"``, or ``"exception"``. May also be any
combination of ``"fix"`` or ``"silentfix"`` with ``"+ignore"``,
``+warn``, or ``+exception" (e.g. ``"fix+warn"``). See :ref:`verify`
for more info.
clobber : bool, optional
If `True`, and if filename already exists, it will overwrite
the file. Default is `False`.
checksum : bool, optional
If `True`, adds both ``DATASUM`` and ``CHECKSUM`` cards to the
headers of all HDU's written to the file
"""
hdu = pyfits.convenience._makehdu(data, header)
hdu.header.update(header.cards)
if hdu.is_image and not isinstance(hdu, pyfits.PrimaryHDU):
hdu = pyfits.PrimaryHDU(data, header=header)
hdu.writeto(filename, clobber=clobber, output_verify=output_verify,
checksum=checksum)
def _fits_append(filename, data, header=None, checksum=False, verify=True,
**kwargs):
"""
Append the header/data to FITS file if filename exists, create if not.
If only ``data`` is supplied, a minimal header is created.
Patched version of pyfits to correctly include provided header
Parameters
----------
filename : file path, file object, or file like object
File to write to. If opened, must be opened for update (rb+) unless it
is a new file, then it must be opened for append (ab+). A file or
`~gzip.GzipFile` object opened for update will be closed after return.
data : array, table, or group data object
the new data used for appending
header : `Header` object, optional
The header associated with ``data``. If `None`, an appropriate header
will be created for the data object supplied.
checksum : bool, optional
When `True` adds both ``DATASUM`` and ``CHECKSUM`` cards to the header
of the HDU when written to the file.
verify : bool, optional
When `True`, the existing FITS file will be read in to verify it for
correctness before appending. When `False`, content is simply appended
to the end of the file. Setting ``verify`` to `False` can be much
faster.
kwargs
Any additional keyword arguments to be passed to
`astropy.io.fits.open`.
"""
name, closed, noexist_or_empty = pyfits.convenience._stat_filename_or_fileobj(filename)
if noexist_or_empty:
#
# The input file or file like object either doesn't exits or is
# empty. Use the writeto convenience function to write the
# output to the empty object.
#
_fits_writeto(filename, data, header, checksum=checksum, **kwargs)
else:
hdu = pyfits.convenience._makehdu(data, header)
hdu.header.update(header.cards)
if isinstance(hdu, pyfits.PrimaryHDU):
hdu = pyfits.ImageHDU(data, header)
if verify or not closed:
f = pyfits.convenience.fitsopen(filename, mode='append')
f.append(hdu)
# Set a flag in the HDU so that only this HDU gets a checksum when
# writing the file.
hdu._output_checksum = checksum
f.close(closed=closed)
else:
f = pyfits.convenience._File(filename, mode='append')
hdu._output_checksum = checksum
hdu._writeto(f)
f.close()
def _ascii_read_header(fname, comments='#', delimiter=None, commentedHeader=True,
*args, **kwargs):
"""
Read ASCII/CSV header
Parameters
----------
fname: str or stream
File, filename, or generator to read.
Note that generators should return byte strings for Python 3k.
comments: str, optional
The character used to indicate the start of a comment;
default: '#'.
delimiter: str, optional
The string used to separate values. By default, this is any
whitespace.
commentedHeader: bool, optional
if set, the last line of the header is expected to be the column titles
Returns
-------
nlines: int
number of lines from the header
header: dict
header dictionary
alias: dict
aliases
units: dict
units
comments: dict
comments/description of keywords
names: sequence
sequence or str, first data line after header, expected to be the column
names.
"""
if hasattr(fname, 'read'):
stream = fname
else:
stream = open(fname, 'r')
header = {}
alias = {}
units = {}
desc = {}
def parseStrNone(v):
""" robust parse """
_v = v.split()
if (len(_v) == 0):
return None
else:
_v = ' '.join(_v)
if (_v.lower()) == 'none' or (_v.lower() == 'null'):
return None
else:
return _v
done = False
oldline = None
lasthdr = None
nlines = 0
header.setdefault('COMMENT', '')
header.setdefault('HISTORY', '')
while done is False:
line = stream.readline()[:-1] # getting rid of '\n'
nlines += 1
if (line[0] == comments): # header part
if (len(line) > 2):
if line[1] == comments: # column meta data
# column meta is expected to start with ##
k = line[2:].split('\t')
colname = k[0].strip()
colunit = None
colcomm = None
if len(k) > 1:
colunit = parseStrNone(k[1])
if len(k) > 2:
colcomm = parseStrNone(k[2])
if colunit is not None:
units[colname] = colunit
if colcomm is not None:
desc[colname] = colcomm
else:
# header is expected as "# key \t value"
k = line[1:].split('\t')
if len(k) > 1:
key = k[0].strip() # remove trainling spaces
val = ' '.join(k[1:]).strip()
if key in ('', None, 'None', 'NONE', 'COMMENT'):
header['COMMENT'] = header['COMMENT'] + '\n' + val
if key in ('HISTORY', ):
header['HISTORY'] = header['HISTORY'] + '\n' + val
elif 'alias' in key.lower():
# take care of aliases
al, orig = val.split('=')
alias[al] = orig
else:
header[key] = val
lasthdr = key
else:
header['COMMENT'] = header['COMMENT'] + '\n' + line[1:]
else:
done = True
if commentedHeader and (oldline is not None):
names = oldline.split(delimiter)
nlines -= 1
if lasthdr == names[0]:
header.pop(lasthdr)
else:
names = line.split(delimiter)
oldline = line[1:]
if not hasattr(fname, 'read'):
stream.close()
else:
stream.seek(stream.tell() - len(line))
nlines = 0 # make sure the value is set to the current position
return nlines, header, units, desc, alias, names
def _hdf5_write_data(filename, data, tablename=None, mode='w', append=False,
header={}, units={}, comments={}, aliases={}, **kwargs):
""" Write table into HDF format
Parameters
----------
filename : file path, or tables.File instance
File to write to. If opened, must be opened and writable (mode='w' or 'a')
data: recarray
data to write to the new file
tablename: str
path of the node including table's name
mode: str
in ('w', 'a') mode to open the file
append: bool
if set, tends to append data to an existing table
header: dict
table header
units: dict
dictionary of units
alias: dict
aliases
comments: dict
comments/description of keywords
.. note::
other keywords are forwarded to :func:`tables.openFile`
"""
if hasattr(filename, 'read'):
raise Exception("HDF backend does not implement stream")
if append is True:
mode = 'a'
if isinstance(filename, tables.File):
if (filename.mode != mode) & (mode != 'r'):
raise tables.FileModeError('The file is already opened in a different mode')
hd5 = filename
else:
hd5 = tables.openFile(filename, mode=mode)
# check table name and path
tablename = tablename or header.get('NAME', None)
if tablename in ('', None, 'Noname', 'None'):
tablename = '/data'
w = tablename.split('/')
where = '/'.join(w[:-1])
name = w[-1]
if where in ('', None):
where = '/'
if where[0] != '/':
where = '/' + where
if append:
try:
t = hd5.getNode(where + name)
t.append(data.astype(t.description._v_dtype))
t.flush()
except tables.NoSuchNodeError:
print(("Warning: Table {0} does not exists. \n A new table will be created").format(where + name))
append = False
if not append:
t = hd5.createTable(where, name, data, **kwargs)
# update header
for k, v in header.items():
if (k == 'FILTERS') & (float(t.attrs['VERSION']) >= 2.0):
t.attrs[k.lower()] = v
else:
t.attrs[k] = v
if 'TITLE' not in header:
t.attrs['TITLE'] = name
# add column descriptions and units
for e, colname in enumerate(data.dtype.names):
_u = units.get(colname, None)
_d = comments.get(colname, None)
if _u is not None:
t.attrs['FIELD_{0:d}_UNIT'] = _u
if _d is not None:
t.attrs['FIELD_{0:d}_DESC'] = _d
# add aliases
for i, (k, v) in enumerate(aliases.items()):
t.attrs['ALIAS{0:d}'.format(i)] = '{0:s}={1:s}'.format(k, v)
t.flush()
if not isinstance(filename, tables.File):
hd5.flush()
hd5.close()
def _hdf5_read_data(filename, tablename=None, silent=False, *args, **kwargs):
""" Generate the corresponding ascii Header that contains all necessary info
Parameters
----------
filename: str
file to read from
tablename: str
node containing the table
silent: bool
skip verbose messages
Returns
-------
hdr: str
string that will be be written at the beginning of the file
"""
source = tables.openFile(filename, *args, **kwargs)
if tablename is None:
node = source.listNodes('/')[0]
tablename = node.name
else:
if tablename[0] != '/':
node = source.getNode('/' + tablename)
else:
node = source.getNode(tablename)
if not silent:
print("\tLoading table: {0}".format(tablename))
hdr = {}
aliases = {}
# read header
exclude = ['NROWS', 'VERSION', 'CLASS', 'EXTNAME', 'TITLE']
for k in node.attrs._v_attrnames:
if (k not in exclude):
if (k[:5] != 'FIELD') & (k[:5] != 'ALIAS'):
hdr[k] = node.attrs[k]
elif k[:5] == 'ALIAS':
c0, c1 = node.attrs[k].split('=')
aliases[c0] = c1
empty_name = ['', 'None', 'Noname', None]
if node.attrs['TITLE'] not in empty_name:
hdr['NAME'] = node.attrs['TITLE']
else:
hdr['NAME'] = '{0:s}/{1:s}'.format(filename, node.name)
# read column meta
units = {}
desc = {}
for (k, colname) in enumerate(node.colnames):
_u = getattr(node.attrs, 'FIELD_{0:d}_UNIT'.format(k), None)
_d = getattr(node.attrs, 'FIELD_{0:d}_DESC'.format(k), None)
if _u is not None:
units[colname] = _u
if _d is not None:
desc[colname] = _d
data = node[:]
source.close()
return hdr, aliases, units, desc, data
def _ascii_generate_header(tab, comments='#', delimiter=' ',
commentedHeader=True):
""" Generate the corresponding ascii Header that contains all necessary info
Parameters
----------
tab: SimpleTable instance
table
comments: str
string to prepend header lines
delimiter: str, optional
The string used to separate values. By default, this is any
whitespace.
commentedHeader: bool, optional
if set, the last line of the header is expected to be the column titles
Returns
-------
hdr: str
string that will be be written at the beginning of the file
"""
hdr = []
if comments is None:
comments = ''
# table header
length = max(map(len, tab.header.keys()))
fmt = '{{0:s}} {{1:{0:d}s}}\t{{2:s}}'.format(length)
for k, v in tab.header.items():
for vk in v.split('\n'):
if len(vk) > 0:
hdr.append(fmt.format(comments, k.upper(), vk.strip()))
# column metadata
hdr.append(comments) # add empty line
length = max(map(len, tab.keys()))
fmt = '{{0:s}}{{0:s}} {{1:{0:d}s}}\t{{2:s}}\t{{3:s}}'.format(length)
for colname in tab.keys():
unit = tab._units.get(colname, 'None')
desc = tab._desc.get(colname, 'None')
hdr.append(fmt.format(comments, colname, unit, desc))
# aliases
if len(tab._aliases) > 0:
hdr.append(comments) # add empty line
for k, v in tab._aliases.items():
hdr.append('{0:s} alias\t{1:s}={2:s}'.format(comments, k, v))
# column names
hdr.append(comments)
if commentedHeader:
hdr.append('{0:s} {1:s}'.format(comments, delimiter.join(tab.keys())))
else:
hdr.append('{0:s}'.format(delimiter.join(tab.keys())))
return '\n'.join(hdr)
def _latex_writeto(filename, tab, comments='%'):
""" Write the data into a latex table format
Parameters
----------
filename: str
file or unit to write into
tab: SimpleTable instance
table
comments: str
string to prepend header lines
delimiter: str, optional
The string used to separate values. By default, this is any
whitespace.
commentedHeader: bool, optional
if set, the last line of the header is expected to be the column titles
"""
txt = "\\begin{table}\n\\begin{center}\n"
# add caption
tabname = tab.header.get('NAME', None)
if tabname not in ['', None, 'None']:
txt += "\\caption{{{0:s}}}\n".format(tabname)
# tabular
txt += '\\begin{{tabular}}{{{0:s}}}\n'.format('c' * tab.ncols)
txt += tab.pprint(delim=' & ', fields='MAG*', headerChar='', endline='\\\\\n', all=True, ret=True)
txt += '\\end{tabular}\n'
# end table
txt += "\\end{center}\n"
# add notes if any
if len(tab._desc) > 0:
txt += '\% notes \n\\begin{scriptsize}\n'
for e, (k, v) in enumerate(tab._desc.items()):
if v not in (None, 'None', 'none', ''):
txt += '{0:d} {1:s}: {2:s} \\\\\n'.format(e, k, v)
txt += '\\end{scriptsize}\n'
txt += "\\end{table}\n"
if hasattr(filename, 'write'):
filename.write(txt)
else:
with open(filename, 'w') as unit:
unit.write(txt)
def _convert_dict_to_structured_ndarray(data):
"""convert_dict_to_structured_ndarray
Parameters
----------
data: dictionary like object
data structure which provides iteritems and itervalues
returns
-------
tab: structured ndarray
structured numpy array
"""
newdtype = []
for key, dk in iteritems(data):
_dk = np.asarray(dk)
dtype = _dk.dtype
# unknown type is converted to text
if dtype.type == np.object_:
if len(data) == 0:
longest = 0
else:
longest = len(max(_dk, key=len))
_dk = _dk.astype('|%iS' % longest)
if _dk.ndim > 1:
newdtype.append((str(key), _dk.dtype, (_dk.shape[1],)))
else:
newdtype.append((str(key), _dk.dtype))
tab = np.rec.fromarrays(itervalues(data), dtype=newdtype)
return tab
def __indent__(rows, header=None, units=None, headerChar='-',
delim=' | ', endline='\n', **kwargs):
"""Indents a table by column.
Parameters
----------
rows: sequences of rows
one sequence per row.
header: sequence of str
row consists of the columns' names
units: sequence of str
Sequence of units
headerChar: char
Character to be used for the row separator line
delim: char
The column delimiter.
returns
-------
txt: str
string represation of rows
"""
length_data = list(map(max, zip(*[list(map(len, k)) for k in rows])))
length = length_data[:]
if (header is not None):
length_header = list(map(len, header))
length = list(map(max, zip(length_data, length_header)))
if (units is not None):
length_units = list(map(len, units))
length = list(map(max, zip(length_data, length_units)))
if headerChar not in (None, '', ' '):
rowSeparator = headerChar * (sum(length) + len(delim) * (len(length) - 1)) + endline
else:
rowSeparator = ''
# make the format
fmt = ['{{{0:d}:{1:d}s}}'.format(k, l) for (k, l) in enumerate(length)]
fmt = delim.join(fmt) + endline
# write the string
txt = rowSeparator
if header is not None:
txt += fmt.format(*header) # + endline
txt += rowSeparator
if units is not None:
txt += fmt.format(*units) # + endline
txt += rowSeparator
for r in rows:
txt += fmt.format(*r) # + endline
txt += rowSeparator
return txt
def pprint_rec_entry(data, num=0, keys=None):
""" print one line with key and values properly to be readable
Parameters
----------
data: recarray
data to extract entry from
num: int, slice
indice selection
keys: sequence or str
if str, can be a regular expression
if sequence, the sequence of keys to print
"""
if (keys is None) or (keys == '*'):
_keys = data.dtype.names
elif type(keys) in basestring:
_keys = [k for k in data.dtype.names if (re.match(keys, k) is not None)]
else:
_keys = keys
length = max(map(len, _keys))
fmt = '{{0:{0:d}s}}: {{1}}'.format(length)
data = data[num]
for k in _keys:
print(fmt.format(k, data[k]))
def pprint_rec_array(data, idx=None, fields=None, ret=False, all=False,
headerChar='-', delim=' | ', endline='\n' ):
""" 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)
Parameters
----------
data: array
array to show
idx: sequence, slide
sub selection to print
fields: str, sequence
if str can be a regular expression, and/or list of fields separated
by spaces or commas
ret: bool
if set return the string representation instead of printing the result
all: bool
if set, force to show all rows
headerChar: char
Character to be used for the row separator line
delim: char
The column delimiter.
"""
if (fields is None) or (fields == '*'):
_keys = data.dtype.names
elif type(fields) in basestring:
if ',' in fields:
_fields = fields.split(',')
elif ' ' in fields:
_fields = fields.split()
else:
_fields = [fields]
lbls = data.dtype.names
_keys = []
for _fk in _fields:
_keys += [k for k in lbls if (re.match(_fk, k) is not None)]
else:
lbls = data.dtype.names
_keys = []
for _fk in _fields:
_keys += [k for k in lbls if (re.match(_fk, k) is not None)]
nfields = len(_keys)
nrows = len(data)
fields = list(_keys)
if idx is None:
if (nrows < 10) or (all is True):
rows = [ [ str(data[k][rk]) for k in _keys ] for rk in range(nrows)]
else:
_idx = range(6)
rows = [ [ str(data[k][rk]) for k in _keys ] for rk in range(5) ]
if nfields > 1:
rows += [ ['...' for k in range(nfields) ] ]
else:
rows += [ ['...' for k in range(nfields) ] ]
rows += [ [ str(data[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(data[k][rk]) for k in fields ] for rk in _idx]
else:
rows = [ [ str(data[k][rk]) for k in fields ] for rk in idx]
out = __indent__(rows, header=_keys, units=None, delim=delim,
headerChar=headerChar, endline=endline)
if ret is True:
return out
else:
print(out)
def elementwise(func):
"""
Quick and dirty elementwise function decorator it provides a quick way
to apply a function either on one element or a sequence of elements
"""
@wraps(func)
def wrapper(it, **kwargs):
if hasattr(it, '__iter__') & (type(it) not in basestring):
_f = partial(func, **kwargs)
return map(_f, it)
else:
return func(it, **kwargs)
return wrapper