pyemaps 2.2.1__tar.gz → 2.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. {pyemaps-2.2.1 → pyemaps-2.4.0}/COPYING +0 -48
  2. {pyemaps-2.2.1/pyemaps.egg-info → pyemaps-2.4.0}/PKG-INFO +10 -2
  3. {pyemaps-2.2.1 → pyemaps-2.4.0}/README.md +5 -0
  4. {pyemaps-2.2.1 → pyemaps-2.4.0}/__init__.py +4 -0
  5. pyemaps-2.4.0/__version__.py +1 -0
  6. pyemaps-2.4.0/cifreader.py +391 -0
  7. pyemaps-2.4.0/dmreader.py +431 -0
  8. pyemaps-2.4.0/emdreader.py +382 -0
  9. pyemaps-2.4.0/expimage.py +393 -0
  10. {pyemaps-2.2.1 → pyemaps-2.4.0}/fileutils.py +65 -120
  11. pyemaps-2.4.0/mibreader.py +141 -0
  12. pyemaps-2.4.0/mrcreader.py +135 -0
  13. pyemaps-2.4.0/notebooks/si_bloch.ipynb +844 -0
  14. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/si_lacbed.ipynb +53 -47
  15. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/si_scm.ipynb +73 -75
  16. pyemaps-2.4.0/picreader.py +142 -0
  17. {pyemaps-2.2.1 → pyemaps-2.4.0/pyemaps.egg-info}/PKG-INFO +10 -2
  18. {pyemaps-2.2.1 → pyemaps-2.4.0}/pyemaps.egg-info/SOURCES.txt +18 -16
  19. pyemaps-2.4.0/pyemaps.egg-info/requires.txt +8 -0
  20. pyemaps-2.4.0/readerbase.py +77 -0
  21. {pyemaps-2.2.1 → pyemaps-2.4.0}/setup.py +20 -17
  22. {pyemaps-2.2.1 → pyemaps-2.4.0}/stackimg.py +204 -16
  23. pyemaps-2.4.0/tiffreader.py +617 -0
  24. pyemaps-2.2.1/CifFile/src/CifFile_module.py +0 -3117
  25. pyemaps-2.2.1/CifFile/src/StarFile.py +0 -2496
  26. pyemaps-2.2.1/CifFile/src/TypeContentsParser.py +0 -82
  27. pyemaps-2.2.1/CifFile/src/YappsStarParser_1_0.py +0 -289
  28. pyemaps-2.2.1/CifFile/src/YappsStarParser_1_1.py +0 -288
  29. pyemaps-2.2.1/CifFile/src/YappsStarParser_2_0.py +0 -369
  30. pyemaps-2.2.1/CifFile/src/YappsStarParser_STAR2.py +0 -382
  31. pyemaps-2.2.1/CifFile/src/__init__.py +0 -7
  32. pyemaps-2.2.1/CifFile/src/drel/__init__.py +0 -1
  33. pyemaps-2.2.1/CifFile/src/drel/drel_ast_yacc.py +0 -582
  34. pyemaps-2.2.1/CifFile/src/drel/drel_lex.py +0 -228
  35. pyemaps-2.2.1/CifFile/src/drel/drel_runtime.py +0 -126
  36. pyemaps-2.2.1/CifFile/src/drel/parsetab.py +0 -185
  37. pyemaps-2.2.1/CifFile/src/drel/py_from_ast.py +0 -628
  38. pyemaps-2.2.1/CifFile/src/parsetab.py +0 -185
  39. pyemaps-2.2.1/CifFile/src/yapps3_compiled_rt.py +0 -390
  40. pyemaps-2.2.1/__version__.py +0 -1
  41. pyemaps-2.2.1/notebooks/si_bloch.ipynb +0 -844
  42. pyemaps-2.2.1/pyemaps.egg-info/requires.txt +0 -3
  43. {pyemaps-2.2.1 → pyemaps-2.4.0}/MANIFEST.in +0 -0
  44. {pyemaps-2.2.1 → pyemaps-2.4.0}/__config__.py +0 -0
  45. {pyemaps-2.2.1 → pyemaps-2.4.0}/__main__.py +0 -0
  46. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Aluminium.xtl +0 -0
  47. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/AluminiumOxide.xtl +0 -0
  48. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Aluminium_FCC.xtl +0 -0
  49. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/BariumTitanate_180k.xtl +0 -0
  50. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/BariumTitanate_270k.xtl +0 -0
  51. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/BariumTitanate_Tetra.xtl +0 -0
  52. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/BiMnO3.xtl +0 -0
  53. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Boron_Tetra.xtl +0 -0
  54. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/CadmiumSelenide_Hex.xtl +0 -0
  55. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/CadmiumSulfide_Cubic.xtl +0 -0
  56. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/CadmiumSulfide_Hex.xtl +0 -0
  57. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Chromium_BCC.xtl +0 -0
  58. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/CoSb3_Skutterudite.xtl +0 -0
  59. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/CopperOxide.xtl +0 -0
  60. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Copper_FCC.xtl +0 -0
  61. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Cu2O_Cuprite.xtl +0 -0
  62. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Diamond.xtl +0 -0
  63. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/ErbiumPyrogermanate.xtl +0 -0
  64. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/FePd_Tetra.xtl +0 -0
  65. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/FeS2_Pyrite.xtl +0 -0
  66. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/GalliumAntimonide.xtl +0 -0
  67. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/GalliumArsenide.xtl +0 -0
  68. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/GalliumNitride.xtl +0 -0
  69. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Germanium.xtl +0 -0
  70. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Gold_FCC.xtl +0 -0
  71. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/IndiumArsenide.xtl +0 -0
  72. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/LaMnO3.xtl +0 -0
  73. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/LeadZirconateTitanate.xtl +0 -0
  74. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Li2MnO3.xtl +0 -0
  75. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/NaFeO2.xtl +0 -0
  76. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Nb3Sn.xtl +0 -0
  77. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Pentacene.xtl +0 -0
  78. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/SiAlONa.xtl +0 -0
  79. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Silicon.xtl +0 -0
  80. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/StrontiumTitanate.xtl +0 -0
  81. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/TelluriumDioxide.xtl +0 -0
  82. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/TinDioxide_RT.xtl +0 -0
  83. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/TitaniumDioxide_Anatase.xtl +0 -0
  84. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/TitaniumDioxide_Rutile.xtl +0 -0
  85. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/TungstenDiselenide.xtl +0 -0
  86. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/VanadiumDioxide_RT.xtl +0 -0
  87. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/ZincOxide.xtl +0 -0
  88. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/Zinc_HCP.xtl +0 -0
  89. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/ZirconiumNitride.xtl +0 -0
  90. {pyemaps-2.2.1 → pyemaps-2.4.0}/cdata/limno2.xtl +0 -0
  91. {pyemaps-2.2.1 → pyemaps-2.4.0}/crystals.py +0 -0
  92. {pyemaps-2.2.1 → pyemaps-2.4.0}/ddiffs.py +0 -0
  93. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/__init__.py +0 -0
  94. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/bloch_dec.py +0 -0
  95. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/csf_dec.py +0 -0
  96. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/dif_dec.py +0 -0
  97. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/dpgen_dec.py +0 -0
  98. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/mxtal_dec.py +0 -0
  99. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/powder_dec.py +0 -0
  100. {pyemaps-2.2.1 → pyemaps-2.4.0}/diffract/stereo_dec.py +0 -0
  101. {pyemaps-2.2.1 → pyemaps-2.4.0}/display.py +0 -0
  102. {pyemaps-2.2.1 → pyemaps-2.4.0}/emcontrols.py +0 -0
  103. {pyemaps-2.2.1 → pyemaps-2.4.0}/errors.py +0 -0
  104. {pyemaps-2.2.1 → pyemaps-2.4.0}/kdiffs.py +0 -0
  105. {pyemaps-2.2.1 → pyemaps-2.4.0}/license-exception.txt +0 -0
  106. {pyemaps-2.2.1 → pyemaps-2.4.0}/license.txt +0 -0
  107. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/adf.ipynb +0 -0
  108. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/al_ediom.ipynb +0 -0
  109. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/powder.ipynb +0 -0
  110. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/si_constructor.ipynb +0 -0
  111. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/si_csf.ipynb +0 -0
  112. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/si_dif.ipynb +0 -0
  113. {pyemaps-2.2.1 → pyemaps-2.4.0}/notebooks/si_stereo.ipynb +0 -0
  114. {pyemaps-2.2.1 → pyemaps-2.4.0}/pyemaps.egg-info/dependency_links.txt +0 -0
  115. {pyemaps-2.2.1 → pyemaps-2.4.0}/pyemaps.egg-info/entry_points.txt +0 -0
  116. {pyemaps-2.2.1 → pyemaps-2.4.0}/pyemaps.egg-info/top_level.txt +0 -0
  117. {pyemaps-2.2.1 → pyemaps-2.4.0}/pyproject.toml +0 -0
  118. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/adf.py +0 -0
  119. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/al.img +0 -0
  120. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/al_dpgen.py +0 -0
  121. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/al_ediom.py +0 -0
  122. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/convert_image.py +0 -0
  123. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/dm_diff.py +0 -0
  124. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/mask.im3 +0 -0
  125. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/powder.py +0 -0
  126. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/raw.img +0 -0
  127. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_bloch.py +0 -0
  128. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_constructor.py +0 -0
  129. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_csf.py +0 -0
  130. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_dif.py +0 -0
  131. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_lacbed.py +0 -0
  132. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_pyemaps.py +0 -0
  133. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_scm.py +0 -0
  134. {pyemaps-2.2.1 → pyemaps-2.4.0}/samples/si_stereo.py +0 -0
  135. {pyemaps-2.2.1 → pyemaps-2.4.0}/scattering/__init__.py +0 -0
  136. {pyemaps-2.2.1 → pyemaps-2.4.0}/scattering/sct_dec.py +0 -0
  137. {pyemaps-2.2.1 → pyemaps-2.4.0}/setup.cfg +0 -0
  138. {pyemaps-2.2.1 → pyemaps-2.4.0}/spg/__init__.py +0 -0
  139. {pyemaps-2.2.1 → pyemaps-2.4.0}/spg/spg_dec.py +0 -0
  140. {pyemaps-2.2.1 → pyemaps-2.4.0}/xtal.py +0 -0
