Package geometry :: Module formatting
[hide private]
[frames] | no frames]

Source Code for Module geometry.formatting

 1  from contracts import contract 
 2  import numpy as np 
 3  from string import ljust 
 4  from contracts import describe_type, describe_value 
5 6 7 -def printm(*args):
8 print(formatm(*args))
9
10 11 -def formatm(*args, **kwargs):
12 #name_len = 10 13 assert len(args) > 0 14 assert len(args) % 2 == 0 15 cols = [] 16 for i in range(len(args) / 2): 17 name = args[i * 2] 18 matrix = args[i * 2 + 1] 19 if not isinstance(name, str): 20 raise ValueError('I expect a string for label, not %s.' 21 % describe_type(name)) 22 # varname = ' %s:' % rjust(name, name_len) 23 varname = ' %s:' % name 24 25 if isinstance(matrix, np.ndarray): 26 # raise ValueError('I expect a numpy array for value, not %s.' % 27 # describe_type(matrix)) 28 value = format_matrix(matrix, **kwargs) 29 if matrix.ndim > 1: 30 varname = '\n' + varname 31 else: 32 value = describe_value(matrix) 33 34 cols.append(varname) 35 cols.append(value) 36 37 cols = add_spacer(cols) 38 return join_columns(cols)
39
40 41 -def add_spacer(cols, spacer=' '):
42 r = [] 43 for c in cols: 44 r.append(c) 45 r.append(spacer) 46 return r[:-1]
47
48 49 @contract(cols='list(str)') 50 -def join_columns(cols):
51 # split lines 52 cols = [x.split('\n') for x in cols] 53 # count max number of rows 54 nrows = max([len(col) for col in cols]) 55 # get row of one column or empty string 56 get_cell = lambda col, i: col[i] if len(col) > i else '' 57 # get maximum length of column 58 col_width = lambda col: max([len(cell) for cell in col]) 59 col_widths = [col_width(col) for i, col in enumerate(cols)] 60 s = '' 61 for j in range(nrows): 62 srow = '' 63 for i, col in enumerate(cols): 64 cell = get_cell(col, j) 65 cell = ljust(cell, col_widths[i]) 66 srow += cell 67 s += srow + '\n' 68 return s
69
70 71 -def format_matrix(matrix, fsize=8, format_str='%g'):
72 if matrix.ndim == 2: 73 nrows, ncols = matrix.shape 74 cols = [[] for _ in range(ncols)] 75 for j in range(ncols): 76 for i in range(nrows): 77 s = (' ' + format_str) % matrix[i, j] 78 cols[j].append(s) 79 cols = ["\n".join(col) for col in cols] 80 borders = "\n".join(["|" for i in range(nrows)]) 81 bcols = [] 82 bcols.append(borders) 83 bcols.extend(cols) 84 bcols.append(borders) 85 return join_columns(bcols) 86 return "%s" % matrix
87 88 89 if __name__ == '__main__': 90 91 A = np.eye(3) 92 B = np.random.randn(3, 4) 93 printm('A (identity):', A, 'B (random):', B) 94