diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 97c9256..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -artistlib/_version.py export-subst diff --git a/.gitignore b/.gitignore index d1b7468..60ddc32 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ -__pycache__ -artistlib.egg-info -dist \ No newline at end of file +/venv/ +*.egg-info +*.raw +/.idea/ +*.tiff +sartist/__pycache__/* +sartist/hardware/__pycache__/* +__pycache__/* \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 6f68915..0000000 --- a/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 Bundesanstalt für Materialforschung und -prüfung - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index d6b5dd3..0000000 --- a/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# PythonLib aRTist - -Python library and scripts to control the BAM X-ray simulation tool "aRTist" remotely and automatically. - -Please refer to the **[documentation](https://bamresearch.github.io/aRTist-PythonLib/)** to get started. - -For more information on aRTist see its **[website](https://www.artist.bam.de)** and its **[online guide](https://bamresearch.github.io/aRTist-handbook/)**. diff --git a/SimulateFromList/ListOfSimulations.txt b/SimulateFromList/ListOfSimulations.txt deleted file mode 100644 index 2160ad3..0000000 --- a/SimulateFromList/ListOfSimulations.txt +++ /dev/null @@ -1,449 +0,0 @@ -ID LG LG Thickness Spot size Spot resolution Sampling ETA Source Type Source U Source I Source Filter Material Source Filter Thickness N Detector pixel size Cone beam angle Other parameters Filename Remarks -1 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -2 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -3 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -4 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -5 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -6 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -7 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -8 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -9 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -10 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -11 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -12 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -13 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -14 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -15 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -16 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -17 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -18 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -19 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -20 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -21 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -22 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -23 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -24 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -25 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -26 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -27 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -28 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -29 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -30 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -31 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -32 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -33 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -34 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -35 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -36 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -37 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -38 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -39 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -40 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -41 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -42 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -43 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -44 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -45 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -46 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -47 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -48 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -49 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -50 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -51 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -52 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -53 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -54 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -55 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -56 6 2 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -57 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -58 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -59 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -60 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -61 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -62 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -63 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -64 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -65 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -66 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -67 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -68 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -69 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -70 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -71 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -72 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -73 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -74 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -75 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -76 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -77 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -78 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -79 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -80 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -81 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -82 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -83 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -84 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -85 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -86 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -87 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -88 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -89 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -90 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -91 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -92 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -93 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -94 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -95 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -96 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -97 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -98 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -99 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -100 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -101 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -102 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -103 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -104 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -105 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -106 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -107 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -108 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -109 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -110 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -111 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -112 6 4 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -113 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -114 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -115 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -116 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -117 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -118 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -119 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -120 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -121 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -122 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -123 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -124 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -125 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -126 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -127 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -128 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -129 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -130 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -131 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -132 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -133 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -134 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -135 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -136 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -137 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -138 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -139 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -140 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -141 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -142 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -143 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -144 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -145 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -146 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -147 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -148 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -149 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -150 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -151 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -152 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -153 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -154 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -155 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -156 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -157 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -158 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -159 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -160 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -161 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -162 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -163 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -164 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -165 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -166 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -167 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -168 6 6 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -169 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -170 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -171 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -172 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -173 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -174 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -175 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -176 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -177 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -178 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -179 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -180 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -181 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -182 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -183 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -184 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -185 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -186 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -187 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -188 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -189 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -190 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -191 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -192 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -193 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -194 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -195 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -196 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -197 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -198 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -199 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -200 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -201 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -202 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -203 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -204 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -205 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -206 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -207 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -208 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -209 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -210 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -211 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -212 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -213 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -214 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -215 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -216 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -217 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -218 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -219 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -220 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -221 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -222 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -223 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -224 6 8 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -225 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -226 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -227 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -228 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -229 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -230 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -231 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -232 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -233 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -234 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -235 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -236 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -237 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -238 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -239 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -240 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -241 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -242 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -243 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -244 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -245 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -246 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -247 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -248 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -249 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -250 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -251 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -252 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -253 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -254 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -255 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -256 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -257 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -258 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -259 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -260 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -261 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -262 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -263 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -264 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -265 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -266 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -267 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -268 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -269 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -270 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -271 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -272 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -273 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -274 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -275 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -276 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -277 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -278 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -279 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -280 6 10 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -281 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -282 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -283 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -284 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -285 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -286 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -287 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -288 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -289 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -290 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -291 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -292 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -293 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -294 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -295 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -296 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -297 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -298 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -299 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -300 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -301 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -302 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -303 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -304 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -305 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -306 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -307 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -308 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -309 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -310 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -311 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -312 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -313 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -314 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -315 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -316 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -317 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -318 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -319 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -320 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -321 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -322 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -323 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -324 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -325 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -326 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -327 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -328 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -329 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -330 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -331 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -332 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -333 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -334 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -335 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -336 6 12 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -337 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -338 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -339 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -340 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -341 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -342 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -343 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -344 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -345 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -346 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -347 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -348 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -349 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -350 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -351 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -352 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -353 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -354 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -355 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -356 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -357 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -358 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -359 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -360 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -361 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -362 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -363 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -364 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -365 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -366 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -367 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -368 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -369 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -370 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -371 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -372 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -373 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -374 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -375 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -376 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -377 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -378 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -379 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -380 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -381 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -382 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -383 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -384 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -385 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -386 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -387 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -388 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -389 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -390 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -391 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -392 6 14 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif -393 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.05 NxS_UB_ConeBeamAngle.tif -394 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.1 NxS_UB_ConeBeamAngle.tif -395 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.2 NxS_UB_ConeBeamAngle.tif -396 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.3 NxS_UB_ConeBeamAngle.tif -397 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.4 NxS_UB_ConeBeamAngle.tif -398 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.5 NxS_UB_ConeBeamAngle.tif -399 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.6 NxS_UB_ConeBeamAngle.tif -400 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.7 NxS_UB_ConeBeamAngle.tif -401 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.8 NxS_UB_ConeBeamAngle.tif -402 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 0.9 NxS_UB_ConeBeamAngle.tif -403 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1 NxS_UB_ConeBeamAngle.tif -404 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.2 NxS_UB_ConeBeamAngle.tif -405 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.4 NxS_UB_ConeBeamAngle.tif -406 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.6 NxS_UB_ConeBeamAngle.tif -407 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 1.8 NxS_UB_ConeBeamAngle.tif -408 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2 NxS_UB_ConeBeamAngle.tif -409 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.2 NxS_UB_ConeBeamAngle.tif -410 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.4 NxS_UB_ConeBeamAngle.tif -411 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.6 NxS_UB_ConeBeamAngle.tif -412 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 2.8 NxS_UB_ConeBeamAngle.tif -413 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3 NxS_UB_ConeBeamAngle.tif -414 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.2 NxS_UB_ConeBeamAngle.tif -415 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.4 NxS_UB_ConeBeamAngle.tif -416 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.6 NxS_UB_ConeBeamAngle.tif -417 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 3.8 NxS_UB_ConeBeamAngle.tif -418 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4 NxS_UB_ConeBeamAngle.tif -419 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.2 NxS_UB_ConeBeamAngle.tif -420 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.4 NxS_UB_ConeBeamAngle.tif -421 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.6 NxS_UB_ConeBeamAngle.tif -422 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 4.8 NxS_UB_ConeBeamAngle.tif -423 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5 NxS_UB_ConeBeamAngle.tif -424 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.2 NxS_UB_ConeBeamAngle.tif -425 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.4 NxS_UB_ConeBeamAngle.tif -426 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.6 NxS_UB_ConeBeamAngle.tif -427 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 5.8 NxS_UB_ConeBeamAngle.tif -428 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6 NxS_UB_ConeBeamAngle.tif -429 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.2 NxS_UB_ConeBeamAngle.tif -430 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.4 NxS_UB_ConeBeamAngle.tif -431 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.6 NxS_UB_ConeBeamAngle.tif -432 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 6.8 NxS_UB_ConeBeamAngle.tif -433 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7 NxS_UB_ConeBeamAngle.tif -434 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.2 NxS_UB_ConeBeamAngle.tif -435 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.4 NxS_UB_ConeBeamAngle.tif -436 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.6 NxS_UB_ConeBeamAngle.tif -437 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 7.8 NxS_UB_ConeBeamAngle.tif -438 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8 NxS_UB_ConeBeamAngle.tif -439 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.2 NxS_UB_ConeBeamAngle.tif -440 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.4 NxS_UB_ConeBeamAngle.tif -441 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.6 NxS_UB_ConeBeamAngle.tif -442 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 8.8 NxS_UB_ConeBeamAngle.tif -443 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9 NxS_UB_ConeBeamAngle.tif -444 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.2 NxS_UB_ConeBeamAngle.tif -445 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.4 NxS_UB_ConeBeamAngle.tif -446 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.6 NxS_UB_ConeBeamAngle.tif -447 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 9.8 NxS_UB_ConeBeamAngle.tif -448 6 16 0.002 301 1089 0 Mono 50 1 VOID 0 10 0.1 10 NxS_UB_ConeBeamAngle.tif diff --git a/SimulateFromList/SimulateFromList.py b/SimulateFromList/SimulateFromList.py deleted file mode 100644 index addd95e..0000000 --- a/SimulateFromList/SimulateFromList.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Tue May 31 11:04:16 2022 - -@author: dschumac - -The aRTist.py library needs to be present! -This is an example scipt which shows how to use a spreadsheet to simulate a bunch of images. The corresponding spreadsheet for this script is as a tab-separeted text-file ("ListOfSimulations.txt"). -Each row in the spreadsheet corresponds to a single aRTist simulation. The colums represent the individual simulation parameters. -The given comlumns need to be adapted according to the simulation task, as the script needs to be! - -""" - -import pandas as pd -import os -import sys -sys.path.insert(1, '[Your python library directory]/aRTist-PythonLib') -import aRTist -import math - - - - -######################## Options ############################### -''' aRTist connection ''' -HOST = "127.0.0.1" # localhost -PORT = 3658 # port @HOST -buffer = 1024 # package size -timeout = 10 # TimeOut in sec - - - -''' Path ''' -#Cone Beam -path_script = "[Your directory]/ListOfSimulations.txt" -path_save_images = "[Your directory]/Images_UB_ConeBeam/" - - - - -############################################################################## -''' Read Script file''' - -data = pd.read_csv(path_script, sep="\t", encoding='mbcs') #Read data -data.dropna(axis=0, how='all', inplace=True) #Delete empty rows -data["Filename"].fillna('NA', inplace = True) #Replace empty file names with "NA" -data_sort = data.sort_values(by=['ETA', 'ID']) #sort by ID and spot size - - -############################################################################### -''' Connect to aRTist ''' -Con = aRTist.Connection(HOST, PORT, buffer, timeout) - -############################################################################### -aRTist.Connection.send(Con, aRTist.SETUP_Preview(1)) - -"""Source Setup""" -SourceZ = 10 #Random SZ pos, outside of object -SourcekV = data_sort['Source U'].iloc[0] -SourcemA = data_sort['Source I'].iloc[0] -SourceType = data_sort['Source Type'].iloc[0] -SourceFilterMat = data_sort['Source Filter Material'].iloc[0] -SourceFilterTh = data_sort['Source Filter Thickness'].iloc[0] -sampling = data_sort['Sampling'].iloc[0] - -aRTist.Connection.send(Con, aRTist.SETUP_source(SourceZ, SourcekV, SourcemA, SourceType, SourceFilterMat, SourceFilterTh)) -aRTist.Connection.send(Con, aRTist.SETUP_SourceSampling(sampling)) - - -eta_out = -1 # for checking if ETA has changed -FS_out = -1 # for checking if FS has changed - -for index, row in data_sort.iterrows(): - - Fname = data_sort.loc[index, 'Filename'] - Fname = os.path.splitext(Fname)[0] #extract name without extension - - """Detector position and pixel size""" - PixelSize = data_sort.loc[index, 'Detector pixel size'] - - - """Spot Setup""" - FS = data_sort.loc[index, 'Spot size'] - eta = data_sort.loc[index, 'ETA'] - SpotRes = data_sort.loc[index, 'Spot resolution'] - - """Scene Setup""" - LG = data_sort.loc[index, 'LG'] - name = 'LG{:.0f}'.format(LG) # create object name similar to list in aRTist - Obj = aRTist.Connection.send(Con, aRTist.get_ObjID(name)).split() # Query Object ID from name - OID = Obj[1] # isolate Object ID - aRTist.Connection.send(Con, aRTist.set_vis_AllParts("off")) # set visibility of all objects off - aRTist.Connection.send(Con, aRTist.set_vis(OID, 'on')) # activate object with only - - """Calc magnification, source and detector Z pos""" - cba = data_sort.loc[index, 'Cone beam angle'] # Read cone beam angle - CBA = cba*math.pi/180 # Degree to radian - - GW = LG*9 # group width for 5 lines and 4 gaps in um!! - N = data_sort.loc[index, 'N'] # No. of pixels representing unsharpness - Mag = N*PixelSize/FS+1 # Magnification - SZ = (GW/1000) / (2 * math.sin(CBA)) # Source Z position (SOD) - DetZ = -SZ * (Mag-1) # Detector Z position (SOD) - aRTist.Connection.send(Con, aRTist.set_position('S', 0, 0, SZ)) - - '''Set object thickness (and other dimensions)''' - sizeX = GW*10/3000 - sizeY = GW/1000 - sizeZ = data_sort.loc[index, 'LG Thickness']/1000 - aRTist.Connection.send(Con, aRTist.resize(OID, sizeX, sizeY, sizeZ)) - - - """Calc Detector Size""" - ePS = PixelSize*1000 / Mag # effective pixel size - DetSizeX = int(GW / ePS * 1.5) # Detector length 1.5x group width to limit calc and analysis time - DetSizeY = int(GW / ePS * 2.5) # Detector widht 2.5x group width to allow for background fitting - aRTist.Connection.send(Con, aRTist.SETUP_detector(DetZ, 0, DetSizeX, DetSizeY, PixelSize, 'max', 50000)) - - - if eta != eta_out or FS != FS_out: # Only calc new source when ETA or FS have changed - aRTist.Connection.send(Con, aRTist.SETUP_CalcFocalspot(FS, FS, eta, SpotRes)) - - - aRTist.Connection.send(Con, aRTist.Clear_FF()) - aRTist.Connection.send(Con, aRTist.AutoAcq_FF(1)) - eta_out = eta - FS_out = FS - - aRTist.Connection.send(Con, aRTist.RenderPreview()) - - - #Print name to update user - # print('ID={}, ETA={:.1f}; LG={:.0f} um; Spot={:.1f} um; Sampling={:.0f}; N={:.1f}; {}'.format(index, eta, LG, FS*1000, sampling, N, Fname)) - print('ID={}, CB={:.2f}°; ETA={:.1f}; LG={:.0f} um; Thickness {:.0f} um; Spot={:.1f} um; Sampling={}; N={:.1f}; {}'.format(index, cba, eta, LG, sizeZ*1000, FS*1000, sampling, N, Fname)) - ResFname = '{}_CB{:.2f}_ETA{:.1f}_LG{:.0f}_Th{:.0f}_FS{:.1f}um_Sampling{}_N{:.1f}.tif'.format(Fname, cba, eta, LG, sizeZ*1000, FS*1000, sampling, N) - ResPath = path_save_images + ResFname - - - aRTist.Connection.send(Con, aRTist.make_image()) - aRTist.Connection.send(Con, aRTist.save_image(ResPath)) - - - -############################################################################### -''' Close Connection to aRTist''' -Con.S.close() diff --git a/Standalones/ParticlesAndPores/CreateParticlePoreMatrix.py b/Standalones/ParticlesAndPores/CreateParticlePoreMatrix.py deleted file mode 100644 index 6e5d4db..0000000 --- a/Standalones/ParticlesAndPores/CreateParticlePoreMatrix.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Fri Oct 30 16:20:50 2020 - -@author: David Schumacher -""" -import socket -import numpy as np -import csv - -########################### Options #################################### -''' aRTist connection ''' -HOST = "127.0.0.1" # localhost -PORT = 3658 # port @HOST -BUFFER_SIZE = 1024 # package size -timeout = 10 # TimeOut in sec - -''' aRTist setup ''' -SolidModNo = 16 # Number of module "Solid" in aRTist (Modules/XX. Solid) - -''' Particles/Pores ''' -D_max = 100 # max particle diameter in micrometer -P_max = 30 # max pore diameter in micrometer -P_min = 5 # min pore diameter in micrometer - -N_ParX = 2 # No. of particles in X-direction -N_ParY = 2 # No. of particles in X-direction - -Mat_par = "{Fe}" # Material of Particle -Mat_pore = "{VOID}" # Material of Pore - - -MAG = 50 # magnification -SDD = 400 # source-detector distance in mm -pitch = 0.1 # ative pixel size (pitch) of the detector in mm -DBorder = 1.5 # detector border (1/2), Factor (particle size) - -DetX = 500 # Detector resolution X -DetY = 500 # Detector resolution Y - -kV = 150 # Voltage of X-ray source -mA = 100 # Current of X-ray source - -''' Paths ''' -path_aRTist_scene = "I:/Simulations/TMP/Pores/Pore_Matrix_Scene.aRTist" -path_save = "I:/Simulations/TMP/Pores/Coordinates_" - - - -error = 0 - -########################### aRTist functions (to be replaced by library!) ################################# -''' Communication with aRTist ''' -def aRTist_connect(): - S = socket.socket() # Create socket (for TCP) - S.connect((HOST, PORT)) # Connect to aRTist - S.settimeout(timeout) - return S - -def aRTist_sent(x): - total = "" - for i in range(len(x)): - # print(i+1, "of", len(x), " commands send") - # print(x[i]) - S.send(x[i].encode()) - total = total + aRTist_listen(1) - return total - -def aRTist_listen(command_no): - total = "" - stop = False - if (command_no == 0): - S.settimeout(0.2) - while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total): # as long as server doesn't respond and doesn't contain "SUCCESS" - try: - msg = S.recv(BUFFER_SIZE).decode() # - except socket.timeout as e: - err = e.args[0] - if err == "timed out": - print("Timeout\n") - stop = True - continue - else: - if ("SUCCESS" in msg): - total = total + msg - # print(msg) - stop = True - continue - elif ("ERROR" in msg): - total = total + msg - # print(msg) - stop = True - global error - error = error + 1 - continue - else: - # print(msg) - if (command_no == 0): - print(msg) - total = total + msg - S.settimeout(timeout) - return total - -''' aRTist specific commands ''' -def aRTist_setup(Path): - STR = ["""FileIO::OpenAny """+ Path +"""; -"""] - return STR - -def aRTist_SETUP_detector(x, y, px): - STR = ["""set ::Xdetector(Type) {flat panel}; -""","""set ::Xsetup_private(DGauto) {Size}; -""","""set ::Xsetup(DetectorPixelX) """+ str((int(x))) +"""; -""","""set ::Xsetup(DetectorPixelY) """+ str((int(y))) +"""; -""","""set ::Xsetup_private(DGdx) """+ str(px) +"""; -""","""set ::Xsetup_private(DGdy) """+ str(px) +"""; -""","""set ::Xdetector(AutoD) {max}; -""","""set ::Xdetector(RefGV) 50000; -""","""::XDetector::UpdateGeometry 1; -"""] - return STR - -def aRTist_SETUP_source(pos, kV, mA): - STR = ["""set ::Xsetup(SourceSampling) {point}; -""","""set ::Xsource(Exposure) """+ str(mA) +"""; -""","""set ::Xsource(Tube) {Mono}; -""","""set ::Xsource(Voltage) """+ str(kV) +"""; -""","""::PartList::Invoke S SetPosition 0 0 """+ str(pos) +"""; -""","""::PartList::Invoke S SetRefPos 0 0 """+ str(pos) +"""; -""","""set ::Xdetector(FFCorrRun) 0; -""","""XDetector::FFCorrClearCmd; -""","""::XSource::spectrumOK; -"""] # set ::Engine::RenderPreview 0; - return STR - -def aRTist_SETUP_FFcorr(): - STR = ["""::XDetector::FFCorrGenCmd; -"""] - return STR - -def aRTist_create_sphere(R): - R = 2 * R - STR = ["""::Modules::Run Solid; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Type) {ellipsoid}; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Equilateral) 1; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(X) """+ str(R) +"""; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(PhiResolution) 80; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(ThetaResolution) 80; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(GridEllipsoid) 1; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(VolumeCorrect) 1; -""","""::Modules::Module""" +str(SolidModNo)+"""::GenerateCmd; -"""] - return STR - -def aRTist_set_material(ID, mat): - STR = ["""::PartList::Set """+ str(ID) +""" Material """+ mat +"""; -"""] - return STR - -def aRTist_set_position(ID, x, y, z): - STR = ["""::PartList::Invoke """+ str(ID) +""" SetPosition """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; -""","""::PartList::Invoke """+ str(ID) +""" SetRefPos """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; -"""] - return STR - -def aRTist_translate(ID, x, y, z): - STR = ["""::PartList::Invoke """+ str(ID) +""" Translate world """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; -"""] - return STR - - -def aRTist_vis_off(): - STR = ["""::PartList::Set parts Visible off; -"""] - return STR - -def aRTist_vis_on(ID): - STR = ["""::PartList::Set """+str(ID)+""" Visible on; -"""] - return STR - -def aRTist_resize(ID, size): - STR = ["""::PartList::Invoke """+str(ID)+""" SetSize """+str(size)+""" """+str(size)+""" """+str(size)+"""; -"""] - return STR - -def aRTist_make_image(): - STR = ["""::Engine::StartStopCmd; -"""] - return STR - -def aRTist_save_image(Path): - STR = ["""::Modules::Execute ImageViewer Save16bit """+ Path +""" 1; -"""] - return STR - - - -########################## Conversions ################################ -''' Particle/Pore ''' - -R_max = D_max / 2 / 1000 # max. particle radius in mm -r_max = P_max / 2 / 1000 # max. pore radius in mm -r_min = P_min / 2 / 1000 # min. pore radius in mm - -''' Detector/Source ''' -OZ = SDD / MAG # position of object (in Z-direction) -OZ = SDD - OZ -VX = pitch / MAG # voxel size , i.e. eff. pixel size -DETxy = (DBorder * D_max) / VX / 1000 # detector size (square) in pixel - -P_xy = (DETxy / 2) * VX * 0.9 # origin of particle range[x][y] with 10% border - -############################################################################### - -P_count = N_ParX*N_ParY #No. of Particles/Pores - - -############################################################################### -''' Connect to aRTist ''' -S = aRTist_connect() - -aRTist_listen(0) - -############################################################################### -''' SETUP aRTist scene ''' -print("SETUP aRTist scene") -aRTist_sent(aRTist_setup(path_aRTist_scene)) -print("SETUP Detector aRTist-Scene") -aRTist_sent(aRTist_SETUP_detector(DetX, DetY, pitch)) -print("SETUP Source aRTist-Scene") -aRTist_sent(aRTist_SETUP_source(SDD, kV, mA)) -print("SETUP FFcorr aRTist-Scene") -aRTist_sent(aRTist_SETUP_FFcorr()) -aRTist_sent(["""set ::Xdetector(FFCorrRun) 1; -"""]) #to check!! -print("SETUP FINISH aRTist-Scene") - -############################################################################### -'''Calc Particle/Pore positions:''' -P_ID, P_RAD, P_XYZ, p_RAD, p_ID = [],[],[],[],[] # List of all particles/pores - -n = 0 #loop count -for i in range(N_ParY): - for ii in range(N_ParX): - n += 1 #increment n by 1 - if (i % 2): #ii is odd - X = 2*R_max*ii + R_max - else: #ii is even (incl. 0) - X = 2*R_max*ii # particle position x - - Y = np.sqrt(3*R_max**2)*i # particle position x - - P_XYZ.append([X, Y, OZ]) - P_ID.append(2*n-1) # Particle-ID - p_ID.append(2*n) # Pore-ID - P_RAD.append(R_max) - -print(P_ID) -print(p_ID) -print(P_XYZ) - -############################################################################## -'''Calc Pore distribution:''' -p_RAD = list(np.linspace(r_min, r_max, num=P_count)) #list of pore radii - -############################################################################## -''' Create particles and pores in aRTist ''' -n = -1 #loop count -for i in range(N_ParY): - for ii in range(N_ParX): - n += 1 #increment n by 1 - # Particle - print("Create Particle ", n+1 , "of", P_count) - aRTist_sent(aRTist_create_sphere(R_max)) - aRTist_sent(aRTist_set_material(P_ID[n], Mat_par)) - aRTist_sent(aRTist_set_position(P_ID[n], P_XYZ[n][0], P_XYZ[n][1], P_XYZ[n][2])) - - - # Pore - aRTist_sent(aRTist_create_sphere(p_RAD[n])) - aRTist_sent(aRTist_set_material(p_ID[n], Mat_pore)) - aRTist_sent(aRTist_set_position(p_ID[n], P_XYZ[n][0], P_XYZ[n][1], P_XYZ[n][2])) - - if (i == range(N_ParY)[-1]): - aRTist_sent(["""::Modules::Module""" +str(SolidModNo)+"""::Close; - """]) - -############################################################################## -'Center middle particle at [0,0,z]' - -Shift = [] -for i in range(len(P_XYZ[0])): - diff = (P_XYZ[0][i] - P_XYZ[-1][i]) / 2 - Shift.append(diff) - -aRTist_sent(aRTist_translate('Parts', Shift[0], Shift[1] , Shift[2])) - - - -####################### Save coordinates in CSV #################################### -header = ["Particle ID", "Particle Diameter", "Pore ID", "Pore Diameter", "X", "Y", "Z"] - -with open(path_save +"data.csv", "w", newline ='') as file: - write = csv.writer(file) - write.writerow(header) - - for i in range(P_count): - row = [str(P_ID[i]), str(2*P_RAD[i]), str(p_ID[i]), str(2*p_RAD[i]), str(P_XYZ[i][0]), str(P_XYZ[i][1]), str(P_XYZ[i][2])] - write.writerow(row) - - -############################################################################### -''' Close Connection to aRTist''' -S.close() - \ No newline at end of file diff --git a/Standalones/ParticlesAndPores/Create_SingleParticle+Pores.py b/Standalones/ParticlesAndPores/Create_SingleParticle+Pores.py deleted file mode 100644 index e3e7f50..0000000 --- a/Standalones/ParticlesAndPores/Create_SingleParticle+Pores.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Tue Aug 13 19:30:16 2019 -Creates and transates particles/pores -ONLY for 0 to 1 pore, faster and less expensive than creating new objects each time. -@authors: Alexander Funk, David Schumacher -""" - -import socket -import random -import numpy as np -import math -from time import sleep - -############################### Options ####################################### -''' Connection ''' -HOST = "127.0.0.1" # localhost -PORT = 3658 # port @HOST -BUFFER_SIZE = 1024 # package size -timeout = 10 # TimeOut in sec - -''' aRTist Module ''' -SolidModNo = 17 # Number of module "Solid" in aRTist (Modules/XX. Solid) - -''' Particles/Pores ''' -D_max = 100 # max particle diameter in micrometer -D_min = 90 # min particle diameter in micrometer -P_max = 45 # max pore diameter in micrometer -P_min = 10 # min pore diameter in micrometer -N_Par = 10 # No. of particles to be created -pores_max = 5 # max. no. of pores per particle -pores_min = 1 # min. no. of pores per particle -space = 5 / 1000 # space to particle boundary - -''' X-Ray Setup ''' -MAG = 200 # magnification -SDD = 400 # source-detector distance in mm -pitch = 0.1 # native pixel size (pitch) of the detector in mm -DBorder = 1.5 # detector border (1/2), Factor (particle size) - -kV = 15 # Voltage of X-ray source -mA = 100 # Current of X-ray source - -''' Paths ''' -path_aRTist_scene = "I:/Simulations/TMP/Pores/Single_Pore_Scene.aRTist" -path_save_images = "I:/Simulations/TMP/Pores/img_" - - -error = 0 - -############### aRTist functions (to be replaced by library!) ################# -''' Communication with aRTist ''' -def aRTist_connect(): - S = socket.socket() # Create socket (for TCP) - S.connect((HOST, PORT)) # Connect to aRTist - S.settimeout(timeout) - return S - -def aRTist_sent(x): - total = "" - for i in range(len(x)): - # print(i+1, "of", len(x), " commands send") - # print(x[i]) - S.send(x[i].encode()) - total = total + aRTist_listen(1) - return total - -def aRTist_listen(command_no): - total = "" - stop = False - if (command_no == 0): - S.settimeout(0.2) - while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total): # as long as server doesn't respond and doesn't contain "SUCCESS" - try: - msg = S.recv(BUFFER_SIZE).decode() # - except socket.timeout as e: - err = e.args[0] - if err == "timed out": - print("Timeout\n") - stop = True - continue - else: - if ("SUCCESS" in msg): - total = total + msg - # print(msg) - stop = True - continue - elif ("ERROR" in msg): - total = total + msg - # print(msg) - stop = True - global error - error = error + 1 - continue - else: - # print(msg) - if (command_no == 0): - print(msg) - total = total + msg - S.settimeout(timeout) - return total - -''' aRTist specific commands ''' -def aRTist_setup(Path): - STR = ["""FileIO::OpenAny """+ Path +"""; -"""] - return STR - -def aRTist_SETUP_detector(x, y, px): - STR = ["""set ::Xdetector(Type) {flat panel}; -""","""set ::Xsetup_private(DGauto) {Size}; -""","""set ::Xsetup(DetectorPixelX) """+ str((int(x))) +"""; -""","""set ::Xsetup(DetectorPixelY) """+ str((int(y))) +"""; -""","""set ::Xsetup_private(DGdx) """+ str(px) +"""; -""","""set ::Xsetup_private(DGdy) """+ str(px) +"""; -""","""set ::Xdetector(AutoD) {max}; -""","""set ::Xdetector(RefGV) 50000; -""","""::XDetector::UpdateGeometry 1; -"""] - return STR - -def aRTist_SETUP_source(pos, kV, mA): - STR = ["""set ::Xsetup(SourceSampling) {point}; -""","""set ::Xsource(Exposure) """+ str(mA) +"""; -""","""set ::Xsource(Tube) {Mono}; -""","""set ::Xsource(Voltage) """+ str(kV) +"""; -""","""::PartList::Invoke S SetPosition 0 0 """+ str(pos) +"""; -""","""::PartList::Invoke S SetRefPos 0 0 """+ str(pos) +"""; -""","""set ::Xdetector(FFCorrRun) 0; -""","""XDetector::FFCorrClearCmd; -""","""::XSource::spectrumOK; -"""] # set ::Engine::RenderPreview 0; - return STR - -def aRTist_SETUP_FFcorr(): - STR = ["""::XDetector::FFCorrGenCmd; -"""] - return STR - -def aRTist_create_sphere(R): - R = 2 * R - STR = ["""::Modules::Run Solid; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Type) {ellipsoid}; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Equilateral) 1; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(X) """+ str(R) +"""; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(PhiResolution) 80; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(ThetaResolution) 80; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(GridEllipsoid) 1; -""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(VolumeCorrect) 1; -""","""::Modules::Module""" +str(SolidModNo)+"""::GenerateCmd; -"""] - return STR - -def aRTist_set_material(ID, mat): - STR = ["""::PartList::Set """+ str(ID) +""" Material """+ mat +"""; -"""] - return STR - -def aRTist_translate(ID, x, y, z): - STR = ["""::PartList::Invoke """+ str(ID) +""" SetPosition """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; -""","""::PartList::Invoke """+ str(ID) +""" SetRefPos """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; -"""] - return STR - -def aRTist_vis_off(): - STR = ["""::PartList::Set 1 Visible off; -""","""::PartList::Set 2 Visible off; -"""] - return STR - -def aRTist_vis_on(ID): - STR = ["""::PartList::Set """+str(ID)+""" Visible on; -"""] - return STR - -def aRTist_resize(ID, size): - STR = ["""::PartList::Invoke """+str(ID)+""" SetSize """+str(size)+""" """+str(size)+""" """+str(size)+"""; -"""] - return STR - -def aRTist_make_image(): - STR = ["""::Engine::StartStopCmd; -"""] - return STR - -def aRTist_save_image(Path): - STR = ["""::Modules::Execute ImageViewer Save16bit """+ Path +""" 1; -"""] - return STR - - -# def aRTist_fire(): - # STR = ["""::Modules::Module""" +str(SolidModNo)+"""::GenerateCmd; -# """] -# ::Modules::Module""" +str(SolidModNo)+"""::Close;" - # return STR - -########################## Conversions ################################ -''' Particle/Pore ''' -R_max = D_max / 2 / 1000 # max. particle radius in mm -R_min = D_min / 2 / 1000 # min. particle radius in mm -r_max = P_max / 2 / 1000 # max. pore radius in mm -r_min = P_min / 2 / 1000 # min. pore radius in mm - -''' Detector/Source ''' -OZ = SDD / MAG # position of object (in Z-direction) -OZ = SDD - OZ -VX = pitch / MAG # voxel size , i.e. eff. pixel size -DETxy = (DBorder * D_max) / (VX * 1000) # detector size (square) in pixel - -P_xy = (DETxy / 2) * VX * 0.9 # origin of particle range[x][y] with 10% border - -############################################################################### -''' Generation of random variables and calculate objects (paricles+pores) ''' -P_ID, P_RAD, P_XYZ, p_ANZ, p_RAD, p_XYZ = [],[],[],[],[],[] # List of all particles/pores -R = np.array(range(N_Par), dtype=np.float) -for i in range(N_Par): - R[i] = round(random.uniform(R_min, R_max),3) # particle radius in mm - X = round(random.uniform(-(P_xy-R[i]), (P_xy-R[i])),3) # particle position x - Y = round(random.uniform(-(P_xy-R[i]), (P_xy-R[i])),3) # particle position y - print('Particle',i ,' RADIUS =',R[i] ,'mm') - P_ID.append(i) - P_RAD.append(R[i]) - P_XYZ.append([X, Y, OZ]) - pores = random.randint(pores_min, pores_max) # random no. of pores - r = [] #np.array(range(pores), dtype=np.float) - p_xyz = [] - for ii in range(pores): - r.append(round(random.uniform(r_min, r_max),3)) # random pore radius in mm - print('Particle',i ,' Pore',ii ,' RADIUS =', r[ii],'mm') - - ''' Generate coordinates for pore ''' - R2 = round(R[i] - space - r[ii],3) # max. sphere radius with R2+pore in sphere R - # print(R2) - R3 = round(random.uniform(0, R2),3) # sphere with random radius in R2 - theta = random.uniform(0, math.pi) - phi = random.uniform(0, 2*math.pi) - # print(theta, phi) - p_x = round((X + R3 * math.sin(theta) * math.cos(phi)),3) - p_y = round((Y + R3 * math.sin(theta) * math.sin(phi)),3) - p_z = round((OZ + R3 * math.cos(theta)),3) - p_xyz.append([p_x, p_y, p_z]) - p_ANZ.append(pores) - p_RAD.append(r) - p_XYZ.append(p_xyz) - -print(P_RAD) -print(P_XYZ) -print(p_RAD) -print(p_XYZ) -print(p_ANZ) - -###################### Save coordinates in CSV ########################### -with open(path_save_images +"data.csv", "w+") as file: - STR = "Particle_ID, P_RADIUS, P_x, P_y, P_z, No. of pores, Pore_ID, p_RADIUS, p_x, p_y, p_z" - file.write(STR + "\n") - for i in range(N_Par): - STR = ""+str(P_ID[i])+", "+str(P_RAD[i])+", "+str(P_XYZ[i][0])+", "+str(P_XYZ[i][1])+", "+str(P_XYZ[i][2]) - if p_ANZ[i] == 0: - STR = STR + ", 0, , , , , " - file.write(STR + "\n") - elif p_ANZ[i] > 0: - STR = STR + ", " +str(p_ANZ[i]) - for ii in range(p_ANZ[i]): - STR2 = STR +", "+str(ii)+", "+str(p_RAD[i][ii])+", "+str(p_XYZ[i][ii][0])+", "+str(p_XYZ[i][ii][1])+", "+str(p_XYZ[i][ii][2]) - file.write(STR2 + "\n") - -############################################################################### -''' Connect to aRTist ''' -S = aRTist_connect() - -aRTist_listen(0) - -############################################################################### -''' SETUP aRTist scene ''' -print("SETUP aRTist scene") -aRTist_sent(aRTist_setup(path_aRTist_scene)) -print("SETUP Detector aRTist-Scene") -aRTist_sent(aRTist_SETUP_detector(DETxy, DETxy, pitch)) -print("SETUP Source aRTist-Scene") -aRTist_sent(aRTist_SETUP_source(SDD, kV, mA)) -print("SETUP FFcorr aRTist-Scene") -aRTist_sent(aRTist_SETUP_FFcorr()) -aRTist_sent(["""set ::Xdetector(FFCorrRun) 1; -"""]) -print("SETUP FINISH aRTist-Scene") - -############################################################################### -''' Create particles and pores in aRTist, save image ''' -# Create two dummy spheres -aRTist_sent(aRTist_create_sphere(R_max)) -aRTist_sent(aRTist_create_sphere(r_max)) -aRTist_sent(aRTist_set_material(1, "{Ti}")) -aRTist_sent(aRTist_set_material(2, "{void}")) -#aRTist_sent(["""::Modules::Module""" +str(SolidModNo)+"""::Close; -#"""]) - -# translate spheres -for i in range(N_Par): - # particle - print("Create Particle ", i , "of", N_Par) - aRTist_sent(aRTist_vis_off()) - aRTist_sent(aRTist_vis_on(1)) - aRTist_sent(aRTist_resize(1, (2*P_RAD[i]))) - aRTist_sent(aRTist_translate(1, P_XYZ[i][0], P_XYZ[i][1], P_XYZ[i][2])) - - # pores - if p_ANZ[i] > 0: - aRTist_sent(aRTist_vis_on(2)) - aRTist_sent(aRTist_resize(2, (2*p_RAD[i][0]))) - aRTist_sent(aRTist_translate(2, p_XYZ[i][0][0], p_XYZ[i][0][1], p_XYZ[i][0][2])) - # for ii in range(p_ANZ[i]): - # acquire image - aRTist_sent(aRTist_make_image()) - # save image - aRTist_sent(aRTist_save_image((path_save_images + str(i).zfill(5) +".tif"))) - - - -############################################################################### -''' Timer for Debug ''' -for i in range(5): - print("wait ",i ," s") - sleep(1) -print("FINISH!", error, "aRTist Errors") -############################################################################### -''' Close Connection to aRTist''' -S.close() diff --git a/Standalones/ParticlesAndPores/Pore_Matrix_Scene.aRTist b/Standalones/ParticlesAndPores/Pore_Matrix_Scene.aRTist deleted file mode 100644 index d2b7087..0000000 Binary files a/Standalones/ParticlesAndPores/Pore_Matrix_Scene.aRTist and /dev/null differ diff --git a/Standalones/ParticlesAndPores/Single_Pore_Scene.aRTist b/Standalones/ParticlesAndPores/Single_Pore_Scene.aRTist deleted file mode 100644 index 29ae4fe..0000000 Binary files a/Standalones/ParticlesAndPores/Single_Pore_Scene.aRTist and /dev/null differ diff --git a/aRTist.py b/aRTist.py deleted file mode 100644 index 6709fcc..0000000 --- a/aRTist.py +++ /dev/null @@ -1,304 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Created on Mon Nov 30 12:23:40 2020 by afunkt1 based on MATLAB-scripts by dschumac -Updated on Mon May 30 17:36:00 2022 by dschumac - -@authors: dschumac. afunk1, cbellon -""" -import socket - -############################### Connection ##################################### -class Connection: - def __init__(self, Host="localhost", Port=3658, buffer_size=1024, timeout=5): - self.Host = Host - self.Port = Port - self.buffer_size = buffer_size - self.timeout = timeout - self.error = 0 - self.connect() - - def connect(self): - self.S = socket.socket() # Create socket (for TCP) - self.S.connect((self.Host, self.Port)) # Connect to aRTist - self.S.settimeout(self.timeout) - self.listen(0) - return self - - def send(self, commands, type="RESULT"): - answers = [] - for c in commands: - self.S.send(c.encode()) - answers.append(self.listen(type=type)) - return answers - - def listen(self, command_no=1, type="RESULT"): - answer = "" - stop = False - if (command_no == 0): - self.S.settimeout(0.2) - while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total): # Solange server antwortet und nicht "SUCCESS" enthält - try: - msg = self.S.recv(self.buffer_size).decode() - except BaseException as e: - err = e.args[0] - if err == "timed out": - print("Timeout\n") - answer += "RESULT Timeout\n" - #print(answer) - stop = True - continue - else: - if ("SUCCESS" in msg): - answer += msg - stop = True - continue - elif ("ERROR" in msg): - answer += msg - stop = True - #global error - self.error = self.error + 1 - continue - else: - if (command_no == 0): - print(msg) - answer += msg - self.S.settimeout(self.timeout) - if (type != "*"): - answer = self.result(answer, type) - return answer - - def result(self, answer, res='RESULT'): - start = answer.find(res+' ') - if start == -1: - return res + ' not found.' - start += len(res) + 1 - end = answer.find('\n', start) # one line per result - if answer.find('\r', start) == end-1: # care for Windows line endings - end -= 1 - return answer[start:end] - -################# Extract results from aRTist answer string ################### -def extract_result(answer, res='RESULT'): - start = answer.find(res+' ') - if start == -1: - return res + ' not found.' - start += len(res) + 1 - end = answer.find('\n', start) # one line per result - if answer.find('\r', start) == end-1: # care for Windows line endings - end -= 1 - return answer[start:end] - - -############################### Scene ######################################### -def open_scene(Path): - STR = ["""FileIO::OpenAny """+ Path +"""; - """] - return STR - -def create_Object(SolidModNo, OType, Eq, x, y, z, PhiRes, ThetaRes, Grid, VC): - STR = ["""::Modules::Run Solid; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Type) """+ str(OType) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Equilateral) """+ str(Eq) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(X) """+ str(x) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Y) """+ str(y) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(Z) """+ str(z) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(PhiResolution) """+ str(PhiRes) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(ThetaResolution) """+ str(ThetaRes) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(GridEllipsoid) """+ str(Grid) +"""; - ""","""set ::Modules::Module""" +str(SolidModNo)+"""::Solid(VolumeCorrect) """+ str(VC) +"""; - ""","""::Modules::Module""" +str(SolidModNo)+"""::GenerateCmd; - """] - return STR - -def get_Obj_IDs(): - STR = ["""PartList::Query {ID}; - """] - return STR - -def get_ObjID(name): - STR = ['PartList::Query {ID Name} -where {Name=="' +str(name)+ '"};\r\n'] - return STR #PartList::Query {ID Name Material} -where {Material=="Al"} - -def get_Obj_ID_by_Pos(pos): - #pos (e.g. 'end') - STR = ["""PartList::GetIDFromPos """+ str(pos) +"""; - """] - return STR - -def select_last_Obj(): - STR = ["""PartList::Select [PartList::GetIDFromPos end]; - """] - return STR - -def delete_all_Obj(): - STR = ["""PartList::Clear; - """] - return STR - -def count_parts(): - STR = ["""::PartList::Count; - """] - return STR - -def set_material(ID, mat): - STR = ["""::PartList::Set """+ str(ID) +""" Material """+ mat +"""; - """] - return STR - -def set_position(ID, x, y, z): - STR = ["""::PartList::Invoke """+ str(ID) +""" SetPosition """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; - ""","""::PartList::Invoke """+ str(ID) +""" SetRefPos """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; - """] - return STR - -def translate(ID, x, y, z): - STR = ["""::PartList::Invoke """+ str(ID) +""" Translate world """+ str(x) +""" """+ str(y) +""" """+ str(z) +"""; - """] - return STR - -def set_vis_AllParts(state): #state = "on"/"off" - STR = ["""::PartList::SetVisibility """+state+"""; - """] - return STR - -def set_vis(ID, state): - STR = ["""::PartList::Set """+str(ID)+""" Visible """+state+"""; - """] - return STR - -def resize(ID, sizeX, sizeY, sizeZ): - STR = ["""::PartList::Invoke """+str(ID)+""" SetSize """+str(sizeX)+""" """+str(sizeY)+""" """+str(sizeZ)+"""; - """] - return STR - - -############################### Detector ######################################### -def SETUP_detector(posZ, angleZ, x, y, px, RefPoint, GV): #Order of commands important!! -> Invoke should be reomved! - #RefPoint ('off', 'min', 'max', 'center') - STR = ["""::PartList::Invoke D SetPosition 0 0 """+ str(posZ) +"""; - ""","""::PartList::Invoke D SetRefPos 0 0 """+ str(posZ) +"""; - ""","""::PartList::Invoke D SetOrientation 0 0 """+ str(angleZ) +"""; - ""","""set ::Xdetector(AutoD) """+ RefPoint +"""; - ""","""set ::Xdetector(RefGV) """+ str(GV) +"""; - ""","""::XDetector::ExposureModeChange; - ""","""set ::Xsetup_private(DGauto) Size; - ""","""set ::Xsetup(DetectorPixelX) """+ str((int(x))) +"""; - ""","""set ::Xsetup(DetectorPixelY) """+ str((int(y))) +"""; - ""","""set ::Xsetup_private(DGdx) """+ str(px) +"""; - ""","""set ::Xsetup_private(DGdy) """+ str(px) +"""; - ""","""::XDetector::UpdateGeometry 1; - """] - return STR - -def Acq_FF(): - STR = ["""::XDetector::FFCorrGenCmd; - """] - return STR - -def AutoAcq_FF(state): - #state (0, 1) - STR = ["""set ::Xdetector(FFCorrRun) """+str(state)+"""; - """] - return STR - -def Clear_FF(): - STR = ["""XDetector::FFCorrClearCmd; - """] - return STR - -############################### Source ######################################## -def SETUP_source(posZ, kV, mA, Type, FMat, FThick): - #Type (Mono, General) - STR = ["""set ::Xsource(Exposure) """+ str(mA) +"""; - ""","""set ::Xsource(Voltage) """+ str(kV) +"""; - ""","""set ::Xsource(Tube) """+ str(Type) +"""; - ""","""set ::Xsource(FilterMaterial) """+ str(FMat) +"""; - ""","""set ::Xsource(FilterThickness) """+ str(FThick) +"""; - ""","""::PartList::Invoke S SetPosition 0 0 """+ str(posZ) +"""; - ""","""::PartList::Invoke S SetRefPos 0 0 """+ str(posZ) +"""; - ""","""::XSource::ComputeSpectrum; - """] - return STR - -def SETUP_SourceSampling(sampling): - STR = ["""set ::Xsetup(SourceSampling) """+ str(sampling) +"""; - ""","""::XSource::SelectSpotTypeEvent; - """] - return STR - -def SETUP_CalcFocalspot(width, height, fract, res): - STR = ["""set ::Xsource_private(SpotWidth) """+ str(width) +"""; - ""","""set ::Xsource_private(SpotHeight) """+ str(height) +"""; - ""","""set ::Xsource_private(SpotHeight) """+ str(height) +"""; - ""","""set ::Xsource_private(SpotLorentz) """+ str(fract) +"""; - ""","""set ::Xsource_private(SpotRes) """+ str(res) +"""; - ""","""::XSource::SetSpotProfile; - """] - return STR - -def LOAD_spectrum(SpecPath): - #Type (Mono, General) - STR = ["""::XSource::LoadSpectrum """+ SpecPath +"""; - """] - return STR - -################################# CT ########################################## -def SETUP_CT(CTModNo, angle, steps, OutDir, OutName, OutFormat, PType, RunFDK, OnlySelObj, Direction, Scat, ScatInt): - #OutFormat ({BAM CT}, TIFFs) - #PType (16bit, float) - #Direction (clockwise, counterclockwise) - #Scat (off, McRay) - STR = ["""::Modules::Run CtScan; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Angle) """+ str(angle) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Steps) """+ str(steps) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Directory) """+ OutDir +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(File) """+ OutName +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Output) """+ str(OutFormat) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(PixelType) """+ str(PType) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Feldkamp) """+ str(RunFDK) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Selected) """+ str(OnlySelObj) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Direction) """+ str(Direction) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(ScatterMode) """+ Scat +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(ScatterInterval) """+ str(ScatInt) +"""; - """] - return STR - -def SETUP_FDK(CTModNo, VType, Interp, OutFormat): - #VType (8bit, 16bit, 32bit, float) - #OutFormat ({BAM CT}, VTK, RAW) - STR = ["""::Modules::Run CtScan; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(VoxelType) """+ str(VType) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(Interpolate) """+ str(Interp) +"""; - ""","""set ::Modules::Module""" +str(CTModNo)+"""::CtScan(FileType) """+ str(OutFormat) +"""; - """] - return STR - -def Run_CT(CTModNo): - STR = ["""::Modules::Run CtScan; - ""","""::Modules::Module""" +str(CTModNo)+"""::Execute; - """] - return STR - - - -############################### Engine ######################################## -def SETUP_Preview(state): - #state (0, 1) - STR = ["""set ::Engine::RenderPreview """+str(state)+"""; - """] - return STR - -def RenderPreview(): - STR = ["""::Engine::RenderPreview; - """] - return STR - -def make_image(): - STR = ["""::Engine::StartStopCmd; - """] - return STR - -def save_image(Path): - STR = ["""::Modules::Execute ImageViewer Save16bit """+ Path +""" 1; - """] - return STR diff --git a/artistlib/__init__.py b/artistlib/__init__.py index fa13308..8a0d669 100644 --- a/artistlib/__init__.py +++ b/artistlib/__init__.py @@ -1,95 +1,19 @@ -# -*- coding: UTF-8 -*- -"""The aRTist Python library is intended to remote control and automate the radiographic simulator aRTist. - -.. include:: ./documentation.md -""" - -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions - -from numpy import append -import socket - -class Junction: - """Remote control of aRTist simulator - """ - def __init__(self, host="localhost", port=3658, bufferSize=1024, timeout=5): - self.host = host - self.port = port - self.bufferSize = bufferSize - self.timeout = timeout - self.error = 0 - self.progress = 0 - self.connect() - - def connect(self): - self.S = socket.socket() # Create socket (for TCP) - self.S.connect((self.host, self.port)) # Connect to aRTist - self.S.settimeout(self.timeout) - self.listen(0) - return self - - def send(self, command, msgType="RESULT"): - if type(command) != type([]): - c = command + '\n' - self.S.send(c.encode()) - return self.listen(msgType=msgType) - else: - answers = [] - for c in command: - c += '\n' - self.S.send(c.encode()) - answers.append(self.listen(msgType=msgType)) - return answers - - def listen(self, command_no=1, msgType="RESULT"): - answer = "" - stop = False - if (command_no == 0): - self.S.settimeout(0.2) - while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total): # Solange server antwortet und nicht "SUCCESS" enthält - try: - msg = self.S.recv(self.bufferSize).decode() - except BaseException as e: - err = e.args[0] - if err == "timed out": - print("Timeout\n") - answer += "RESULT Timeout\n" - #print(answer) - stop = True - continue - else: - if ("SUCCESS" in msg): - answer += msg - stop = True - continue - elif ("ERROR" in msg): - answer += msg - stop = True - #global error - self.error = self.error + 1 - continue - elif ("PROGRESS" in msg): - try: - self.progress = float(msg.strip('PROGRESS ')) - except: - self.progress = 0 - continue - else: - if (command_no == 0): - print(msg) - answer += msg - self.S.settimeout(self.timeout) - if (msgType != "*"): - answer = self.pick(answer, msgType) - return answer - - def pick(self, answer, res='RESULT'): - picked = '' - for a in answer.split('\n'): - if a.find(res) == 0: - picked += a[1 + len(res):].strip('\r') + '\n' - if len(picked) == 0: - return res + ' not found.' - return picked +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from . import hardware + +from .api import ArtistApi +from .connection import Connection +from .common_types import SolidModelTypes \ No newline at end of file diff --git a/artistlib/_version.py b/artistlib/_version.py deleted file mode 100644 index 6e093b4..0000000 --- a/artistlib/_version.py +++ /dev/null @@ -1,658 +0,0 @@ - -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.26 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "$Format:%d$" - git_full = "$Format:%H$" - git_date = "$Format:%ci$" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "pep440" - cfg.tag_prefix = "v" - cfg.parentdir_prefix = "" - cfg.versionfile_source = "artistlib/_version.py" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} diff --git a/artistlib/api.py b/artistlib/api.py new file mode 100644 index 0000000..2e1d1f8 --- /dev/null +++ b/artistlib/api.py @@ -0,0 +1,78 @@ +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from .connection import Connection +from .common_types import SolidModelTypes, SendTypes + +from pathlib import Path + + +class ArtistApi: + """aRTist API + """ + def __init__(self, connection: Connection = Connection()) -> None: + self.connection = connection + + def open_scene(self, scene_path: str | Path) -> None: + """Opens a aRTist scene. + + Args: + scene_path (str | Path): Path to the saved aRTist scene. + """ + if isinstance(scene_path, str): + scene_path = Path(scene_path) + scene_path = scene_path.absolute() + command = f'FileIO::OpenAny {str(scene_path)}' + self.connection.send(command) + + def get_object_ids(self) -> list[int]: + """Retuns the object ids of all objects in aRTist. + + Returns: + list[int]: _description_ + """ + command = "PartList::Query ID;\n" + result = self.connection.send(command, SendTypes.RESULT)[0] + return self.connection.string_to_list(result, int) + + def clear_objects(self) -> None: + """Clears all objects in aRTist. + """ + command = 'PartList::Clear;' + self.connection.send(command, SendTypes.RESULT) + + @property + def number_of_objects(self) -> int: + """Return the number of objects in aRTist. + + Returns: + int: number of objects. + """ + command = '::PartList::Count;\n' + return int(self.connection.send(command, SendTypes.RESULT)[0]) + + def set_material(self, object_id: str | int, material: str): + """Sets the material of an object in aRTist. + + Args: + object_id (str | int): The object, which material gets set. + material (str): Materia, which gets set. As string! + """ + command = f'::PartList::Set {str(object_id)} Material {material};' + self.connection.send(command, SendTypes.RESULT) + + + diff --git a/artistlib/common_types.py b/artistlib/common_types.py new file mode 100644 index 0000000..e573c62 --- /dev/null +++ b/artistlib/common_types.py @@ -0,0 +1,37 @@ +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from enum import IntEnum + + +class SendTypes: + RESULT = 'RESULT' + TIME_OUT = 'timed out' + SUCCESS = 'SUCCESS' + ERROR = 'ERROR' + ALL = '*' + +class SolidModelTypes(IntEnum): + CUBOID = 0 + ELLIPSSOID = 1 + CYLINDER = 2 + TUBE = 3 + CONE = 4 + TEXT = 5 + WEDGE = 6 + STEP_WEDGE = 7 + + +class CommandTypes(IntEnum): + CONNECTION = 0 + SEND = 1 \ No newline at end of file diff --git a/artistlib/connection.py b/artistlib/connection.py new file mode 100644 index 0000000..4710f92 --- /dev/null +++ b/artistlib/connection.py @@ -0,0 +1,133 @@ +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import socket +from .common_types import SendTypes, CommandTypes + + + + +class Connection: + """Main connection class for the aRTist API + """ + def __init__(self, host: str = "localhost", port: int = 3658, buffer_size: int = 1024, timeout: float = 5., listen_timeout: float = 0.2, verbose: bool = True): + self.host = host + self.port = port + self.buffer_size = buffer_size + self.timeout = timeout + self.listen_timeout = listen_timeout + self.verbose = verbose + self.error = 0 + + self.connect() + + def connect(self): + """Establish connection to the aRTist remote console + """ + self.socket = socket.socket() # Create socket (for TCP) + self.socket.connect((self.host, self.port)) # Connect to aRTist + self.socket.settimeout(self.timeout) + self.listen(command_no=CommandTypes.CONNECTION) + + def send(self, commands: str | list, type: str = SendTypes.RESULT) -> str: + """Send a command to the aRTist remote console. + + Args: + commands (str | list): TCL / TK command. + type (str, optional): Defines the send and result type. Defaults to SendTypes.RESULT. + + Returns: + str: Result of the command. Dependend of the send type + """ + if isinstance(commands, str): + commands = [commands] + answers = [] + for c in commands: + self.socket.send(c.encode()) + answers.append(self.listen(type=type)) + return answers + + def listen(self, command_no: int = CommandTypes.SEND, type: str = SendTypes.RESULT): + answer = "" + stop = False + if (command_no == CommandTypes.CONNECTION): + self.socket.settimeout(0.2) + while not stop:# and ("SUCCESS" not in total) and ("ERROR" not in total): # Solange server antwortet und nicht "SUCCESS" enthält + try: + msg = self.socket.recv(self.buffer_size).decode() + except BaseException as e: + err = e.args[0] + if err == SendTypes.TIME_OUT: + answer += "RESULT Timeout\n" + stop = True + continue + else: + if SendTypes.SUCCESS in msg: + answer += msg + stop = True + continue + elif SendTypes.ERROR in msg: + answer += msg + stop = True + #global error + self.error = self.error + 1 + continue + else: + if command_no == 0: + print(msg) if self.verbose else None + answer += msg + self.socket.settimeout(self.timeout) + if type != SendTypes.ALL: + answer = self.result(answer, type) + return answer + + def result(self, answer: str, res: str = SendTypes.RESULT): + """_summary_ + + Args: + answer (str): _description_ + res (str, optional): _description_. Defaults to SendTypes.RESULT. + + Returns: + _type_: _description_ + """ + start = answer.find(res+' ') + if start == -1: + return res + ' not found.' + start += len(res) + 1 + end = answer.find('\n', start) # one line per result + if answer.find('\r', start) == end-1: # care for Windows line endings + end -= 1 + return answer[start:end] + + @staticmethod + def extract_result(answer: str, res: str = SendTypes.RESULT): + start = answer.find(res+' ') + if start == -1: + return res + ' not found.' + start += len(res) + 1 + end = answer.find('\n', start) # one line per result + if answer.find('\r', start) == end-1: # care for Windows line endings + end -= 1 + return answer[start:end] + + @staticmethod + def string_to_list(message: str, dtype: callable = float): + return_list = list() + for element in message.split(' '): + return_list.append(dtype(element)) + return return_list + + diff --git a/artistlib/documentation.md b/artistlib/documentation.md deleted file mode 100644 index 343cdf8..0000000 --- a/artistlib/documentation.md +++ /dev/null @@ -1,64 +0,0 @@ -**Hint:** This project is in its early stages and may change significantly over time. - -Getting started -=============== - -Requirements ------------- -A **Python 3** environment (Python 3.8 or higher) is required. The following Python packages are required as well. They usually come with a Python environment, or can be installed there easily: - -* none so far. - - -Installation ------------- - -If you want to **install** the package in your Python environment, you can use [pip]. For example, you can run the following command to make the toolbox available: - - pip install artistlib - -[pip]: https://pip.pypa.io - -To use the package **without installation**, you need to download the package manually. You have the following three options: - -* Download the package [from PyPi]. You will get a zipped file called `artistlib-X.X.X.tar.gz` (where X.X.X is the current version number). Open or unpack this file to get to its contents. -* Download the repository [from GitHub]: press the *clone* button to download a ZIP file. Unpack it or open it to see its contents. -* You can also clone the repository from GitHub via the terminal: - - `git clone https://github.com/BAMresearch/aRTist-PythonLib.git` - -From any of these three options, you will get the complete package source code. It contains a folder called `artistlib`. If you want to use the library from your Python scripts without installing it, you need to copy the folder `artistlib` to the location of your Python scripts to make the package available. - - -[from GitHub]: https://github.com/BAMresearch/aRTist-PythonLib -[from PyPi]: https://pypi.org/project/artistlib/ - -Usage ------ - -Please make sure that aRTist is running and waiting for remote connection (menu: Tools>Enable remote access). - -The following example code shows the basic usage: - -```python -.. include:: ../example_artistlib.py -``` - -About -===== - -The aRTist library was developed for utilize the Python scripting of the radiographic simulator [aRTist]. - -The software is released under the **Apache 2.0 license,** its source code is available [on GitHub]. - -[aRTist]: https://artist.bam.de -[on GitHub]: https://github.com/BAMresearch/aRTist-PythonLib - -Contributors ------------- -The following people contributed to code and documentation of package: - -* Alexander Funke -* David Schumacher -* Carsten Bellon -* David Plotzki \ No newline at end of file diff --git a/artistlib/hardware/__init__.py b/artistlib/hardware/__init__.py new file mode 100644 index 0000000..2fecc2a --- /dev/null +++ b/artistlib/hardware/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .xray_source import ArtistXraySource \ No newline at end of file diff --git a/artistlib/hardware/xray_source.py b/artistlib/hardware/xray_source.py new file mode 100644 index 0000000..0d20583 --- /dev/null +++ b/artistlib/hardware/xray_source.py @@ -0,0 +1,51 @@ +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from ..connection import Connection +from ..api import ArtistApi +from ..common_types import SendTypes + + +class ArtistXraySource: + """Wrapper for the aRTist xray source + """ + def __init__(self, connection: Connection | ArtistApi) -> None: + """aRTist xray source. + + Args: + connection (Connection | ArtistApi): Connection to aRTist. Note you should only use one connection for your python script. + """ + + if isinstance(connection, ArtistApi): + connection = connection.connection + + self.connection = connection + + @property + def voltage_kv(self) -> float: + command = 'array get Xsource Voltage;\n' + return_value = self.connection.send(command, SendTypes.RESULT)[0] + return_value = return_value.split(' ')[1] + return float(return_value) + + @voltage_kv.setter + def voltage_kv(self, voltage_kv: float) -> None: + commands = [f'set ::Xsource(Voltage) {voltage_kv};' + '::XSource::ComputeSpectrum;'] + self.connection.send(commands) + + @property + def exposure_ma(self): + ... \ No newline at end of file diff --git a/build.sh b/build.sh deleted file mode 100644 index dcd830f..0000000 --- a/build.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -rm -R dist -rm -R artistlib.egg-info -python -m build - -# twine upload dist/* \ No newline at end of file diff --git a/build_html.sh b/build_html.sh deleted file mode 100644 index 18e650d..0000000 --- a/build_html.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -# Builds the HTML documentation using pdoc3 -# and moves it to the "docs" folder (instead of docs/artistlib). -pdoc --force --html --template-dir "docs/templates" -o "docs/" artistlib -cp -R docs/artistlib/* docs/ -rm -R docs/artistlib -###pdoc --logo "artistlib.png" --template-dir "docs/templates" -o "docs/" artistlib -###rm -R docs/artistlib \ No newline at end of file diff --git a/build_pdf.sh b/build_pdf.sh deleted file mode 100644 index 34c26c2..0000000 --- a/build_pdf.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -# Builds the documentation as a PDF file, -# using pdoc3 to create a complete Markdown file, -# which is then passed to pandoc to create a LaTeX -# file and a PDF using XeLaTeX. -pdoc --force --pdf artistlib > docs/artistlib.md -pandoc --metadata=title:"aRTsit PythonLib Documentation" --from=markdown+abbreviations+tex_math_single_backslash --pdf-engine=xelatex --variable=mainfont:"DejaVu Sans" --toc --toc-depth=1 --output=docs/artistlib.pdf docs/artistlib.md -rm docs/artistlib.md \ No newline at end of file diff --git a/docs/artistlib.png b/docs/artistlib.png deleted file mode 100644 index 18bf79c..0000000 Binary files a/docs/artistlib.png and /dev/null differ diff --git a/docs/favicon.ico b/docs/favicon.ico deleted file mode 100644 index ae77cce..0000000 Binary files a/docs/favicon.ico and /dev/null differ diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index 6045865..0000000 --- a/docs/index.html +++ /dev/null @@ -1,458 +0,0 @@ - - - - - - -artistlib API documentation - - - - - - - - - - - - - -
-
-
-

Package artistlib

-
-
-

The aRTist Python library is intended to remote control and automate the radiographic simulator aRTist.

-

Hint: This project is in its early stages and may change significantly over time.

-

Getting started

-

Requirements

-

A Python 3 environment (Python 3.8 or higher) is required. The following Python packages are required as well. They usually come with a Python environment, or can be installed there easily:

-
    -
  • none so far.
  • -
-

Installation

-

If you want to install the package in your Python environment, you can use pip. For example, you can run the following command to make the toolbox available:

-
pip install artistlib
-
-

To use the package without installation, you need to download the package manually. You have the following three options:

-
    -
  • Download the package from PyPi. You will get a zipped file called artistlib-X.X.X.tar.gz (where X.X.X is the current version number). Open or unpack this file to get to its contents.
  • -
  • Download the repository from GitHub: press the clone button to download a ZIP file. Unpack it or open it to see its contents.
  • -
  • -

    You can also clone the repository from GitHub via the terminal:

    -

    git clone https://github.com/BAMresearch/aRTist-PythonLib.git

    -
  • -
-

From any of these three options, you will get the complete package source code. It contains a folder called artistlib. If you want to use the library from your Python scripts without installing it, you need to copy the folder artistlib to the location of your Python scripts to make the package available.

-

Usage

-

Please make sure that aRTist is running and waiting for remote connection (menu: Tools>Enable remote access).

-

The following example code shows the basic usage:

-
import artistlib as a
-
-# connect to aRTist (default: host='localhost', port=3658) 
-rc = a.Junction()
-
-# single command
-# print aRTist's version number
-ver = a.Junction.send(rc, '::aRTist::GetVersion full')
-print(ver)
-
-# list of commands
-# - load a project
-# - run the simulation
-# - save the resulting projection from the image viewer
-cmds = [
-  'FileIO::OpenAny $Xray(LibraryDir)/ExampleProjects/Schlumpfmark.aRTist',
-  'Engine::GoCmd',
-  'Modules::Invoke ImageViewer SaveFile [file join $env(HOME) Pictures/artistlib.tif] true']
-a.Junction.send(rc, cmds)
-
-# list of commands (2)
-# - load a project
-# - run the simulation without viewing the result
-# - save the final projection 
-# - delete the images to release the memory
-cmds = [
-  'FileIO::OpenAny $Xray(LibraryDir)/ExampleProjects/aRTist.aRTist',
-  'set imgList [Engine::Go]',
-  'Image::SaveFile [lindex $imgList 0] [file join $env(HOME) Pictures/artistlib2.tif] true',
-  'foreach i $imgList {$i Delete}']
-a.Junction.send(rc, cmds)
-
-

About

-

The aRTist library was developed for utilize the Python scripting of the radiographic simulator aRTist.

-

The software is released under the Apache 2.0 license, its source code is available on GitHub.

-

Contributors

-

The following people contributed to code and documentation of package:

-
    -
  • Alexander Funke
  • -
  • David Schumacher
  • -
  • Carsten Bellon
  • -
  • David Plotzki
  • -
-
- -Expand source code - -
# -*- coding: UTF-8 -*-
-"""The aRTist Python library is intended to remote control and automate the radiographic simulator aRTist.
-
-.. include:: ./documentation.md
-"""
-
-from ._version import get_versions
-__version__ = get_versions()['version']
-del get_versions
-
-from numpy import append
-import socket
-
-class Junction:
-    """Remote control of aRTist simulator this is a test
-    """
-    def __init__(self, host="localhost", port=3658, bufferSize=1024, timeout=5):
-        self.host = host
-        self.port = port
-        self.bufferSize = bufferSize
-        self.timeout = timeout
-        self.error = 0
-        self.progress = 0
-        self.connect()
-
-    def connect(self):
-        self.S = socket.socket()                        # Create socket (for TCP)
-        self.S.connect((self.host, self.port))          # Connect to aRTist
-        self.S.settimeout(self.timeout)
-        self.listen(0)
-        return self
-
-    def send(self, command, msgType="RESULT"):
-        if type(command) != type([]):
-            c = command + '\n'
-            self.S.send(c.encode())
-            return self.listen(msgType=msgType)
-        else:
-            answers = []
-            for c in command:
-                c += '\n'
-                self.S.send(c.encode())
-                answers.append(self.listen(msgType=msgType))
-            return answers
-
-    def listen(self, command_no=1, msgType="RESULT"):
-        answer = ""
-        stop = False
-        if (command_no == 0):
-            self.S.settimeout(0.2)
-        while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total):     # Solange server antwortet und nicht "SUCCESS" enthält
-            try:
-                msg = self.S.recv(self.bufferSize).decode()
-            except BaseException as e:
-                err = e.args[0]
-                if err == "timed out":
-                    print("Timeout\n")
-                    answer += "RESULT Timeout\n"
-                    #print(answer)
-                    stop = True
-                    continue
-            else:
-                if ("SUCCESS" in msg):
-                    answer += msg
-                    stop = True
-                    continue
-                elif ("ERROR" in msg):
-                    answer += msg
-                    stop = True
-                    #global error
-                    self.error = self.error + 1 
-                    continue
-                elif ("PROGRESS" in msg):
-                    try:
-                        self.progress = float(msg.strip('PROGRESS '))
-                    except:
-                        self.progress = 0
-                    continue
-                else:
-                    if (command_no == 0):
-                        print(msg)
-                    answer += msg
-        self.S.settimeout(self.timeout)
-        if (msgType != "*"):
-            answer = self.pick(answer, msgType)
-        return answer
-
-    def pick(self, answer, res='RESULT'):
-        picked = ''
-        for a in answer.split('\n'):
-            if a.find(res) == 0:
-                picked += a[1 + len(res):].strip('\r') + '\n'
-        if len(picked) == 0:
-            return res + ' not found.'
-        return picked
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class Junction -(host='localhost', port=3658, bufferSize=1024, timeout=5) -
-
-

Remote control of aRTist simulator

-
- -Expand source code - -
class Junction:
-    """Remote control of aRTist simulator
-    """
-    def __init__(self, host="localhost", port=3658, bufferSize=1024, timeout=5):
-        self.host = host
-        self.port = port
-        self.bufferSize = bufferSize
-        self.timeout = timeout
-        self.error = 0
-        self.progress = 0
-        self.connect()
-
-    def connect(self):
-        self.S = socket.socket()                        # Create socket (for TCP)
-        self.S.connect((self.host, self.port))          # Connect to aRTist
-        self.S.settimeout(self.timeout)
-        self.listen(0)
-        return self
-
-    def send(self, command, msgType="RESULT"):
-        if type(command) != type([]):
-            c = command + '\n'
-            self.S.send(c.encode())
-            return self.listen(msgType=msgType)
-        else:
-            answers = []
-            for c in command:
-                c += '\n'
-                self.S.send(c.encode())
-                answers.append(self.listen(msgType=msgType))
-            return answers
-
-    def listen(self, command_no=1, msgType="RESULT"):
-        answer = ""
-        stop = False
-        if (command_no == 0):
-            self.S.settimeout(0.2)
-        while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total):     # Solange server antwortet und nicht "SUCCESS" enthält
-            try:
-                msg = self.S.recv(self.bufferSize).decode()
-            except BaseException as e:
-                err = e.args[0]
-                if err == "timed out":
-                    print("Timeout\n")
-                    answer += "RESULT Timeout\n"
-                    #print(answer)
-                    stop = True
-                    continue
-            else:
-                if ("SUCCESS" in msg):
-                    answer += msg
-                    stop = True
-                    continue
-                elif ("ERROR" in msg):
-                    answer += msg
-                    stop = True
-                    #global error
-                    self.error = self.error + 1 
-                    continue
-                elif ("PROGRESS" in msg):
-                    try:
-                        self.progress = float(msg.strip('PROGRESS '))
-                    except:
-                        self.progress = 0
-                    continue
-                else:
-                    if (command_no == 0):
-                        print(msg)
-                    answer += msg
-        self.S.settimeout(self.timeout)
-        if (msgType != "*"):
-            answer = self.pick(answer, msgType)
-        return answer
-
-    def pick(self, answer, res='RESULT'):
-        picked = ''
-        for a in answer.split('\n'):
-            if a.find(res) == 0:
-                picked += a[1 + len(res):].strip('\r') + '\n'
-        if len(picked) == 0:
-            return res + ' not found.'
-        return picked
-
-

Methods

-
-
-def connect(self) -
-
-
-
- -Expand source code - -
def connect(self):
-    self.S = socket.socket()                        # Create socket (for TCP)
-    self.S.connect((self.host, self.port))          # Connect to aRTist
-    self.S.settimeout(self.timeout)
-    self.listen(0)
-    return self
-
-
-
-def listen(self, command_no=1, msgType='RESULT') -
-
-
-
- -Expand source code - -
def listen(self, command_no=1, msgType="RESULT"):
-    answer = ""
-    stop = False
-    if (command_no == 0):
-        self.S.settimeout(0.2)
-    while (not stop):# and ("SUCCESS" not in total) and ("ERROR" not in total):     # Solange server antwortet und nicht "SUCCESS" enthält
-        try:
-            msg = self.S.recv(self.bufferSize).decode()
-        except BaseException as e:
-            err = e.args[0]
-            if err == "timed out":
-                print("Timeout\n")
-                answer += "RESULT Timeout\n"
-                #print(answer)
-                stop = True
-                continue
-        else:
-            if ("SUCCESS" in msg):
-                answer += msg
-                stop = True
-                continue
-            elif ("ERROR" in msg):
-                answer += msg
-                stop = True
-                #global error
-                self.error = self.error + 1 
-                continue
-            elif ("PROGRESS" in msg):
-                try:
-                    self.progress = float(msg.strip('PROGRESS '))
-                except:
-                    self.progress = 0
-                continue
-            else:
-                if (command_no == 0):
-                    print(msg)
-                answer += msg
-    self.S.settimeout(self.timeout)
-    if (msgType != "*"):
-        answer = self.pick(answer, msgType)
-    return answer
-
-
-
-def pick(self, answer, res='RESULT') -
-
-
-
- -Expand source code - -
def pick(self, answer, res='RESULT'):
-    picked = ''
-    for a in answer.split('\n'):
-        if a.find(res) == 0:
-            picked += a[1 + len(res):].strip('\r') + '\n'
-    if len(picked) == 0:
-        return res + ' not found.'
-    return picked
-
-
-
-def send(self, command, msgType='RESULT') -
-
-
-
- -Expand source code - -
def send(self, command, msgType="RESULT"):
-    if type(command) != type([]):
-        c = command + '\n'
-        self.S.send(c.encode())
-        return self.listen(msgType=msgType)
-    else:
-        answers = []
-        for c in command:
-            c += '\n'
-            self.S.send(c.encode())
-            answers.append(self.listen(msgType=msgType))
-        return answers
-
-
-
-
-
-
-
- -
- - - diff --git a/docs/templates/head.mako b/docs/templates/head.mako deleted file mode 100644 index 9897e5a..0000000 --- a/docs/templates/head.mako +++ /dev/null @@ -1,25 +0,0 @@ -<%! - from pdoc.html_helpers import minify_css -%> -<%def name="homelink()" filter="minify_css"> - .homelink { - display: block; - font-size: 2em; - font-weight: bold; - color: #555; - padding-bottom: .5em; - border-bottom: 1px solid silver; - } - .homelink:hover { - color: inherit; - } - .homelink img { - max-width:35%; - max-height: 5em; - margin: auto; - margin-bottom: .3em; - } - - - - diff --git a/docs/templates/logo.mako b/docs/templates/logo.mako deleted file mode 100644 index a327aae..0000000 --- a/docs/templates/logo.mako +++ /dev/null @@ -1,5 +0,0 @@ -
- - artistlib - -
diff --git a/example.py b/example.py deleted file mode 100644 index 9282177..0000000 --- a/example.py +++ /dev/null @@ -1,12 +0,0 @@ - -import aRTist as a - -rc = a.Connection() - -ver = a.Connection.send(rc, ['::aRTist::GetVersion;\n'])[0] -print(ver) - -# write at aRTist Console -cmd = 'puts "aRTist ' + ver + ' remote controlled by >>>example.py<<<."\n' -a.Connection.send(rc, [cmd]) -print('Some text written to aRTist\'s console.') \ No newline at end of file diff --git a/example_artistlib.py b/example_artistlib.py deleted file mode 100644 index 24a7210..0000000 --- a/example_artistlib.py +++ /dev/null @@ -1,31 +0,0 @@ -import artistlib as a - -# connect to aRTist (default: host='localhost', port=3658) -rc = a.Junction() - -# single command -# print aRTist's version number -ver = a.Junction.send(rc, '::aRTist::GetVersion full') -print(ver) - -# list of commands -# - load a project -# - run the simulation -# - save the resulting projection from the image viewer -cmds = [ - 'FileIO::OpenAny $Xray(LibraryDir)/ExampleProjects/Schlumpfmark.aRTist', - 'Engine::GoCmd', - 'Modules::Invoke ImageViewer SaveFile [file join $env(HOME) Pictures/artistlib.tif] true'] -a.Junction.send(rc, cmds) - -# list of commands (2) -# - load a project -# - run the simulation without viewing the result -# - save the final projection -# - delete the images to release the memory -cmds = [ - 'FileIO::OpenAny $Xray(LibraryDir)/ExampleProjects/aRTist.aRTist', - 'set imgList [Engine::Go]', - 'Image::SaveFile [lindex $imgList 0] [file join $env(HOME) Pictures/artistlib2.tif] true', - 'foreach i $imgList {$i Delete}'] -a.Junction.send(rc, cmds) \ No newline at end of file diff --git a/example_receive_data.py b/example_receive_data.py deleted file mode 100644 index f5adba9..0000000 --- a/example_receive_data.py +++ /dev/null @@ -1,30 +0,0 @@ - -import aRTist as a -import base64 - -rc = a.Connection() - -ch = a.Connection.send(rc, ['::RemoteControl::GetCurrentChannel\n'])[0] - -# send string "qwer" as data from aRTist to Python -rdata = a.Connection.send(rc, ['::RemoteControl::SendData '+ch+' "qwer";\n'], '*')[0] -print('<1>'+rdata+'<1>') -rdata_b64 = a.Connection.result(rc, rdata, 'BASE64') -print('<2>'+rdata_b64+'<2>') -rdata_txt = str(base64.b64decode(rdata_b64), 'utf-8') -print('<3>'+rdata_txt+'<3>') - -# reduce the viewer image width just to have a tiny image for the example -a.Connection.send(rc, [ - 'set Xsetup_private(DGauto) Resolution\n', - 'set Xsetup(DetectorPixelX) 10\n', - 'XDetector::UpdateGeometry $::XDetector::widget(XPixel)\n' -]) - -# send aRTist viewer image to Python -a_img = a.Connection.send(rc, ['::Modules::Invoke ImageViewer GetCurrentImage\n'])[0] -print('<4>'+a_img+'<4>') -idata = a.Connection.send(rc, ['::RemoteControl::SendImage '+a_img+';\n'], '*')[0] -print('<5>'+idata+'<5>') -# Attention: Larger images will result in multiple BASE64 lines, but so far aRTist.Connection.result() returns the first line only. - diff --git a/examples/example_api.py b/examples/example_api.py new file mode 100644 index 0000000..a516e58 --- /dev/null +++ b/examples/example_api.py @@ -0,0 +1,44 @@ +# Copyright 2023 Simon Wittl (Deggendorf Institute of Technology) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import artistlib + +def main(): + ### Test Connection() class + connection = artistlib.Connection() + ver = connection.send(['::aRTist::GetVersion;\n']) + cmd = f'puts "aRTist {ver} remote controlled by >>>example.py<<<."\n' + connection.send(cmd) + print('Some text written to aRTist\'s console.') + + + ### Test API + artist = artistlib.ArtistApi() # Create handle + object_ids = artist.get_object_ids() # Get list of all object ids of aRTist + print(artist.number_of_objects) # print the number of objects + artist.set_material(object_ids[0], 'Al') # Change the material of an object. + + ### Hardware components as python class + + xray_source = artistlib.hardware.ArtistXraySource(artist) # Create a hardware object of the xray source, the same connection object is used. + current_voltage = xray_source.voltage_kv # Wrap the properties of the aRTist xray source as properties of a python class + print(f'Current voltage in aRTist: {current_voltage}') + + xray_source.voltage_kv = 20. # Wrap the python setter + changed_voltage = xray_source.voltage_kv + print(f'Changed voltage in aRTist: {changed_voltage}') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/licence.md b/licence.md new file mode 100644 index 0000000..75d63f1 --- /dev/null +++ b/licence.md @@ -0,0 +1,16 @@ + + diff --git a/project.toml b/project.toml deleted file mode 100644 index f56da58..0000000 --- a/project.toml +++ /dev/null @@ -1,7 +0,0 @@ -[build-system] -requires = [ - "setuptools>=42", - "versioneer" - "wheel" -] -build-backend = "setuptools.build_meta" diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9a12a50 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +setuptools~=56.2.0 +numpy~=1.20.3 \ No newline at end of file diff --git a/setup.cfg b/setup.cfg index f81c5e6..8b33189 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,12 +1,35 @@ +# setup.cfg file at the root directory +[metadata] +name = artistlib +version = 1.0.0 +author = Simon Wittl +author_email = simon.wittl@th-deg.de +description = Python API for the XRay simulation software aRTist +long_description = Python API for the BAM Xray simulation software aRTist. Most GUI elements are wrapped and called via the remote TCL/TK interface to allow scripting in python. Only for reasearch purposes. +python_requires = >=3.7, <4 +license = AL-2 +classifiers = + Framework :: numpy + Programming Language :: Python :: 3 -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -VCS = git -style = pep440 -versionfile_source = artistlib/_version.py -versionfile_build = artistlib/_version.py -tag_prefix = v -parentdir_prefix = +[options] +include_package_data = True +packages = find: +python_requires = >=3.7 +install_requires = + wheel + numpy + + +[options.packages.find] +exclude = + data* + workspace* + build* + +[build-system] +requires = ["setuptools>=42", "wheel"] + +[bdist_wheel] +universal = 0 +python-tag = 3.9 diff --git a/setup.py b/setup.py index 2aa7607..7a0a7c2 100644 --- a/setup.py +++ b/setup.py @@ -1,26 +1,18 @@ -from setuptools import setup -import versioneer +# Copyright 2023 TH DEGGENDORF (contact simon.wittl@th-deg.de) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + -with open("README.md", "r", encoding="utf-8") as fh: - long_description = fh.read() +from setuptools import setup -setup(name='artistlib', - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - description='aRTist Python library', - url='https://github.com/BAMresearch/aRTist-PythonLib', - author='Carsten Bellon', - author_email='Carsten.Bellon@bam.de', - long_description=long_description, - long_description_content_type="text/markdown", - license='Apache 2.0', - packages=['artistlib'], - classifiers=[ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: Apache Software License", - "Operating System :: OS Independent", - "Natural Language :: English", - "Topic :: Multimedia :: Graphics :: Graphics Conversion" - ], - zip_safe=False) - \ No newline at end of file +setup() diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 223db1d..0000000 --- a/versioneer.py +++ /dev/null @@ -1,2194 +0,0 @@ - -# Version: 0.26 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain (Unlicense) -* Compatible with: Python 3.7, 3.8, 3.9, 3.10 and pypy3 -* [![Latest Version][pypi-image]][pypi-url] -* [![Build Status][travis-image]][travis-url] - -This is a tool for managing a recorded version number in setuptools-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -Versioneer provides two installation modes. The "classic" vendored mode installs -a copy of versioneer into your repository. The experimental build-time dependency mode -is intended to allow you to skip this step and simplify the process of upgrading. - -### Vendored mode - -* `pip install versioneer` to somewhere in your $PATH -* add a `[tool.versioneer]` section to your `pyproject.toml or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* run `versioneer install --vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -### Build-time dependency mode - -* `pip install versioneer` to somewhere in your $PATH -* add a `[tool.versioneer]` section to your `pyproject.toml or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* add `versioneer` to the `requires` key of the `build-system` table in - `pyproject.toml`: - ```toml - [build-system] - requires = ["setuptools", "versioneer"] - build-backend = "setuptools.build_meta" - ``` -* run `versioneer install --no-vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other languages) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg` and `pyproject.toml`, if necessary, - to include any new configuration settings indicated by the release notes. - See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install --[no-]vendor` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - -## Similar projects - -* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time - dependency -* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of - versioneer -* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools - plugin - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg -[pypi-url]: https://pypi.python.org/pypi/versioneer/ -[travis-image]: -https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg -[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer - -""" -# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring -# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements -# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error -# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with -# pylint:disable=attribute-defined-outside-init,too-many-arguments - -import configparser -import errno -import json -import os -import re -import subprocess -import sys -from pathlib import Path -from typing import Callable, Dict -import functools -try: - import tomli - have_tomli = True -except ImportError: - have_tomli = False - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - my_path = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(my_path)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root): - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise OSError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - root = Path(root) - pyproject_toml = root / "pyproject.toml" - setup_cfg = root / "setup.cfg" - section = None - if pyproject_toml.exists() and have_tomli: - try: - with open(pyproject_toml, 'rb') as fobj: - pp = tomli.load(fobj) - section = pp['tool']['versioneer'] - except (tomli.TOMLDecodeError, KeyError): - pass - if not section: - parser = configparser.ConfigParser() - with open(setup_cfg) as cfg_file: - parser.read_file(cfg_file) - parser.get("versioneer", "VCS") # raise error if missing - - section = parser["versioneer"] - - cfg = VersioneerConfig() - cfg.VCS = section['VCS'] - cfg.style = section.get("style", "") - cfg.versionfile_source = section.get("versionfile_source") - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = section.get("tag_prefix") - if cfg.tag_prefix in ("''", '""', None): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - cfg.verbose = section.get("verbose") - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -LONG_VERSION_PY['git'] = r''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.26 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Callable, Dict -import functools - - -def get_keywords(): - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_config(): - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError: - e = sys.exc_info()[1] - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%%d" %% (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions(): - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs): - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords(keywords, tag_prefix, verbose): - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(versionfile_source, ipy): - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [versionfile_source] - if ipy: - files.append(ipy) - if "VERSIONEER_PEP518" not in globals(): - try: - my_path = __file__ - if my_path.endswith(".pyc") or my_path.endswith(".pyo"): - my_path = os.path.splitext(my_path)[0] + ".py" - versioneer_file = os.path.relpath(my_path) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - with open(".gitattributes", "r") as fobj: - for line in fobj: - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - break - except OSError: - pass - if not present: - with open(".gitattributes", "a+") as fobj: - fobj.write(f"{versionfile_source} export-subst\n") - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir(parentdir_prefix, root, verbose): - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.26) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename): - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except OSError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces): - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver): - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces): - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces): - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces): - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces): - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces): - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces, style): - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools subclasses used by Versioneer. - - If the package uses a different cmdclass (e.g. one from numpy), it - should be provide as an argument. - """ - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to setuptools - from setuptools import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # pip install -e . and setuptool/editable_wheel will invoke build_py - # but the build_py command is not expected to copy any files. - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py = cmds['build_py'] - else: - from setuptools.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - if getattr(self, "editable_mode", False): - # During editable installs `.py` and data files are - # not copied to build_lib - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext = cmds['build_ext'] - else: - from setuptools.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_ext.run(self) - if self.inplace: - # build_ext --inplace will only build extensions in - # build/lib<..> dir with no _version.py to write to. - # As in place builds will already have a _version.py - # in the module dir, we do not need to write one. - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - if not os.path.exists(target_versionfile): - print(f"Warning: {target_versionfile} does not exist, skipping " - "version update. This can happen if you are running build_ext " - "without first running build_py.") - return - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.setuptools_buildexe import py2exe as _py2exe - except ImportError: - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # sdist farms its file list building out to egg_info - if 'egg_info' in cmds: - _sdist = cmds['egg_info'] - else: - from setuptools.command.egg_info import egg_info as _egg_info - - class cmd_egg_info(_egg_info): - def find_sources(self): - # egg_info.find_sources builds the manifest list and writes it - # in one shot - super().find_sources() - - # Modify the filelist and normalize it - root = get_root() - cfg = get_config_from_root(root) - self.filelist.append('versioneer.py') - if cfg.versionfile_source: - # There are rare cases where versionfile_source might not be - # included by default, so we must be explicit - self.filelist.append(cfg.versionfile_source) - self.filelist.sort() - self.filelist.remove_duplicates() - - # The write method is hidden in the manifest_maker instance that - # generated the filelist and was thrown away - # We will instead replicate their final normalization (to unicode, - # and POSIX-style paths) - from setuptools import unicode_utils - normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') - for f in self.filelist.files] - - manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') - with open(manifest_filename, 'w') as fobj: - fobj.write('\n'.join(normalized)) - - cmds['egg_info'] = cmd_egg_info - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist = cmds['sdist'] - else: - from setuptools.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir, files): - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -OLD_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - -INIT_PY_SNIPPET = """ -from . import {0} -__version__ = {0}.get_versions()['version'] -""" - - -def do_setup(): - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (OSError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except OSError: - old = "" - module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] - snippet = INIT_PY_SNIPPET.format(module) - if OLD_SNIPPET in old: - print(" replacing boilerplate in %s" % ipy) - with open(ipy, "w") as f: - f.write(old.replace(OLD_SNIPPET, snippet)) - elif snippet not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(snippet) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - ipy = None - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -def setup_command(): - """Set up Versioneer and exit with appropriate error code.""" - errors = do_setup() - errors += scan_setup_py() - sys.exit(1 if errors else 0) - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - setup_command()