@@ -748,51 +748,3 @@ products or services of Licensee, or any third party.
748
748
  8. By copying, installing or otherwise using matplotlib ,
749
749
  Licensee agrees to be bound by the terms and conditions of this License
750
750
  Agreement.
751
-
752
- ## PYCIFRW License Agreement (Python License, Version 2)
753
-
754
- Copyright (c) 2001-2014 ANSTO; All Rights Reserved.
755
-
756
- This LICENSE AGREEMENT is between the Australian Nuclear Science
757
- and Technology Organisation ("ANSTO"), and the Individual or
758
- Organization ("Licensee") accessing and otherwise using this software
759
- ("PyCIFRW") in source or binary form and its associated documentation.
760
-
761
- Subject to the terms and conditions of this License Agreement,
762
- ANSTO hereby grants Licensee a nonexclusive, royalty-free, world-wide
763
- license to reproduce, analyze, test, perform and/or display publicly,
764
- prepare derivative works, distribute, and otherwise use PyCIFRW alone
765
- or in any derivative version, provided, however, that this License
766
- Agreement and ANSTO's notice of copyright, i.e., "Copyright (c)
767
- 2001-2014 ANSTO; All Rights Reserved" are retained in PyCIFRW alone or
768
- in any derivative version prepared by Licensee.
769
-
770
- In the event Licensee prepares a derivative work that is based on
771
- or incorporates PyCIFRW or any part thereof, and wants to make the
772
- derivative work available to others as provided herein, then Licensee
773
- hereby agrees to include in any such work a brief summary of the
774
- changes made to PyCIFRW.
775
-
776
- ANSTO is making PyCIFRW available to Licensee on an "AS IS"
777
- basis. ANSTO MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
778
- IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, ANSTO MAKES NO AND
779
- DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
780
- FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYCIFRW WILL NOT
781
- INFRINGE ANY THIRD PARTY RIGHTS.
782
-
783
- ANSTO SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYCIFRW
784
- FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A
785
- RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYCIFRW, OR ANY
786
- DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
787
-
788
- This License Agreement will automatically terminate upon a material
789
- breach of its terms and conditions.
790
-
791
- Nothing in this License Agreement shall be deemed to create any
792
- relationship of agency, partnership, or joint venture between ANSTO
793
- and Licensee. This License Agreement does not grant permission to use
794
- ANSTO trademarks or trade name in a trademark sense to endorse or
795
- promote products or services of Licensee, or any third party.
796
-
797
- By copying, installing or otherwise using PyCIFRW, Licensee agrees
798
- to be bound by the terms and conditions of this License Agreement.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyemaps
3
- Version: 2.2.1
3
+ Version: 2.4.0
4
4
  Summary: A Python Package for Transmission Electron Diffraction Simulations and Crystallographic Computing
