Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:48:48

0001 #!/usr/bin/env python
0002 #
0003 # Copyright (c) 2019 Opticks Team. All Rights Reserved.
0004 #
0005 # This file is part of Opticks
0006 # (see https://bitbucket.org/simoncblyth/opticks).
0007 #
0008 # Licensed under the Apache License, Version 2.0 (the "License"); 
0009 # you may not use this file except in compliance with the License.  
0010 # You may obtain a copy of the License at
0011 #
0012 #   http://www.apache.org/licenses/LICENSE-2.0
0013 #
0014 # Unless required by applicable law or agreed to in writing, software 
0015 # distributed under the License is distributed on an "AS IS" BASIS, 
0016 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
0017 # See the License for the specific language governing permissions and 
0018 # limitations under the License.
0019 #
0020 
0021 """
0022 Copied from env/doc/make_rst_table.py 
0023 
0024 http://stackoverflow.com/questions/11347505/what-are-some-approaches-to-outputting-a-python-data-structure-to-restructuredte
0025 
0026 NOTE THAT ana/rsttable.py is a much more capable approach to the same problem 
0027 
0028 
0029 """
0030 import os, logging, numpy as np
0031 log = logging.getLogger(__name__)
0032 
0033 
0034 def make_rst_table(grid):
0035     max_cols = [max(out) for out in map(list, zip(*[[len(item) for item in row] for row in grid]))]
0036     rst = table_div(max_cols, 1)
0037 
0038     for i, row in enumerate(grid):
0039         header_flag = i == 0 or i == len(grid)-1
0040         rst += normalize_row(row,max_cols)
0041         if header_flag or row[0].strip()[-1] == "]":
0042             rst += table_div(max_cols, header_flag )
0043     return rst
0044 
0045 def table_div(max_cols, header_flag=1):
0046     out = ""
0047     if header_flag == 1:
0048         style = "="
0049     else:
0050         style = "-"
0051 
0052     for max_col in max_cols:
0053         out += max_col * style + " "
0054 
0055     out += "\n"
0056     return out
0057 
0058 
0059 def normalize_row(row, max_cols):
0060     """
0061     Padding to equalize cell string lengths 
0062     """
0063     r = ""
0064     for i, max_col in enumerate(max_cols):
0065         r += row[i] + (max_col  - len(row[i]) + 1) * " "
0066 
0067     return r + "\n"
0068 
0069 
0070 
0071 def fmt(cellkind, prefix="", trim="key"):
0072 
0073     cell, kind = cellkind
0074 
0075     # indicates a skipped field
0076     if kind is None:
0077         return None
0078 
0079 
0080     if kind == "f":
0081         fmt = "%5.2f"
0082     elif kind == "i":
0083         fmt = "%d"
0084     else:
0085         fmt = "%s"
0086     pass
0087 
0088     if type(cell) is str or type(cell) is np.string_:
0089         s = str(cell) 
0090         if s == trim:
0091             return prefix  
0092         elif s.startswith(prefix):
0093             return s[len(prefix):]
0094         else:
0095             return s
0096 
0097     return fmt % cell
0098          
0099 
0100 def recarray_as_rst(ra, trim="key", skip=[]):
0101     """
0102     Expecting recarray with dtype of form: 
0103 
0104          dtype=[('key', 'S64'), ('X', '<f4'), ('Y', '<f4'), ('Z', '<f4'), ('T', '<f4'), ('A', '<f4'), ('B', '<f4'), ('C', '<f4'), ('R', '<f4')]
0105 
0106     ======================= ===== ===== ===== ===== ===== ===== ===== ===== 
0107     PmtInBox/torch          X     Y     Z     T     A     B     C     R     
0108     ======================= ===== ===== ===== ===== ===== ===== ===== ===== 
0109     [TO] BT SA               1.15  1.00  0.00  0.00  1.06  1.03  0.00  1.13 
0110     TO [BT] SA               1.15  1.00  1.06  0.91  1.06  1.03  0.00  1.13 
0111     TO BT [SA]               0.97  1.02  1.05  0.99  1.06  1.03  0.00  1.25 
0112     [TO] BT SD               0.91  0.73  0.56  0.56  0.98  1.09  0.56  0.88 
0113     TO [BT] SD               0.91  0.73  0.81  0.89  0.98  1.09  0.56  0.88 
0114     TO BT [SD]               0.99  0.83  0.97  0.99  0.98  1.09  0.56  0.89 
0115     [TO] BT BT SA            0.95  0.82  0.04  0.04  0.97  0.89  0.04  0.57 
0116     TO [BT] BT SA            0.95  0.82  0.70  0.50  0.97  0.89  0.04  0.57 
0117     TO BT [BT] SA            0.91  0.94  0.43  0.60  0.97  0.89  0.04  0.05 
0118     TO BT BT [SA]            0.93  0.87  0.04  0.35  0.97  0.89  0.04  0.72 
0119     ======================= ===== ===== ===== ===== ===== ===== ===== ===== 
0120 
0121 
0122     """
0123 
0124     grid = []
0125 
0126     kinds = map( lambda k:None if k in skip else ra.dtype[k].kind, ra.dtype.names )
0127 
0128     kfield = getattr(ra, trim, None)
0129 
0130     if kfield is None:
0131         prefix = ""
0132     else:  
0133         prefix = os.path.commonprefix(map(str,kfield))
0134     pass
0135 
0136     label_kinds = [None if k in skip else "S" for k in ra.dtype.names]  # all "S" for string, or None for skips
0137 
0138     grid.append(filter(None,map(lambda _:fmt(_,prefix, trim),zip(ra.dtype.names,label_kinds))))
0139 
0140     for i in range(len(ra)):
0141         grid.append(filter(None,map(lambda _:fmt(_,prefix, trim),zip(ra[i],kinds)))) 
0142     pass
0143     return make_rst_table(grid)
0144 
0145 
0146 
0147 def test_make_rst_table():
0148     print(make_rst_table( [['Name', 'Favorite Food', 'Favorite Subject'],
0149                            ['Joe', 'Hamburgrs', 'I like things with really long names'],
0150                            ['Jill', 'Salads', 'American Idol'],
0151                            ['Sally', 'Tofu', 'Math']]))
0152 
0153 if __name__ == '__main__':
0154     logging.basicConfig(level=logging.INFO)
0155     path = os.path.expandvars("$TMP/stat.npy")
0156     log.info("path %s " % path )
0157 
0158     stat = np.load(path).view(np.recarray)
0159     print(recarray_as_rst(stat))
0160 
0161 
0162 
0163 
0164 
0165 
0166 
0167 
0168     
0169 
0170