├── .gitignore ├── CHANGES.txt ├── LICENSE.TXT ├── MANIFEST.in ├── README.md ├── README.txt ├── example └── python-omx-sample.py ├── openmatrix ├── Exceptions.py ├── File.py ├── __init__.py ├── test │ └── test_file.py └── validator.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | *.egg 4 | *.egg-info 5 | .installed.cfg 6 | 7 | pip-log.txt 8 | 9 | # Unit test / coverage reports 10 | .coverage 11 | .tox 12 | nosetests.xml 13 | 14 | # Translations 15 | *.mo 16 | 17 | # Mr Developer 18 | .mr.developer.cfg 19 | .project 20 | .pydevproject 21 | 22 | # Python build directory 23 | api/python/build 24 | -------------------------------------------------------------------------------- /CHANGES.txt: -------------------------------------------------------------------------------- 1 | v0.2.0, 2015-01-15 -- Initial release. 2 | v0.2.1, 2015-01-15 -- Fix numpy version requirement in setup 3 | v0.2.2, 2015-01-15 -- Fix test to reference openmatrix instead of omx 4 | v0.2.3, 2015-02-20 -- Bug fixes and lots more tests 5 | v0.3.3, 2017-03-07 -- Python 3 compatible 6 | v0.3.4, 2018-04-05 -- Fix incorrect version being saved 7 | v0.3.4.1, 2018-10-19 -- python3 compatible next for generator 8 | v0.3.5, 2019-12-21 -- add validator and clean-up repo structure 9 | 10 | -------------------------------------------------------------------------------- /LICENSE.TXT: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | recursive-include docs *.txt 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OMX Python API Documentation 2 | 3 | The Python OMX API borrows heavily from PyTables. An OMX file extends the equivalent PyTables File object, so anything you can do in PyTables you can do with OMX as well. This API attempts to be very Pythonic, including dictionary-style lookup of matrix names. 4 | 5 | * [Pre-requisites](#pre-requisites) 6 | * [Installation](#installation) 7 | * [Quick Start Code](#quick-start-sample-code) 8 | * [Testing](#testing) 9 | * [OMX File Validator](#omx-file-validator) 10 | * [Usage Notes](#usage-notes) 11 | * [API Reference](#api-reference) 12 | 13 | # Pre-requisites 14 | 15 | Python 2.6+, PyTables 3.1+, and NumPy. Python 3 is now supported too. 16 | 17 | On Windows, the easiest way to get these is from [Anaconda](https://www.continuum.io/downloads#windows) or from Chris Gohlke's python binaries [page](http://www.lfd.uci.edu/~gohlke/pythonlibs/). On Linux, your distribution already has these available. 18 | 19 | # Installation 20 | 21 | The easiest way to get OMX on Python is to use pip. Get the latest package (called OpenMatrix) from the [Python Package Index](https://pypi.python.org/pypi) 22 | 23 | `pip install openmatrix` 24 | 25 | This command will fetch openmatrix from the PyPi repository and download/install it for you. The package name "omx" was already taken on pip for a lame xml library that no one uses. Thus our little project goes by "openmatrix" on pip instead of "omx". This means your import statements should look like, 26 | 27 | `import openmatrix as omx` 28 | 29 | and NOT: 30 | 31 | `import omx` 32 | 33 | # Quick-Start Sample Code 34 | 35 | ```python 36 | from __future__ import print_function 37 | import openmatrix as omx 38 | import numpy as np 39 | 40 | # Create some data 41 | ones = np.ones((100,100)) 42 | twos = 2.0*ones 43 | 44 | # Create an OMX file (will overwrite existing file!) 45 | print('Creating myfile.omx') 46 | myfile = omx.open_file('myfile.omx','w') # use 'a' to append/edit an existing file 47 | 48 | # Write to the file. 49 | myfile['m1'] = ones 50 | myfile['m2'] = twos 51 | myfile['m3'] = ones + twos # numpy array math is fast 52 | myfile.close() 53 | 54 | # Open an OMX file for reading only 55 | print('Reading myfile.omx') 56 | myfile = omx.open_file('myfile.omx') 57 | 58 | print ('Shape:', myfile.shape()) # (100,100) 59 | print ('Number of tables:', len(myfile)) # 3 60 | print ('Table names:', myfile.list_matrices()) # ['m1','m2',',m3'] 61 | 62 | # Work with data. Pass a string to select matrix by name: 63 | # ------------------------------------------------------- 64 | m1 = myfile['m1'] 65 | m2 = myfile['m2'] 66 | m3 = myfile['m3'] 67 | 68 | # halves = m1 * 0.5 # CRASH! Don't modify an OMX object directly. 69 | # # Create a new numpy array, and then edit it. 70 | halves = np.array(m1) * 0.5 71 | 72 | first_row = m2[0] 73 | first_row[:] = 0.5 * first_row[:] 74 | 75 | my_very_special_zone_value = m2[10][25] 76 | 77 | # FANCY: Use attributes to find matrices 78 | # -------------------------------------- 79 | myfile.close() # was opened read-only, so let's reopen. 80 | myfile = omx.open_file('myfile.omx','a') # append mode: read/write existing file 81 | 82 | myfile['m1'].attrs.timeperiod = 'am' 83 | myfile['m1'].attrs.mode = 'hwy' 84 | 85 | myfile['m2'].attrs.timeperiod = 'md' 86 | 87 | myfile['m3'].attrs.timeperiod = 'am' 88 | myfile['m3'].attrs.mode = 'trn' 89 | 90 | print('attributes:', myfile.list_all_attributes()) # ['mode','timeperiod'] 91 | 92 | # Use a DICT to select matrices via attributes: 93 | 94 | all_am_trips = myfile[ {'timeperiod':'am'} ] # [m1,m3] 95 | all_hwy_trips = myfile[ {'mode':'hwy'} ] # [m1] 96 | all_am_trn_trips = myfile[ {'mode':'trn','timeperiod':'am'} ] # [m3] 97 | 98 | print('sum of some tables:', np.sum(all_am_trips)) 99 | 100 | # SUPER FANCY: Create a mapping to use TAZ numbers instead of matrix offsets 101 | # -------------------------------------------------------------------------- 102 | # (any mapping would work, such as a mapping with large gaps between zone 103 | # numbers. For this simple case we'll just assume TAZ numbers are 1-100.) 104 | 105 | taz_equivs = np.arange(1,101) # 1-100 inclusive 106 | 107 | myfile.create_mapping('taz', taz_equivs) 108 | print('mappings:', myfile.list_mappings()) # ['taz'] 109 | 110 | tazs = myfile.mapping('taz') # Returns a dict: {1:0, 2:1, 3:2, ..., 100:99} 111 | m3 = myfile['m3'] 112 | print('cell value:', m3[tazs[100]][tazs[100]]) # 3.0 (taz (100,100) is cell [99][99]) 113 | 114 | myfile.close() 115 | ``` 116 | 117 | # Testing 118 | Testing is done with [nose](https://nose.readthedocs.io/en/latest/). Run the tests via: 119 | 120 | ``` 121 | openmatrix\test> nosetests -v 122 | ``` 123 | 124 | # OMX File Validator 125 | Included in this package is a command line OMX file validation tool used to validate OMX files against the specification. The tool is added to the system PATH when the package is installed and can be run as follows: 126 | 127 | ``` 128 | omx-validate my_file.omx 129 | ``` 130 | 131 | # Usage Notes 132 | 133 | ### File Objects 134 | 135 | OMX File objects extend Pytables.File, so all Pytables functions work normally. We've also added some useful stuff to make things even easier. 136 | 137 | ### Writing Data 138 | 139 | Writing data to an OMX file is simple: You must provide a name, and you must provide either an existing numpy (or python) array, or a shape and an "atom". You can optionally provide a descriptive title, a list of tags, and other implementation minutiae. 140 | 141 | The easiest way to do all that is to use python dictionary nomenclature: 142 | 143 | ```python 144 | myfile['matrixname'] = mynumpyobject 145 | ``` 146 | 147 | will call createMatrix() for you and populate it with the specified array. 148 | 149 | ### Accessing Data 150 | 151 | You can access matrix objects by name, using dictionary lookup e.g. `myfile['hwydist']` or using PyTables path notation, e.g. `myfile.root.hwydist` 152 | 153 | ### Matrix objects 154 | 155 | OMX matrices extend numpy arrays. An OMX matrix object extends a Pytables/HDF5 "node" which means all HDF5 methods and properties behave normally. Generally these datasets are going to be numpy CArray objects of arbitrary shape. 156 | You can access a matrix object by name using: 157 | 158 | * dictionary syntax, e.g. `myfile['hwydist']` 159 | * or by Pytables path syntax, e.g. `myfile.root.hwydist` 160 | 161 | Once you have a matrix object, you can perform normal numpy math on it or you can access rows and columns pythonically: 162 | 163 | ```python 164 | myfile['biketime'][0][0] = 0.60 * myfile['bikedist'][0][0] 165 | total_trips = numpy.sum(myfile.root.trips)` 166 | ``` 167 | 168 | ### Properties 169 | Every Matrix has its own dictionary of key/value pair attributes (properties) which can be accessed using the standard Pytables .attrs field. Add as many attributes as you like; attributes can be string, ints, floats, and lists: 170 | 171 | ```python 172 | print mymatrix.attrs 173 | print mymatrix.attrs.myfield 174 | print mymatrix.attrs['myfield'] 175 | ``` 176 | 177 | ### Tags 178 | 179 | If you create tags for your objects, you can also look up matrices by those tags. You can assign tags to any matrix using the 'tags' property attribute. Tags are a list of strings, e.g. ['skims','am','hwy']. To retrieve the list of matrices that matches a given set of tags, pass in a tuple of tags when using dictionary-style lookups: 180 | 181 | ```python 182 | list_all_hwy_skims = mybigfile[ ('skims','hwy') ] 183 | ``` 184 | 185 | This will always return a list (which can be empty). A matrix will only be included in the returned list if ALL tags specified match exactly. Tags are case-sensitive. 186 | 187 | ### Mappings 188 | 189 | A mapping allows rows and columns to be accessed using an integer value other than a zero-based offset. For instance zone numbers often start at "1" not "0", and there can be significant gaps between zone numbers; they're rarely fully sequential. An OMX file can contain multiple mappings. 190 | 191 | * Use the dictionary from mapping() to translate from an key value to a matrix lookup offset, e.g. `taznumber[1] -> matrix[0]` 192 | * Use the list from mapentries() to translate the other way; i.e. from an offset to an index value, e.g. `matrix[0] -> 1` (where 1 is the TAZ number). 193 | 194 | 195 | # API Reference 196 | 197 | ## Global Properties 198 | 199 | ### `__version__` 200 | OMX module version string. Currently '0.3.5' as of this writing. This is the Python API version. 201 | 202 | ### `__omx_version__` 203 | OMX file format version. Currently '0.2'. This is the OMX file format specification that omx-python adheres to. 204 | 205 | ### `open_file`(filename, mode='r', title='', root_uep='/', filters=Filters(complevel=1, complib='zlib', shuffle=True, bitshuffle=False, fletcher32=False, least_significant_digit=None), shape=None, **kwargs) 206 | Open or create a new OMX file. New files will be created with default 207 | zlib compression enabled. 208 | 209 | Parameters 210 | ---------- 211 | filename : string 212 | Name or path and name of file 213 | mode : string 214 | 'r' for read-only; 215 | 'w' to write (erases existing file); 216 | 'a' to read/write an existing file (will create it if doesn't exist). 217 | Ignored in read-only mode. 218 | title : string 219 | Short description of this file, used when creating the file. Default is ''. 220 | Ignored in read-only mode. 221 | filters : tables.Filters 222 | HDF5 default filter options for compression, shuffling, etc. Default for 223 | OMX standard file format is: zlib compression level 1, and shuffle=True. 224 | Only specify this if you want something other than the recommended standard 225 | HDF5 zip compression. 226 | 'None' will create enormous uncompressed files. 227 | Only 'zlib' compression is guaranteed to be available on all HDF5 implementations. 228 | See HDF5 docs for more detail. 229 | shape: numpy.array 230 | Shape of matrices in this file. Default is None. Specify a valid shape 231 | (e.g. (1200,1200)) to enforce shape-checking for all added objects. 232 | If shape is not specified, the first added matrix will not be shape-checked 233 | and all subsequently added matrices must match the shape of the first matrix. 234 | All tables in an OMX file must have the same shape. 235 | 236 | Returns 237 | ------- 238 | f : openmatrix.File 239 | The file object for reading and writing. 240 | 241 | ## File Objects 242 | 243 | ### `create_mapping`(self, title, entries, overwrite=False) 244 | Create an equivalency index, which maps a raw data dimension to 245 | another integer value. Once created, mappings can be referenced by 246 | offset or by key. 247 | 248 | Parameters: 249 | ----------- 250 | title : string 251 | Name of this mapping 252 | entries : list 253 | List of n equivalencies for the mapping. n must match one data 254 | dimension of the matrix. 255 | overwrite : boolean 256 | True to allow overwriting an existing mapping, False will raise 257 | a LookupError if the mapping already exists. Default is False. 258 | 259 | Returns: 260 | -------- 261 | mapping : tables.array 262 | Returns the created mapping. 263 | 264 | Raises: 265 | LookupError : if the mapping exists and overwrite=False 266 | 267 | ### `create_matrix`(self, name, atom=None, shape=None, title='', filters=None, chunkshape=None, byteorder=None, createparents=False, obj=None, attrs=None) 268 | Create an OMX Matrix (CArray) at the root level. User must pass in either 269 | an existing numpy matrix, or a shape and an atom type. 270 | 271 | Parameters 272 | ---------- 273 | name : string 274 | The name of this matrix. Stored in HDF5 as the leaf name. 275 | title : string 276 | Short description of this matrix. Default is ''. 277 | obj : numpy.CArray 278 | Existing numpy array from which to create this OMX matrix. If obj is passed in, 279 | then shape and atom can be left blank. If obj is not passed in, then a shape and 280 | atom must be specified instead. Default is None. 281 | shape : numpy.array 282 | Optional shape of the matrix. Shape is an int32 numpy array of format (rows,columns). 283 | If shape is not specified, an existing numpy CArray must be passed in instead, 284 | as the 'obj' parameter. Default is None. 285 | atom : atom_type 286 | Optional atom type of the data. Can be int32, float32, etc. Default is None. 287 | If None specified, then obj parameter must be passed in instead. 288 | filters : tables.Filters 289 | Set of HDF5 filters (compression, etc) used for creating the matrix. 290 | Default is None. See HDF5 documentation for details. Note: while the default here 291 | is None, the default set of filters set at the OMX parent file level is 292 | zlib compression level 1. Those settings usually trickle down to the table level. 293 | attrs : dict 294 | Dictionary of attribute names and values to be attached to this matrix. 295 | Default is None. 296 | 297 | Returns 298 | ------- 299 | matrix : tables.carray 300 | HDF5 CArray matrix 301 | 302 | ### `delete_mapping`(self, title) 303 | Remove a mapping. 304 | 305 | Raises: 306 | ------- 307 | LookupError : if the specified mapping does not exist. 308 | 309 | ### `list_all_attributes`(self) 310 | Return set of all attributes used for any Matrix in this File 311 | 312 | Returns 313 | ------- 314 | all_attributes : set 315 | The combined set of all attribute names that exist on any matrix in this file. 316 | 317 | ### `list_mappings`(self) 318 | List all mappings in this file 319 | 320 | Returns: 321 | -------- 322 | mappings : list 323 | List of the names of all mappings in the OMX file. Mappings 324 | are stored internally in the 'lookup' subset of the HDF5 file 325 | structure. Returns empty list if there are no mappings. 326 | 327 | ### `list_matrices`(self) 328 | List the matrix names in this File 329 | 330 | Returns 331 | ------- 332 | matrices : list 333 | List of all matrix names stored in this OMX file. 334 | 335 | ### `map_entries`(self, title) 336 | Return a list of entries for the specified mapping. 337 | Throws LookupError if the specified mapping does not exist. 338 | 339 | ### `mapping`(self, title) 340 | Return dict containing key:value pairs for specified mapping. Keys 341 | represent the map item and value represents the array offset. 342 | 343 | Parameters: 344 | ----------- 345 | title : string 346 | Name of the mapping to be returned 347 | 348 | Returns: 349 | -------- 350 | mapping : dict 351 | Dictionary where each key is the map item, and the value 352 | represents the array offset. 353 | 354 | Raises: 355 | ------- 356 | LookupError : if the specified mapping does not exist. 357 | 358 | ### `shape`(self) 359 | Get the one and only shape of all matrices in this File 360 | 361 | Returns 362 | ------- 363 | shape : tuple 364 | Tuple of (rows,columns) for this matrix and file. 365 | 366 | ### `version`(self) 367 | Return the OMX file format of this OMX file, embedded in the OMX_VERSION file attribute. 368 | Returns None if the OMX_VERSION attribute is not set. 369 | 370 | 371 | ## Exceptions 372 | * LookupError 373 | * ShapeError 374 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | ================== 2 | OpenMatrix, or OMX 3 | ================== 4 | 5 | OMX is an open matrix data format, designed for sharing big matrix 6 | data. 7 | 8 | Read more about it at the project home page: 9 | https://github.com/osPlanning/omx 10 | 11 | -------------------------------------------------------------------------------- /example/python-omx-sample.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import openmatrix as omx 3 | import numpy as np 4 | 5 | # Create some data 6 | ones = np.ones((100,100)) 7 | twos = 2.0*ones 8 | 9 | 10 | # Create an OMX file (will overwrite existing file!) 11 | print('Creating myfile.omx') 12 | myfile = omx.open_file('myfile.omx','w') # use 'a' to append/edit an existing file 13 | 14 | 15 | # Write to the file. 16 | myfile['m1'] = ones 17 | myfile['m2'] = twos 18 | myfile['m3'] = ones + twos # numpy array math is fast 19 | myfile.close() 20 | 21 | 22 | # Open an OMX file for reading only 23 | print('Reading myfile.omx') 24 | myfile = omx.open_file('myfile.omx') 25 | 26 | print ('Shape:', myfile.shape()) # (100,100) 27 | print ('Number of tables:', len(myfile)) # 3 28 | print ('Table names:', myfile.list_matrices()) # ['m1','m2',',m3'] 29 | 30 | 31 | # Work with data. Pass a string to select matrix by name: 32 | # ------------------------------------------------------- 33 | m1 = myfile['m1'] 34 | m2 = myfile['m2'] 35 | m3 = myfile['m3'] 36 | 37 | # halves = m1 * 0.5 # CRASH! Don't modify an OMX object directly. 38 | # # Create a new numpy array, and then edit it. 39 | halves = np.array(m1) * 0.5 40 | 41 | first_row = m2[0] 42 | first_row[:] = 0.5 * first_row[:] 43 | 44 | my_very_special_zone_value = m2[10][25] 45 | 46 | 47 | # FANCY: Use attributes to find matrices 48 | # -------------------------------------- 49 | myfile.close() # was opened read-only, so let's reopen. 50 | myfile = omx.open_file('myfile.omx','a') # append mode: read/write existing file 51 | 52 | myfile['m1'].attrs.timeperiod = 'am' 53 | myfile['m1'].attrs.mode = 'hwy' 54 | 55 | myfile['m2'].attrs.timeperiod = 'md' 56 | 57 | myfile['m3'].attrs.timeperiod = 'am' 58 | myfile['m3'].attrs.mode = 'trn' 59 | 60 | print('attributes:', myfile.list_all_attributes()) # ['mode','timeperiod'] 61 | 62 | # Use a DICT to select matrices via attributes: 63 | 64 | all_am_trips = myfile[ {'timeperiod':'am'} ] # [m1,m3] 65 | all_hwy_trips = myfile[ {'mode':'hwy'} ] # [m1] 66 | all_am_trn_trips = myfile[ {'mode':'trn','timeperiod':'am'} ] # [m3] 67 | 68 | print('sum of some tables:', np.sum(all_am_trips)) 69 | 70 | 71 | # SUPER FANCY: Create a mapping to use TAZ numbers instead of matrix offsets 72 | # -------------------------------------------------------------------------- 73 | # (any mapping would work, such as a mapping with large gaps between zone 74 | # numbers. For this simple case we'll just assume TAZ numbers are 1-100.) 75 | 76 | taz_equivs = np.arange(1,101) # 1-100 inclusive 77 | 78 | myfile.create_mapping('taz', taz_equivs) 79 | print('mappings:', myfile.list_mappings()) # ['taz'] 80 | 81 | tazs = myfile.mapping('taz') # Returns a dict: {1:0, 2:1, 3:2, ..., 100:99} 82 | 83 | m3 = myfile['m3'] 84 | 85 | print('cell value:', m3[tazs[100]][tazs[100]]) # 3.0 (taz (100,100) is cell [99][99]) 86 | 87 | myfile.close() 88 | 89 | -------------------------------------------------------------------------------- /openmatrix/Exceptions.py: -------------------------------------------------------------------------------- 1 | class ShapeError(Exception): 2 | pass 3 | 4 | -------------------------------------------------------------------------------- /openmatrix/File.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import tables # requires pytables >= 3.1 3 | 4 | from .Exceptions import * 5 | 6 | 7 | class File(tables.File): 8 | """ 9 | OMX File class, which contains all the methods for adding, removing, manipulating tables 10 | and mappings in an OMX file. 11 | """ 12 | 13 | def __init__(self, f,m,t,r,f1, **kwargs): 14 | tables.File.__init__(self,f,m,t,r,f1,**kwargs) 15 | self._shape = None 16 | 17 | def version(self): 18 | """ 19 | Return the OMX file format of this OMX file, embedded in the OMX_VERSION file attribute. 20 | Returns None if the OMX_VERSION attribute is not set. 21 | """ 22 | if 'OMX_VERSION' in self.root._v_attrs: 23 | return self.root._v_attrs['OMX_VERSION'] 24 | else: 25 | return None 26 | 27 | 28 | def create_matrix(self, name, atom=None, shape=None, title='', filters=None, 29 | chunkshape=None, byteorder=None, createparents=False, obj=None, 30 | attrs=None): 31 | """ 32 | Create an OMX Matrix (CArray) at the root level. User must pass in either 33 | an existing numpy matrix, or a shape and an atom type. 34 | 35 | Parameters 36 | ---------- 37 | name : string 38 | The name of this matrix. Stored in HDF5 as the leaf name. 39 | title : string 40 | Short description of this matrix. Default is ''. 41 | obj : numpy.CArray 42 | Existing numpy array from which to create this OMX matrix. If obj is passed in, 43 | then shape and atom can be left blank. If obj is not passed in, then a shape and 44 | atom must be specified instead. Default is None. 45 | shape : numpy.array 46 | Optional shape of the matrix. Shape is an int32 numpy array of format (rows,columns). 47 | If shape is not specified, an existing numpy CArray must be passed in instead, 48 | as the 'obj' parameter. Default is None. 49 | atom : atom_type 50 | Optional atom type of the data. Can be int32, float32, etc. Default is None. 51 | If None specified, then obj parameter must be passed in instead. 52 | filters : tables.Filters 53 | Set of HDF5 filters (compression, etc) used for creating the matrix. 54 | Default is None. See HDF5 documentation for details. Note: while the default here 55 | is None, the default set of filters set at the OMX parent file level is 56 | zlib compression level 1. Those settings usually trickle down to the table level. 57 | attrs : dict 58 | Dictionary of attribute names and values to be attached to this matrix. 59 | Default is None. 60 | 61 | Returns 62 | ------- 63 | matrix : tables.carray 64 | HDF5 CArray matrix 65 | """ 66 | 67 | # If object was passed in, make sure its shape is correct 68 | if self.shape() is not None and obj is not None and obj.shape != self.shape(): 69 | raise ShapeError('%s has shape %s but this file requires shape %s' % 70 | (name, obj.shape, self.shape())) 71 | 72 | matrix = self.create_carray(self.root.data, name, atom, shape, title, filters, 73 | chunkshape, byteorder, createparents, obj) 74 | 75 | # Store shape if we don't have one yet 76 | if self._shape is None: 77 | storeshape = np.array([matrix.shape[0],matrix.shape[1]], dtype='int32') 78 | self.root._v_attrs['SHAPE'] = storeshape 79 | self._shape = matrix.shape 80 | 81 | # attributes 82 | if attrs: 83 | for key in attrs: 84 | matrix.attrs[key] = attrs[key] 85 | 86 | return matrix 87 | 88 | def shape(self): 89 | """ 90 | Get the one and only shape of all matrices in this File 91 | 92 | Returns 93 | ------- 94 | shape : tuple 95 | Tuple of (rows,columns) for this matrix and file. 96 | """ 97 | 98 | # If we already have the shape, just return it 99 | if self._shape: 100 | return self._shape 101 | 102 | # If shape is already set in root node attributes, grab it 103 | if 'SHAPE' in self.root._v_attrs: 104 | # Shape is stored as a numpy.array: 105 | arrayshape = self.root._v_attrs['SHAPE'] 106 | # which must be converted to a tuple: 107 | realshape = (arrayshape[0],arrayshape[1]) 108 | self._shape = realshape 109 | return self._shape 110 | 111 | # Inspect the first CArray object to determine its shape 112 | if len(self) > 0: 113 | # jwd: generator has no next funtion in python 3 114 | # next() function supported in both in python 2.6+ and python 3 115 | self._shape = next(self.iter_nodes(self.root.data,'CArray')).shape 116 | 117 | # Store it if we can 118 | if self._iswritable(): 119 | storeshape = np.array( 120 | [self._shape[0],self._shape[1]], 121 | dtype='int32') 122 | self.root._v_attrs['SHAPE'] = storeshape 123 | 124 | return self._shape 125 | 126 | else: 127 | return None 128 | 129 | 130 | def list_matrices(self): 131 | """ 132 | List the matrix names in this File 133 | 134 | Returns 135 | ------- 136 | matrices : list 137 | List of all matrix names stored in this OMX file. 138 | """ 139 | return [node.name for node in self.list_nodes(self.root.data,'CArray')] 140 | 141 | 142 | def list_all_attributes(self): 143 | """ 144 | Return set of all attributes used for any Matrix in this File 145 | 146 | Returns 147 | ------- 148 | all_attributes : set 149 | The combined set of all attribute names that exist on any matrix in this file. 150 | """ 151 | all_tags = set() 152 | for m in self.iter_nodes(self.root.data, 'CArray'): 153 | all_tags.update(m.attrs._v_attrnamesuser) 154 | return sorted(all_tags) 155 | 156 | 157 | # MAPPINGS ----------------------------------------------- 158 | def list_mappings(self): 159 | """ 160 | List all mappings in this file 161 | 162 | Returns: 163 | -------- 164 | mappings : list 165 | List of the names of all mappings in the OMX file. Mappings 166 | are stored internally in the 'lookup' subset of the HDF5 file 167 | structure. Returns empty list if there are no mappings. 168 | """ 169 | try: 170 | return [m.name for m in self.list_nodes(self.root.lookup)] 171 | except: 172 | return [] 173 | 174 | 175 | def delete_mapping(self, title): 176 | """ 177 | Remove a mapping. 178 | 179 | Raises: 180 | ------- 181 | LookupError : if the specified mapping does not exist. 182 | """ 183 | 184 | try: 185 | self.remove_node(self.root.lookup, title) 186 | except: 187 | raise LookupError('No such mapping: '+title) 188 | 189 | 190 | def mapping(self, title): 191 | """ 192 | Return dict containing key:value pairs for specified mapping. Keys 193 | represent the map item and value represents the array offset. 194 | 195 | Parameters: 196 | ----------- 197 | title : string 198 | Name of the mapping to be returned 199 | 200 | Returns: 201 | -------- 202 | mapping : dict 203 | Dictionary where each key is the map item, and the value 204 | represents the array offset. 205 | 206 | Raises: 207 | ------- 208 | LookupError : if the specified mapping does not exist. 209 | """ 210 | 211 | try: 212 | # fetch entries 213 | entries = [] 214 | entries.extend(self.get_node(self.root.lookup, title)[:]) 215 | 216 | # build reverse key-lookup 217 | keymap = {} 218 | for i in range(len(entries)): 219 | keymap[entries[i]] = i 220 | 221 | return keymap 222 | 223 | except: 224 | raise LookupError('No such mapping: '+title) 225 | 226 | def map_entries(self, title): 227 | """Return a list of entries for the specified mapping. 228 | Throws LookupError if the specified mapping does not exist. 229 | """ 230 | try: 231 | # fetch entries 232 | entries = [] 233 | entries.extend(self.get_node(self.root.lookup, title)[:]) 234 | 235 | return entries 236 | 237 | except: 238 | raise LookupError('No such mapping: '+title) 239 | 240 | 241 | def create_mapping(self, title, entries, overwrite=False): 242 | """ 243 | Create an equivalency index, which maps a raw data dimension to 244 | another integer value. Once created, mappings can be referenced by 245 | offset or by key. 246 | 247 | Parameters: 248 | ----------- 249 | title : string 250 | Name of this mapping 251 | entries : list 252 | List of n equivalencies for the mapping. n must match one data 253 | dimension of the matrix. 254 | overwrite : boolean 255 | True to allow overwriting an existing mapping, False will raise 256 | a LookupError if the mapping already exists. Default is False. 257 | 258 | Returns: 259 | -------- 260 | mapping : tables.array 261 | Returns the created mapping. 262 | 263 | Raises: 264 | LookupError : if the mapping exists and overwrite=False 265 | """ 266 | 267 | # Enforce shape-checking 268 | if self.shape(): 269 | if not len(entries) in self._shape: 270 | raise ShapeError('Mapping must match one data dimension') 271 | 272 | # Handle case where mapping already exists: 273 | if title in self.list_mappings(): 274 | if overwrite: 275 | self.delete_mapping(title) 276 | else: 277 | raise LookupError(title+' mapping already exists.') 278 | 279 | # Create lookup group under root if it doesn't already exist. 280 | if 'lookup' not in self.root: 281 | self.create_group(self.root, 'lookup') 282 | 283 | # Write the mapping! 284 | mymap = self.create_array(self.root.lookup, title, atom=tables.UInt32Atom(), 285 | shape=(len(entries),) ) 286 | mymap[:] = entries 287 | 288 | return mymap 289 | 290 | 291 | # The following functions implement Python list/dictionary lookups. ---- 292 | def __getitem__(self,key): 293 | """Return a matrix by name, or a list of matrices by attributes""" 294 | 295 | if isinstance(key, str): 296 | return self.get_node(self.root.data, key) 297 | 298 | if 'keys' not in dir(key): 299 | raise LookupError('Key %s not found' % key) 300 | 301 | # Loop through key/value pairs 302 | mats = self.list_nodes(self.root.data, 'CArray') 303 | for a in key.keys(): 304 | mats = self._getMatricesByAttribute(a, key[a], mats) 305 | 306 | return mats 307 | 308 | 309 | def _getMatricesByAttribute(self, key, value, matrices=None): 310 | 311 | answer = [] 312 | 313 | if matrices is None: 314 | matrices = self.list_nodes(self.root.data,'CArray') 315 | 316 | for m in matrices: 317 | if m.attrs is None: 318 | continue 319 | 320 | # Only test if key is present in matrix attributes 321 | if key in m.attrs._v_attrnames and m.attrs[key] == value: 322 | answer.append(m) 323 | 324 | return answer 325 | 326 | 327 | def __len__(self): 328 | return len(self.list_nodes(self.root.data, 'CArray')) 329 | 330 | 331 | def __setitem__(self, key, dataset): 332 | # We need to determine atom and shape from the object that's been passed in. 333 | # This assumes 'dataset' is a numpy object. 334 | atom = tables.Atom.from_dtype(dataset.dtype) 335 | shape = dataset.shape 336 | 337 | #checks to see if it is already a tables instance, and if so, just copies it 338 | if dataset.__class__.__name__ == 'CArray': 339 | return dataset.copy(self.root.data, key) 340 | else: 341 | return self.create_matrix(key, atom, shape, obj=dataset) 342 | 343 | 344 | def __delitem__(self, key): 345 | self.remove_node(self.root.data, key) 346 | 347 | 348 | def __iter__(self): 349 | """Iterate over the keys in this container""" 350 | return self.iter_nodes(self.root.data, 'CArray') 351 | 352 | 353 | def __contains__(self, item): 354 | return item in self.root.data._v_children 355 | 356 | # BACKWARD COMPATIBILITY: 357 | # PyTables switched from camelCaseMethods to camel_case_methods 358 | # We follow suit, and keep old methods for backward compat: 359 | createMapping = create_mapping 360 | createMatrix = create_matrix 361 | deleteMapping = delete_mapping 362 | listMatrices = list_matrices 363 | listAllAttributes = list_all_attributes 364 | listMappings = list_mappings 365 | mapentries = map_entries 366 | mapEntries = map_entries 367 | 368 | -------------------------------------------------------------------------------- /openmatrix/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import tables 4 | import numpy as np 5 | 6 | from .File import * 7 | from .Exceptions import * 8 | 9 | # GLOBAL VARIABLES ----------- 10 | __version__ = '0.3.3' 11 | __omx_version__ = b'0.2' 12 | 13 | # GLOBAL FUNCTIONS ----------- 14 | def open_file(filename, mode='r', title='', root_uep='/', 15 | filters=tables.Filters(complevel=1, shuffle=True, fletcher32=False, complib='zlib'), 16 | shape=None, **kwargs): 17 | """ 18 | Open or create a new OMX file. New files will be created with default 19 | zlib compression enabled. 20 | 21 | Parameters 22 | ---------- 23 | filename : string 24 | Name or path and name of file 25 | mode : string 26 | 'r' for read-only; 27 | 'w' to write (erases existing file); 28 | 'a' to read/write an existing file (will create it if doesn't exist). 29 | Ignored in read-only mode. 30 | title : string 31 | Short description of this file, used when creating the file. Default is ''. 32 | Ignored in read-only mode. 33 | filters : tables.Filters 34 | HDF5 default filter options for compression, shuffling, etc. Default for 35 | OMX standard file format is: zlib compression level 1, and shuffle=True. 36 | Only specify this if you want something other than the recommended standard 37 | HDF5 zip compression. 38 | 'None' will create enormous uncompressed files. 39 | Only 'zlib' compression is guaranteed to be available on all HDF5 implementations. 40 | See HDF5 docs for more detail. 41 | shape: array-like 42 | Shape of matrices in this file. Default is None. Specify a valid shape 43 | (e.g. (1000,1200)) to enforce shape-checking for all added objects. 44 | If shape is not specified, the first added matrix will not be shape-checked 45 | and all subsequently added matrices must match the shape of the first matrix. 46 | All tables in an OMX file must have the same shape. 47 | 48 | Returns 49 | ------- 50 | f : openmatrix.File 51 | The file object for reading and writing. 52 | """ 53 | f = File(filename, mode, title, root_uep, filters, **kwargs); 54 | 55 | # add omx structure if file is writable 56 | if mode != 'r': 57 | # version number 58 | if 'OMX_VERSION' not in f.root._v_attrs: 59 | f.root._v_attrs['OMX_VERSION'] = __omx_version__ 60 | if 'OMX_CREATED_WITH' not in f.root._v_attrs: 61 | f.root._v_attrs['OMX_CREATED_WITH'] = 'python omx ' + __version__ 62 | 63 | # shape 64 | if shape: 65 | storeshape = np.array([shape[0],shape[1]], dtype='int32') 66 | f.root._v_attrs['SHAPE'] = storeshape 67 | 68 | # /data and /lookup folders 69 | if 'data' not in f.root: 70 | f.create_group(f.root,"data") 71 | if 'lookup' not in f.root: 72 | f.create_group(f.root,"lookup") 73 | 74 | return f 75 | 76 | 77 | if __name__ == "__main__": 78 | print('OMX!') 79 | 80 | -------------------------------------------------------------------------------- /openmatrix/test/test_file.py: -------------------------------------------------------------------------------- 1 | import os 2 | import tempfile 3 | 4 | import numpy as np 5 | import numpy.testing as npt 6 | import tables 7 | 8 | import openmatrix as omx 9 | 10 | import nose.tools as nt 11 | 12 | TEST_FILE = None 13 | 14 | 15 | def ones5x5(): 16 | return np.ones((5, 5)) 17 | 18 | 19 | def add_m1_node(f): 20 | f.create_matrix('m1', obj=ones5x5()) 21 | 22 | 23 | def setup_func(): 24 | global TEST_FILE 25 | 26 | if TEST_FILE is not None and os.path.isfile(TEST_FILE): 27 | os.remove(TEST_FILE) 28 | 29 | with tempfile.NamedTemporaryFile(suffix='.omx') as tmp: 30 | TEST_FILE = tmp.name 31 | 32 | 33 | def teardown_func(): 34 | if TEST_FILE is not None and os.path.isfile(TEST_FILE): 35 | os.remove(TEST_FILE) 36 | 37 | 38 | @nt.with_setup(setup_func, teardown_func) 39 | def test_create_file(): 40 | with omx.open_file(TEST_FILE, 'w'): 41 | pass 42 | assert os.path.isfile(TEST_FILE) 43 | 44 | 45 | @nt.with_setup(setup_func, teardown_func) 46 | def test_open_readonly_hdf5_file(): 47 | with tables.open_file(TEST_FILE, 'w'): 48 | pass 49 | 50 | assert os.path.isfile(TEST_FILE) 51 | 52 | with omx.open_file(TEST_FILE, 'r'): 53 | pass 54 | 55 | 56 | @nt.with_setup(setup_func, teardown_func) 57 | def test_set_get_del(): 58 | with omx.open_file(TEST_FILE, 'w') as f: 59 | add_m1_node(f) 60 | npt.assert_array_equal(f['m1'], ones5x5()) 61 | nt.assert_equal(f.shape(), (5, 5)) 62 | del f['m1'] 63 | nt.assert_not_in('m1', f) 64 | 65 | 66 | @nt.with_setup(setup_func, teardown_func) 67 | def test_add_numpy_matrix_using_brackets(): 68 | with omx.open_file(TEST_FILE, 'w') as f: 69 | f['m1'] = ones5x5() 70 | npt.assert_array_equal(f['m1'], ones5x5()) 71 | nt.assert_equal(f.shape(), (5, 5)) 72 | 73 | # test check for shape matching 74 | with nt.assert_raises(omx.Exceptions.ShapeError): 75 | f.create_matrix('m2', obj=np.ones((8, 8))) 76 | 77 | 78 | @nt.with_setup(setup_func, teardown_func) 79 | def test_add_numpy_matrix_using_create_matrix(): 80 | with omx.open_file(TEST_FILE, 'w') as f: 81 | f.create_matrix('m1', obj=ones5x5()) 82 | npt.assert_array_equal(f['m1'], ones5x5()) 83 | nt.assert_equal(f.shape(), (5, 5)) 84 | 85 | 86 | @nt.with_setup(setup_func, teardown_func) 87 | @nt.raises(tables.FileModeError) 88 | def test_add_matrix_to_readonly_file(): 89 | with omx.open_file(TEST_FILE, 'w') as f: 90 | f['m2'] = np.ones((5, 5)) 91 | 92 | with omx.open_file(TEST_FILE, 'r') as f: 93 | f.create_matrix('m1', obj=np.ones((5, 5))) 94 | 95 | 96 | @nt.with_setup(setup_func, teardown_func) 97 | @nt.raises(tables.NodeError) 98 | def test_add_matrix_with_same_name(): 99 | with omx.open_file(TEST_FILE, 'w') as f: 100 | add_m1_node(f) 101 | # now add m1 again: 102 | add_m1_node(f) 103 | 104 | 105 | @nt.with_setup(setup_func, teardown_func) 106 | def test_get_length_of_file(): 107 | with omx.open_file(TEST_FILE, 'w') as f: 108 | f['m1'] = np.ones((5, 5)) 109 | f['m2'] = np.ones((5, 5)) 110 | f['m3'] = np.ones((5, 5)) 111 | f['m4'] = np.ones((5, 5)) 112 | f['m5'] = np.ones((5, 5)) 113 | nt.assert_equal(len(f), 5) 114 | nt.assert_equal(len(f.list_matrices()), 5) 115 | 116 | 117 | @nt.with_setup(setup_func, teardown_func) 118 | def test_len_list_iter(): 119 | names = ['m{}'.format(x) for x in range(5)] 120 | with omx.open_file(TEST_FILE, 'w') as f: 121 | for m in names: 122 | f[m] = ones5x5() 123 | 124 | for mat in f: 125 | npt.assert_array_equal(mat, ones5x5()) 126 | 127 | nt.assert_equal(len(f), len(names)) 128 | nt.assert_equal(f.list_matrices(), names) 129 | 130 | 131 | @nt.with_setup(setup_func, teardown_func) 132 | def test_contains(): 133 | with omx.open_file(TEST_FILE, 'w') as f: 134 | add_m1_node(f) 135 | nt.assert_in('m1', f) 136 | # keep this here to be sure we're actually running 137 | # File.__contains__ 138 | assert 'm1' in f 139 | 140 | 141 | @nt.with_setup(setup_func, teardown_func) 142 | def test_list_all_attrs(): 143 | with omx.open_file(TEST_FILE, 'w') as f: 144 | add_m1_node(f) 145 | f['m2'] = ones5x5() 146 | 147 | nt.assert_equal(f.list_all_attributes(), []) 148 | 149 | f['m1'].attrs['a1'] = 'a1' 150 | f['m1'].attrs['a2'] = 'a2' 151 | f['m2'].attrs['a2'] = 'a2' 152 | f['m2'].attrs['a3'] = 'a3' 153 | 154 | nt.assert_equal(f.list_all_attributes(), ['a1', 'a2', 'a3']) 155 | 156 | 157 | @nt.with_setup(setup_func, teardown_func) 158 | def test_matrices_by_attr(): 159 | with omx.open_file(TEST_FILE, 'w') as f: 160 | f['m1'] = ones5x5() 161 | f['m2'] = ones5x5() 162 | f['m3'] = ones5x5() 163 | 164 | for m in f: 165 | m.attrs['a1'] = 'a1' 166 | m.attrs['a2'] = 'a2' 167 | f['m3'].attrs['a2'] = 'a22' 168 | f['m3'].attrs['a3'] = 'a3' 169 | 170 | gmba = f._getMatricesByAttribute 171 | 172 | nt.assert_equal(gmba('zz', 'zz'), []) 173 | nt.assert_equal(gmba('a1', 'a1'), [f['m1'], f['m2'], f['m3']]) 174 | nt.assert_equal(gmba('a2', 'a2'), [f['m1'], f['m2']]) 175 | nt.assert_equal(gmba('a2', 'a22'), [f['m3']]) 176 | nt.assert_equal(gmba('a3', 'a3'), [f['m3']]) 177 | 178 | 179 | @nt.with_setup(setup_func, teardown_func) 180 | def test_set_with_carray(): 181 | with omx.open_file(TEST_FILE, 'w') as f: 182 | f['m1'] = ones5x5() 183 | f['m2'] = f['m1'] 184 | npt.assert_array_equal(f['m2'], f['m1']) 185 | 186 | @nt.with_setup(setup_func, teardown_func) 187 | def test_mappings(): 188 | with omx.open_file(TEST_FILE, 'w') as f: 189 | taz_equivs = np.arange(1,4) 190 | f.create_mapping('taz', taz_equivs) 191 | 192 | tazs = f.mapping('taz') 193 | nt.assert_equal(tazs, {1:0, 2:1, 3:2}) 194 | nt.assert_raises(LookupError, f.mapping, 'missing') 195 | nt.assert_raises(TypeError, f.mapping) 196 | 197 | entries = f.map_entries('taz') 198 | nt.assert_equal(entries, [1, 2, 3]) 199 | nt.assert_raises(LookupError, f.map_entries, 'missing') 200 | nt.assert_raises(TypeError, f.map_entries) 201 | -------------------------------------------------------------------------------- /openmatrix/validator.py: -------------------------------------------------------------------------------- 1 | import os 2 | from . import open_file as _open_file 3 | 4 | def pass_or_fail(ok): 5 | return("Pass" if ok else "Fail") 6 | 7 | def open_file(filename): 8 | mat_file = _open_file(filename, "r") 9 | print("File contents:", filename) 10 | print(mat_file) 11 | return(mat_file) 12 | 13 | def check1(mat_file, required=True, checknum=1): 14 | try: 15 | print('\nCheck 1: Has OMX_VERSION attribute set to 0.2') 16 | ok = mat_file.root._v_attrs['OMX_VERSION'] == b'0.2' 17 | print(" File version is 0.2:", pass_or_fail(ok)) 18 | return(ok, required, checknum) 19 | except Exception as err: 20 | return (False, required, checknum, str(err)) 21 | 22 | def check2(mat_file, required=True, checknum=2): 23 | try: 24 | print('\nCheck 2: Has SHAPE array attribute set to two item integer array') 25 | ok = len(mat_file.root._v_attrs['SHAPE']) == 2 26 | print(" Length is 2:", pass_or_fail(ok)) 27 | ok_2 = int(mat_file.root._v_attrs['SHAPE'][0]) == mat_file.root._v_attrs['SHAPE'][0] 28 | print(" First item is integer:", pass_or_fail(ok_2)) 29 | ok_3 = int(mat_file.root._v_attrs['SHAPE'][1]) == mat_file.root._v_attrs['SHAPE'][1] 30 | print(" Second item is integer:", pass_or_fail(ok_3)) 31 | print(' Shape:', mat_file.shape()) 32 | return(ok * ok_2 * ok_3, required, checknum) 33 | except Exception as err: 34 | return (False, required, checknum, str(err)) 35 | 36 | def check3(mat_file, required=True, checknum=3): 37 | try: 38 | print('\nCheck 3: Has data group for matrices') 39 | ok = 'data' in map(lambda x: x._v_name, mat_file.list_nodes("/")) 40 | print(" Group:", pass_or_fail(ok)) 41 | print(' Number of Matrices:', len(mat_file)) 42 | print(' Matrix names:', mat_file.list_matrices()) 43 | return(ok, required, checknum) 44 | except Exception as err: 45 | return (False, required, checknum, str(err)) 46 | 47 | def check4(mat_file, required=True, checknum=4): 48 | try: 49 | print("\nCheck 4: Matrix shape matches file shape") 50 | ok = True 51 | for matrix in mat_file.list_matrices(): 52 | ok_2 = (mat_file[matrix].shape == mat_file.root._v_attrs['SHAPE']).all() 53 | print(" Matrix shape: ", matrix, ":", mat_file[matrix].shape, ":", pass_or_fail(ok_2)) 54 | ok = ok * ok_2 55 | return(ok, required, checknum) 56 | except Exception as err: 57 | return (False, required, checknum, str(err)) 58 | 59 | def check5(mat_file, required=True, checknum=5): 60 | try: 61 | print('\nCheck 5: Uses common data types (float or int) for matrices') 62 | ok = True 63 | for matrix in mat_file.list_matrices(): 64 | ok_2 = (mat_file[matrix].dtype == float) or (mat_file[matrix].dtype == int) 65 | print(" Matrix: ", matrix, ":", mat_file[matrix].dtype, ":", pass_or_fail(ok_2)) 66 | ok = ok * ok_2 67 | return(ok, required, checknum) 68 | except Exception as err: 69 | return (False, required, checknum, str(err)) 70 | 71 | def check6(mat_file, required=True, checknum=6): 72 | try: 73 | print('\nCheck 6: Matrices chunked for faster I/O') 74 | ok = True 75 | for matrix in mat_file.list_matrices(): 76 | ok_2 = True if mat_file[matrix].chunkshape is not None else False 77 | print(" Matrix chunkshape: ", matrix, ":", mat_file[matrix].chunkshape, ":", pass_or_fail(ok_2)) 78 | ok = ok * ok_2 79 | return(ok, required, checknum) 80 | except Exception as err: 81 | return (False, required, checknum, str(err)) 82 | 83 | def check7(mat_file, required=False, checknum=7): 84 | try: 85 | print('\nCheck 7: Uses zlib compression if compression used') 86 | ok = True 87 | for matrix in mat_file.list_matrices(): 88 | ok_2 = True if mat_file[matrix].filters.complib is not None else False 89 | if ok_2: 90 | ok_3 = mat_file[matrix].filters.complib == 'zlib' 91 | ok_2 = ok_2 * ok_3 92 | print(" Matrix compression library and level: ", matrix, ":", mat_file[matrix].filters.complib, ":", mat_file[matrix].filters.complevel, ":", pass_or_fail(ok_2)) 93 | ok = ok * ok_2 94 | return(ok, required, checknum) 95 | except Exception as err: 96 | return (False, required, checknum, str(err)) 97 | 98 | def check8(mat_file, required=False, checknum=8): 99 | try: 100 | print("\nCheck 8: Has NA attribute if desired (but not required)") 101 | ok = True 102 | for matrix in mat_file.list_matrices(): 103 | ok_2 = mat_file[matrix].attrs.__contains__("NA") 104 | print(" Matrix NA attribute: ", matrix, ":", pass_or_fail(ok_2)) 105 | ok = ok * ok_2 106 | return(ok, required, checknum) 107 | except Exception as err: 108 | return (False, required, checknum, str(err)) 109 | 110 | def check9(mat_file, required=False, checknum=9): 111 | try: 112 | print('\nCheck 9: Has lookup group for labels/indexes if desired (but not required)') 113 | ok = 'lookup' in map(lambda x: x._v_name, mat_file.list_nodes("/")) 114 | print(" Group:", pass_or_fail(ok)) 115 | if ok: 116 | print(' Number of Lookups:', len(mat_file.list_mappings())) 117 | print(' Lookups names:', mat_file.list_mappings()) 118 | return(ok, required, checknum) 119 | except Exception as err: 120 | return (False, required, checknum, str(err)) 121 | 122 | def check10(mat_file, required=False, checknum=10): 123 | try: 124 | print("\nCheck 10: Lookup shapes are 1-d and match file shape") 125 | ok = False 126 | if 'lookup' in map(lambda x: x._v_name, mat_file.list_nodes("/")): 127 | ok = True 128 | for lookup in mat_file.list_mappings(): 129 | this_shape = mat_file.get_node(mat_file.root.lookup, lookup).shape 130 | ok_2 = len(this_shape)==1 and this_shape[0] in mat_file.root._v_attrs['SHAPE'] 131 | print(" Lookup: ", lookup, ":", this_shape, ":", pass_or_fail(ok_2)) 132 | ok = ok * ok_2 133 | return(ok, required, checknum) 134 | except Exception as err: 135 | return (False, required, checknum, str(err)) 136 | 137 | def check11(mat_file, required=False, checknum=11): 138 | try: 139 | print('\nCheck 11: Uses common data types (int or str) for lookups') 140 | is_int = lambda x: x == int 141 | ok = False 142 | if 'lookup' in map(lambda x: x._v_name, mat_file.list_nodes("/")): 143 | ok = True 144 | for lookup in mat_file.list_mappings(): 145 | try: 146 | ok_2 = all(map(lambda x: x == int(x), mat_file.mapping(lookup).keys())) 147 | except ValueError: 148 | ok_2 = None 149 | if not ok_2: 150 | ok_2 = all(map(lambda x: x == str(x), mat_file.mapping(lookup).keys())) 151 | if not ok_2: 152 | ok_2 = all(map(lambda x: x == bytes(x), mat_file.mapping(lookup).keys())) 153 | this_dtype = mat_file.get_node(mat_file.root.lookup, lookup).dtype 154 | print(" Lookup: ", lookup, ":",this_dtype,":", pass_or_fail(ok_2)) 155 | ok = ok * ok_2 156 | return(ok, required, checknum) 157 | except Exception as err: 158 | return (False, required, checknum, str(err)) 159 | 160 | def check12(mat_file, required=False, checknum=12): 161 | try: 162 | print("\nCheck 12: Has Lookup DIM attribute of 0 (row) or 1 (column) if desired (but not required)") 163 | print(" Not supported at this time by the Python openmatrix package") 164 | ok = False 165 | if 'lookup' in map(lambda x: x._v_name, mat_file.list_nodes("/")): 166 | ok = False 167 | return(ok, required, checknum) 168 | except Exception as err: 169 | return (False, required, checknum, str(err)) 170 | 171 | 172 | def run_checks(filename): 173 | if not os.path.exists(filename): 174 | raise FileNotFoundError(filename) 175 | try: 176 | mat_file = open_file(filename) 177 | except: 178 | print("Unable to open", filename, "using HDF5") 179 | else: 180 | try: 181 | results = [] 182 | results.append(check1(mat_file)) 183 | results.append(check2(mat_file)) 184 | results.append(check3(mat_file)) 185 | results.append(check4(mat_file)) 186 | results.append(check5(mat_file)) 187 | results.append(check6(mat_file)) 188 | results.append(check7(mat_file)) 189 | results.append(check8(mat_file)) 190 | results.append(check9(mat_file)) 191 | results.append(check10(mat_file)) 192 | results.append(check11(mat_file)) 193 | results.append(check12(mat_file)) 194 | print("\nOverall result ") 195 | overall_ok = True 196 | for result in results: 197 | if len(result) == 4: 198 | print(" ERROR", result[3]) 199 | else: 200 | print(" Check", result[2], ":", "Required" if result[1] else "Not required", ":", pass_or_fail(result[0])) 201 | if result[1]: 202 | overall_ok = overall_ok * result[0] 203 | print(" Overall : ", pass_or_fail(overall_ok)) 204 | finally: 205 | mat_file.close() 206 | 207 | 208 | def command_line(): 209 | import argparse 210 | parser = argparse.ArgumentParser() 211 | parser.add_argument('filename', nargs=1, type=str, action="store", help='Open Matrix file to validate') 212 | args = parser.parse_args() 213 | run_checks(args.filename[0]) 214 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | # To push to PyPi/pip, use 4 | # python setup.py sdist bdist_wheel upload 5 | 6 | setup( 7 | name='OpenMatrix', 8 | keywords='openmatrix omx', 9 | version='0.3.5.0', 10 | author='Billy Charlton, Ben Stabler', 11 | author_email='billy@okbecause.com, benstabler@yahoo.com', 12 | packages=find_packages(), 13 | url='https://github.com/osPlanning/omx', 14 | license='Apache', 15 | description='OMX, the open matrix data format', 16 | long_description=open('README.txt').read(), 17 | install_requires=[ 18 | "tables >= 3.1.0", 19 | "numpy >= 1.5.0", 20 | ], 21 | classifiers=[ 22 | 'License :: OSI Approved :: Apache Software License' 23 | ], 24 | entry_points={ 25 | 'console_scripts': [ 26 | 'omx-validate = openmatrix.validator:command_line', 27 | ], 28 | } 29 | 30 | ) 31 | --------------------------------------------------------------------------------