5
5
  Home-page: https://github.com/emlab-solutions/pyemaps
6
6
  Author: EMLab Solutions, Inc.
@@ -24,13 +24,16 @@ Description-Content-Type: text/markdown
24
24
  License-File: license-exception.txt
25
25
  License-File: license.txt
26
26
  License-File: COPYING
27
- Requires-Dist: emaps>=2.0.1
27
+ Requires-Dist: emaps>=2.1.0
28
28
  Requires-Dist: numpy>=2.0
29
29
  Requires-Dist: matplotlib>=3.8.4
30
+ Provides-Extra: emd
31
+ Requires-Dist: h5py>=3.10; python_version < "3.15" and extra == "emd"
30
32
  Dynamic: description
31
33
  Dynamic: description-content-type
32
34
  Dynamic: license-file
33
35
  Dynamic: project-url
36
+ Dynamic: provides-extra
34
37
  Dynamic: requires-dist
35
38
  Dynamic: summary
36
39
 
@@ -75,6 +78,11 @@ The extended 4D-STEM features need a license:
75
78
  - Annular bright and dark field images
76
79
  - Masked images
77
80
 
81
+ Reading experimental patterns is free: TIFF, Gatan DigitalMicrograph (`.dm3`, `.dm4`), MRC,
82
+ Quantum Detectors Merlin (`.mib`), PNG, BMP, JPEG and NumPy files, single images, stacks and
83
+ 4D-STEM scans, with no other package, and EMD files from Thermo Fisher Velox or in the Berkeley EMD format,
84
+ including py4DSTEM's 4D-STEM datacubes, with `pip install "pyemaps[emd]"`.
85
+
78
86
  ## Requirements
79
87
 
80
88
  - 64-bit Windows
@@ -39,6 +39,11 @@ The extended 4D-STEM features need a license:
39
39
  - Annular bright and dark field images
40
40
  - Masked images
41
41
 
42
+ Reading experimental patterns is free: TIFF, Gatan DigitalMicrograph (`.dm3`, `.dm4`), MRC,
43
+ Quantum Detectors Merlin (`.mib`), PNG, BMP, JPEG and NumPy files, single images, stacks and
44
+ 4D-STEM scans, with no other package, and EMD files from Thermo Fisher Velox or in the Berkeley EMD format,
45
+ including py4DSTEM's 4D-STEM datacubes, with `pip install "pyemaps[emd]"`.
46
+
42
47
  ## Requirements
43
48
 
44
49
  - 64-bit Windows
@@ -167,6 +167,9 @@ except ImportError as e:
167
167
  #--------------Pyemaps Display Functions-------------------------------------
168
168
  from .display import showDif, showBloch, showStereo, plot2Powder
169
169
 
170
+ #--------------Experimental images from image files (TIFF, .im3)--------------------
171
+ from .expimage import read_image, write_im3, image_readers, ExperimentalImage
172
+
170
173
  if PKG_TYPE != TYPE_FREE:
171
174
  #------------------Diffraction Database Generator - paid package only---------------------------
172
175
  try:
@@ -203,6 +206,7 @@ if PKG_TYPE != TYPE_FREE:
203
206
  E_SH = 0
204
207
  E_RAW = 1
205
208
  E_NPY = 2
209
+ E_FILE = 3 # any format read_image reads, such as TIFF (convertImage)
206
210
 
207
211
  # --------image loading mode -------
208
212
  # allowing users to handle memory needs depending on size of the images
@@ -0,0 +1 @@
1
+ __version__ = "2.4.0"
@@ -0,0 +1,391 @@
1
+ # This file is part of pyEMAPS.
2
+ # Copyright (C) 2021-2026 EMLab Solutions, Inc.
3
+ #
4
+ # SPDX-License-Identifier: GPL-3.0-or-later
5
+ #
6
+ # Additional permission under GPLv3 Section 7:
7
+ # See license-exception.txt for the exception permitting
8
+ # combination with the separately licensed backend, emaps.
9
+
10
+ '''
11
+ A reader for Crystallographic Information Files (CIF), the IUCr's open standard, in Python
12
+ only.
13
+
14
+ It follows the CIF 1.1 syntax (https://www.iucr.org/resources/cif/spec/version1.1/cifsyntax):
15
+
16
+ - a file holds data blocks, each started by ``data_<name>``;
17
+ - a data item is a data name (a tag starting with ``_``, case-insensitive) and its value;
18
+ - ``loop_`` starts a table: its data names, then their values, row by row;
19
+ - values are unquoted (ending at whitespace), quoted with ``'`` or ``"`` (a closing quote
20
+ must be followed by whitespace or the end of the line), or text fields between lines that
21
+ start with ``;``;
22
+ - ``#`` starts a comment, outside values; ``data_``, ``loop_``, ``save_``, ``global_`` and
23
+ ``stop_`` are reserved words; save frames (dictionaries) and global blocks are skipped.
24
+
25
+ Files that start with the CIF 2.0 code (``#\\#CIF_2.0``) follow CIF 2.0 (Bernstein et al.,
26
+ J. Appl. Cryst. 49 (2016) 277-284), which changes or adds:
27
+
28
+ - a single- or double-quoted value ends at the next matching quote, on the same line;
29
+ - triple-quoted values (between three single or three double quotes), which may span lines;
30
+ - lists, ``[value value ...]``, and tables, ``{"key":value ...}`` (quoted keys, each followed
31
+ directly by ``:``), whose values may be lists and tables in turn, over several lines;
32
+ - ``[``, ``]``, ``{`` and ``}`` can't appear in unquoted values: they end them.
33
+
34
+ Values are returned as strings, as written (without their delimiters): ``?`` and ``.`` are
35
+ the strings ``'?'`` and ``'.'``. Looped values are lists of strings. A CIF 2.0 list is a
36
+ :py:class:`CifList` (a tuple) and a table a :py:class:`CifTable` (a dict), so they're never
37
+ mistaken for looped values.
38
+
39
+ :py:func:`~pyemaps.fileutils.loadCrystalCIFData` uses this module, through
40
+ :py:meth:`Crystal.from_cif <pyemaps.crystals.Crystal.from_cif>`.
41
+ '''
42
+ import os
43
+
44
+ RESERVED = ('data_', 'loop_', 'save_', 'global_', 'stop_')
45
+ CIF2_MAGIC = '#\\#CIF_2.0'
46
+
47
+
48
+ class CifSyntaxError(ValueError):
49
+ '''A file that doesn't follow the CIF syntax, with the line number and the reason.'''
50
+
51
+
52
+ class CifList(tuple):
53
+ '''A CIF 2.0 list value: its values, which are strings, lists or tables.'''
54
+
55
+
56
+ class CifTable(dict):
57
+ '''A CIF 2.0 table value: its values by key; values are strings, lists or tables.'''
58
+
59
+
60
+ class CifBlock:
61
+ '''
62
+ One data block: its data items by name. Names are case-insensitive. A value is a string,
63
+ or a list of strings for a looped data name.
64
+ '''
65
+
66
+ def __init__(self, name):
67
+ self.name = name
68
+ self._items = {}
69
+ self._names = [] # data names as written, in order
70
+ self.loops = [] # each loop's data names, lower case
71
+
72
+ def __contains__(self, tag):
73
+ return tag.lower() in self._items
74
+
75
+ def __getitem__(self, tag):
76
+ return self._items[tag.lower()]
77
+
78
+ def get(self, tag, default=None):
79
+ return self._items.get(tag.lower(), default)
80
+
81
+ def keys(self):
82
+ return list(self._names)
83
+
84
+ def __len__(self):
85
+ return len(self._items)
86
+
87
+ def _set(self, tag, value, where):
88
+ key = tag.lower()
89
+ if key in self._items:
90
+ raise CifSyntaxError(f'{where}: data name {tag} appears twice in data block '
91
+ f'{self.name}')
92
+ self._items[key] = value
93
+ self._names.append(tag)
94
+
95
+ def __repr__(self):
96
+ return f'CifBlock({self.name!r}: {len(self._items)} data names)'
97
+
98
+
99
+ def read_cif(path):
100
+ '''
101
+ Read a CIF file.
102
+
103
+ :param path: the file.
104
+ :type path: str or os.PathLike
105
+ :return: the data blocks, in file order.
106
+ :rtype: list of CifBlock
107
+ :raise OSError: if the file can't be read.
108
+ :raise CifSyntaxError: if the file doesn't follow the CIF syntax.
109
+ '''
110
+ path = os.fspath(path)
111
+ with open(path, 'rb') as f:
112
+ raw = f.read()
113
+ for enc in ('utf-8-sig', 'latin-1'):
114
+ try:
115
+ text = raw.decode(enc)
116
+ break
117
+ except UnicodeDecodeError:
118
+ continue
119
+ return parse_cif(text, path)
120
+
121
+
122
+ def parse_cif(text, source='<string>'):
123
+ '''Parse CIF text into its data blocks; see :py:func:`read_cif`.'''
124
+ tokens = _tokens(text, source)
125
+ return _blocks(tokens, source)
126
+
127
+
128
+ # ------------------------------------------------------------------ tokens
129
+
130
+ TAG, VALUE, WORD = 'tag', 'value', 'word' # WORD: a reserved word
131
+ KEY = 'key' # a CIF 2.0 table key, with its ":"
132
+ OPENERS = {'[': ']', '{': '}'}
133
+
134
+
135
+ def _tokens(text, source):
136
+ '''(kind, text, line number) for every token, comments and whitespace removed.'''
137
+ text = text.replace('\r\n', '\n').replace('\r', '\n')
138
+ if text.startswith(CIF2_MAGIC):
139
+ return _tokens_cif2(text, source)
140
+ lines = text.split('\n')
141
+ out = []
142
+ n = 0
143
+ while n < len(lines):
144
+ line = lines[n]
145
+ if line.startswith(';'): # a text field, to the next ";" line
146
+ start = n
147
+ body = [line[1:]]
148
+ n += 1
149
+ while n < len(lines) and not lines[n].startswith(';'):
150
+ body.append(lines[n])
151
+ n += 1
152
+ if n == len(lines):
153
+ raise CifSyntaxError(f'{source}, line {start + 1}: a text field (";") is '
154
+ 'never closed')
155
+ out.append((VALUE, '\n'.join(body), start + 1))
156
+ rest = lines[n][1:]
157
+ n += 1
158
+ _line_tokens(rest, n, source, out)
159
+ continue
160
+ _line_tokens(line, n + 1, source, out)
161
+ n += 1
162
+ return out
163
+
164
+
165
+ def _line_tokens(line, lineno, source, out):
166
+ '''CIF 1.1 tokens on one line.'''
167
+ i, size = 0, len(line)
168
+ while i < size:
169
+ c = line[i]
170
+ if c in ' \t':
171
+ i += 1
172
+ continue
173
+ if c == '#':
174
+ return
175
+ if c in '\'"':
176
+ j = i + 1
177
+ while True:
178
+ j = line.find(c, j)
179
+ if j < 0:
180
+ raise CifSyntaxError(f'{source}, line {lineno}: a quoted value ({c}) is '
181
+ 'never closed on its line')
182
+ if j + 1 == size or line[j + 1] in ' \t': # CIF 1.1: quote + space ends it
183
+ break
184
+ j += 1
185
+ out.append((VALUE, line[i + 1:j], lineno))
186
+ i = j + 1
187
+ continue
188
+ j = i
189
+ while j < size and line[j] not in ' \t':
190
+ j += 1
191
+ word = line[i:j]
192
+ low = word.lower()
193
+ if c == '_':
194
+ out.append((TAG, word, lineno))
195
+ elif low.startswith(RESERVED):
196
+ out.append((WORD, word, lineno))
197
+ else:
198
+ out.append((VALUE, word, lineno))
199
+ i = j
200
+
201
+
202
+ def _tokens_cif2(text, source):
203
+ '''CIF 2.0 tokens, from a character stream: lists, tables and quoted values may span lines.'''
204
+ out = []
205
+ i, size, line = 0, len(text), 1
206
+ at_line_start = True
207
+ while i < size:
208
+ c = text[i]
209
+ if c == '\n':
210
+ line += 1
211
+ i += 1
212
+ at_line_start = True
213
+ continue
214
+ if c in ' \t':
215
+ i += 1
216
+ at_line_start = False
217
+ continue
218
+ if c == ';' and at_line_start: # a text field
219
+ end = text.find('\n;', i)
220
+ if end < 0:
221
+ raise CifSyntaxError(f'{source}, line {line}: a text field (";") is never closed')
222
+ out.append((VALUE, text[i + 1:end], line))
223
+ line += text.count('\n', i, end + 1)
224
+ i = end + 2
225
+ at_line_start = False
226
+ continue
227
+ at_line_start = False
228
+ if c == '#':
229
+ j = text.find('\n', i)
230
+ i = size if j < 0 else j
231
+ continue
232
+ if text.startswith(("'''", '"""'), i):
233
+ q = text[i:i + 3]
234
+ end = text.find(q, i + 3)
235
+ if end < 0:
236
+ raise CifSyntaxError(f'{source}, line {line}: a triple-quoted value is never closed')
237
+ value, start_line = text[i + 3:end], line
238
+ line += text.count('\n', i, end)
239
+ i = end + 3
240
+ i = _string_token(text, i, value, start_line, out)
241
+ continue
242
+ if c in '\'"':
243
+ end = text.find(c, i + 1)
244
+ nl_at = text.find('\n', i + 1)
245
+ if end < 0 or (0 <= nl_at < end):
246
+ raise CifSyntaxError(f'{source}, line {line}: a quoted value ({c}) is never closed '
247
+ 'on its line')
248
+ i = _string_token(text, end + 1, text[i + 1:end], line, out)
249
+ continue
250
+ if c in '[]{}':
251
+ out.append((c, c, line))
252
+ i += 1
253
+ continue
254
+ j = i
255
+ while j < size and text[j] not in ' \t\n[]{}':
256
+ j += 1
257
+ word = text[i:j]
258
+ if c == '_':
259
+ out.append((TAG, word, line))
260
+ elif word.lower().startswith(RESERVED):
261
+ out.append((WORD, word, line))
262
+ else:
263
+ out.append((VALUE, word, line))
264
+ i = j
265
+ return out
266
+
267
+
268
+ def _string_token(text, i, value, line, out):
269
+ '''A quoted value, or a table key when ":" follows it directly. Returns the next position.'''
270
+ if i < len(text) and text[i] == ':':
271
+ out.append((KEY, value, line))
272
+ return i + 1
273
+ out.append((VALUE, value, line))
274
+ return i
275
+
276
+
277
+ # ------------------------------------------------------------------ blocks
278
+
279
+ def _blocks(tokens, source):
280
+ blocks = []
281
+ block = None
282
+ k, size = 0, len(tokens)
283
+ while k < size:
284
+ kind, word, line = tokens[k]
285
+ where = f'{source}, line {line}'
286
+ low = word.lower()
287
+ if kind == WORD and low.startswith('data_'):
288
+ name = word[5:]
289
+ if not name:
290
+ raise CifSyntaxError(f'{where}: a data block without a name')
291
+ block = CifBlock(name)
292
+ blocks.append(block)
293
+ k += 1
294
+ elif kind == WORD and (low.startswith('save_') or low == 'global_'):
295
+ k = _skip_frame(tokens, k, source)
296
+ elif block is None:
297
+ raise CifSyntaxError(f'{where}: {word!r} comes before the first data block '
298
+ '("data_...")')
299
+ elif kind == WORD and low == 'loop_':
300
+ k = _loop(tokens, k + 1, block, source)
301
+ elif kind == TAG:
302
+ if k + 1 >= size or tokens[k + 1][0] not in (VALUE, '[', '{'):
303
+ raise CifSyntaxError(f'{where}: data name {word} has no value')
304
+ value, k = _value(tokens, k + 1, source)
305
+ block._set(word, value, where)
306
+ elif kind == WORD and low == 'stop_':
307
+ k += 1
308
+ elif kind in (']', '}'):
309
+ raise CifSyntaxError(f'{where}: "{kind}" closes a list or table that never started')
310
+ elif kind == KEY:
311
+ raise CifSyntaxError(f'{where}: table key {word!r} outside a table')
312
+ else:
313
+ raise CifSyntaxError(f'{where}: value {word!r} has no data name')
314
+ return blocks
315
+
316
+
317
+ def _value(tokens, k, source):
318
+ '''One value from token k: a string, or a CIF 2.0 list or table. Returns (value, next k).'''
319
+ kind, word, line = tokens[k]
320
+ if kind == VALUE:
321
+ return word, k + 1
322
+ if kind not in OPENERS:
323
+ raise CifSyntaxError(f'{source}, line {line}: expected a value, not {word!r}')
324
+ close = OPENERS[kind]
325
+ items = [] if kind == '[' else {}
326
+ k += 1
327
+ while True:
328
+ if k >= len(tokens):
329
+ raise CifSyntaxError(f'{source}, line {line}: a {"list" if kind == "[" else "table"} '
330
+ f'("{kind}") is never closed')
331
+ t, w, l = tokens[k]
332
+ if t == close:
333
+ k += 1
334
+ break
335
+ if kind == '[':
336
+ if t == KEY:
337
+ raise CifSyntaxError(f'{source}, line {l}: table key {w!r} in a list')
338
+ v, k = _value(tokens, k, source)
339
+ items.append(v)
340
+ else:
341
+ if t != KEY:
342
+ raise CifSyntaxError(f'{source}, line {l}: a table entry must be a quoted key '
343
+ f'followed directly by ":", not {w!r}')
344
+ if k + 1 >= len(tokens) or tokens[k + 1][0] in (']', '}', KEY):
345
+ raise CifSyntaxError(f'{source}, line {l}: table key {w!r} has no value')
346
+ v, k = _value(tokens, k + 1, source)
347
+ items[w] = v
348
+ return (CifList(items) if kind == '[' else CifTable(items)), k
349
+
350
+
351
+ def _loop(tokens, k, block, source):
352
+ size = len(tokens)
353
+ names = []
354
+ while k < size and tokens[k][0] == TAG:
355
+ names.append(tokens[k][1])
356
+ k += 1
357
+ line = tokens[k - 1][2] if k else 0
358
+ if not names:
359
+ raise CifSyntaxError(f'{source}, line {line}: loop_ without data names')
360
+ values = []
361
+ while k < size and tokens[k][0] in (VALUE, '[', '{'):
362
+ value, k = _value(tokens, k, source)
363
+ values.append(value)
364
+ if not values or len(values) % len(names):
365
+ raise CifSyntaxError(f'{source}, line {line}: a loop of {len(names)} data names has '
366
+ f'{len(values)} values, not a whole number of rows')
367
+ where = f'{source}, line {line}'
368
+ for c, name in enumerate(names):
369
+ block._set(name, values[c::len(names)], where)
370
+ block.loops.append([n.lower() for n in names])
371
+ return k
372
+
373
+
374
+ def _skip_frame(tokens, k, source):
375
+ '''Skip a save frame (save_name ... save_) or a global_ block.'''
376
+ _, word, line = tokens[k]
377
+ if word.lower() == 'global_':
378
+ k += 1
379
+ while k < len(tokens) and not (tokens[k][0] == WORD and
380
+ tokens[k][1].lower().startswith('data_')):
381
+ k += 1
382
+ return k
383
+ if word.lower() == 'save_':
384
+ raise CifSyntaxError(f'{source}, line {line}: "save_" ends a save frame that never '
385
+ 'started')
386
+ k += 1
387
+ while k < len(tokens):
388
+ if tokens[k][0] == WORD and tokens[k][1].lower() == 'save_':
389
+ return k + 1
390
+ k += 1
391
+ raise CifSyntaxError(f'{source}, line {line}: save frame {word[5:]} is never closed')