pygacity 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. pygacity-0.4.0/.gitignore +138 -0
  2. pygacity-0.4.0/LICENSE +21 -0
  3. pygacity-0.4.0/PKG-INFO +76 -0
  4. pygacity-0.4.0/README.md +55 -0
  5. pygacity-0.4.0/pyproject.toml +45 -0
  6. pygacity-0.4.0/src/pygacity/__init__.py +0 -0
  7. pygacity-0.4.0/src/pygacity/cli.py +132 -0
  8. pygacity-0.4.0/src/pygacity/generate/__init__.py +0 -0
  9. pygacity-0.4.0/src/pygacity/generate/answerset.py +194 -0
  10. pygacity-0.4.0/src/pygacity/generate/block.py +166 -0
  11. pygacity-0.4.0/src/pygacity/generate/build.py +188 -0
  12. pygacity-0.4.0/src/pygacity/generate/config.py +91 -0
  13. pygacity-0.4.0/src/pygacity/generate/document.py +50 -0
  14. pygacity-0.4.0/src/pygacity/generate/pick.py +81 -0
  15. pygacity-0.4.0/src/pygacity/resources/__init__.py +0 -0
  16. pygacity-0.4.0/src/pygacity/resources/autoprob-package/tex/latex/autoprob.cls +208 -0
  17. pygacity-0.4.0/src/pygacity/resources/corresponding-states-data/enthalpy-departures.csv +242 -0
  18. pygacity-0.4.0/src/pygacity/resources/corresponding-states-data/enthalpy-departures.raw +246 -0
  19. pygacity-0.4.0/src/pygacity/resources/corresponding-states-data/entropy-departures.csv +155 -0
  20. pygacity-0.4.0/src/pygacity/resources/corresponding-states-data/entropy-departures.raw +158 -0
  21. pygacity-0.4.0/src/pygacity/resources/pythontex/chemeq.pycode +6 -0
  22. pygacity-0.4.0/src/pygacity/resources/pythontex/matplotlib.pycode +11 -0
  23. pygacity-0.4.0/src/pygacity/resources/pythontex/sandlerprops.pycode +3 -0
  24. pygacity-0.4.0/src/pygacity/resources/pythontex/sandlersteam.pycode +6 -0
  25. pygacity-0.4.0/src/pygacity/resources/pythontex/setup.pycode +27 -0
  26. pygacity-0.4.0/src/pygacity/resources/pythontex/showsteamtables.pycode +4 -0
  27. pygacity-0.4.0/src/pygacity/resources/pythontex/teardown.pycode +14 -0
  28. pygacity-0.4.0/src/pygacity/resources/templates/blank_template.tex +16 -0
  29. pygacity-0.4.0/src/pygacity/resources/templates/footer.tex +1 -0
  30. pygacity-0.4.0/src/pygacity/resources/templates/header.tex +13 -0
  31. pygacity-0.4.0/src/pygacity/resources/templates/short.tex +99 -0
  32. pygacity-0.4.0/src/pygacity/topics/__init__.py +0 -0
  33. pygacity-0.4.0/src/pygacity/topics/chem/__init__.py +0 -0
  34. pygacity-0.4.0/src/pygacity/topics/chem/chemeqsystem.py +201 -0
  35. pygacity-0.4.0/src/pygacity/topics/chem/compound.py +251 -0
  36. pygacity-0.4.0/src/pygacity/topics/chem/properties.py +43 -0
  37. pygacity-0.4.0/src/pygacity/topics/chem/reaction.py +138 -0
  38. pygacity-0.4.0/src/pygacity/topics/distillation/__init__.py +0 -0
  39. pygacity-0.4.0/src/pygacity/topics/distillation/binaryduties.py +457 -0
  40. pygacity-0.4.0/src/pygacity/topics/distillation/binaryflashdepriester.py +206 -0
  41. pygacity-0.4.0/src/pygacity/topics/distillation/fug.py +71 -0
  42. pygacity-0.4.0/src/pygacity/topics/distillation/mccabethiele.py +443 -0
  43. pygacity-0.4.0/src/pygacity/topics/steam/__init__.py +0 -0
  44. pygacity-0.4.0/src/pygacity/topics/steam/steamtank.py +67 -0
  45. pygacity-0.4.0/src/pygacity/topics/thermo/__init__.py +0 -0
  46. pygacity-0.4.0/src/pygacity/topics/thermo/corrsts.py +32 -0
  47. pygacity-0.4.0/src/pygacity/topics/thermo/prcalcs.py +343 -0
  48. pygacity-0.4.0/src/pygacity/topics/vle/__init__.py +0 -0
  49. pygacity-0.4.0/src/pygacity/topics/vle/txyplot.py +98 -0
  50. pygacity-0.4.0/src/pygacity/topics/vle/vle.py +357 -0
  51. pygacity-0.4.0/src/pygacity/util/__init__.py +0 -0
  52. pygacity-0.4.0/src/pygacity/util/collectors.py +248 -0
  53. pygacity-0.4.0/src/pygacity/util/command.py +19 -0
  54. pygacity-0.4.0/src/pygacity/util/corrsts_wpd2csv.py +37 -0
  55. pygacity-0.4.0/src/pygacity/util/pdfutils.py +24 -0
  56. pygacity-0.4.0/src/pygacity/util/stringthings.py +170 -0
  57. pygacity-0.4.0/src/pygacity/util/texutils.py +211 -0
@@ -0,0 +1,138 @@
1
+ *.bak
2
+ __defunct__/
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+ .idea/
8
+ *tmp*
9
+ */results/
10
+ .vscode/
11
+ # C extensions
12
+ *.so
13
+ *.o
14
+
15
+ # Distribution / packaging
16
+ .Python
17
+ build/
18
+ develop-eggs/
19
+ dist/
20
+ downloads/
21
+ eggs/
22
+ .eggs/
23
+ lib/
24
+ lib64/
25
+ parts/
26
+ sdist/
27
+ var/
28
+ wheels/
29
+ pip-wheel-metadata/
30
+ share/python-wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ *.py,cover
57
+ .hypothesis/
58
+ .pytest_cache/
59
+
60
+ # Translations
61
+ *.mo
62
+ *.pot
63
+
64
+ # Django stuff:
65
+ *.log
66
+ local_settings.py
67
+ db.sqlite3
68
+ db.sqlite3-journal
69
+
70
+ # Flask stuff:
71
+ instance/
72
+ .webassets-cache
73
+
74
+ # Scrapy stuff:
75
+ .scrapy
76
+
77
+ # Sphinx documentation
78
+ docs/_build/
79
+ docs/source/_build
80
+
81
+ # PyBuilder
82
+ target/
83
+
84
+ # Jupyter Notebook
85
+ .ipynb_checkpoints
86
+
87
+ # IPython
88
+ profile_default/
89
+ ipython_config.py
90
+
91
+ # pyenv
92
+ .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
102
+ __pypackages__/
103
+
104
+ # Celery stuff
105
+ celerybeat-schedule
106
+ celerybeat.pid
107
+
108
+ # SageMath parsed files
109
+ *.sage.py
110
+
111
+ # Environments
112
+ .env
113
+ .venv
114
+ env/
115
+ venv/
116
+ ENV/
117
+ env.bak/
118
+ venv.bak/
119
+
120
+ # Spyder project settings
121
+ .spyderproject
122
+ .spyproject
123
+
124
+ # Rope project settings
125
+ .ropeproject
126
+
127
+ # mkdocs documentation
128
+ /site
129
+
130
+ # mypy
131
+ .mypy_cache/
132
+ .dmypy.json
133
+ dmypy.json
134
+
135
+ # Pyre type checker
136
+ .pyre/
137
+ .vscode/settings.json
138
+
pygacity-0.4.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Cameron Abrams
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: pygacity
3
+ Version: 0.4.0
4
+ Summary: A framework for exam and assignment generation using LaTeX and pythontex
5
+ Author-email: Cameron F Abrams <cfa22@drexel.edu>
6
+ License-File: LICENSE
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Requires-Python: >=3.7
10
+ Requires-Dist: iapws
11
+ Requires-Dist: jinja2
12
+ Requires-Dist: numpy
13
+ Requires-Dist: pandas
14
+ Requires-Dist: progressbar
15
+ Requires-Dist: pypdf2
16
+ Requires-Dist: roman
17
+ Requires-Dist: sandlerprops
18
+ Requires-Dist: sandlersteam
19
+ Requires-Dist: scipy
20
+ Description-Content-Type: text/markdown
21
+
22
+ # pygacity
23
+
24
+ > A Python package to enable high-throughput generation of problems suitable for exams and problem sets for thermodynamics courses
25
+
26
+ You may have learned how to use Python to solve thermodynamics problems, like equilibrium compositions for a reacting system, or phase compositions in vapor-liquid equilibrium. `Pygacity` takes this idea and uses Python to generate new problems. The problems are generated in such a way that they can be typeset into PDF's using LaTeX. `Pygacity` relies on the `pythontex` package in LaTeX to allow Python code to run during document compilation and results of those calculations automatically included in the document.
27
+
28
+ ## Installation
29
+
30
+ `Pygacity` is in development. Best to install it that way.
31
+
32
+ ```sh
33
+ git clone git@github.com:cameronabrams/pygacity.git
34
+ cd pygacity
35
+ pip install -e .
36
+ ```
37
+
38
+ `Pygacity` includes the LaTeX class file `autoprob.cls` under `[INSTALL-DIR]/pygacity/resources/autoprob-package/tex/latex/`. All `latex` commands that are managed by `pygacity` append this directory in a ``--include-directory`` argument. If you would like to use `autoprob.cls` outside of `pygacity`, you will need to make your LaTeX installation aware of `autoprob-package` root.
39
+
40
+ ## Release History
41
+
42
+ * 0.4.0
43
+ * examples
44
+ * 0.3.0
45
+ * Added multiple choice, short answer, and fill in the blank question types
46
+ * 0.2.0
47
+ * Package reorg
48
+ * updated config yaml
49
+ * 0.1.4
50
+ * single-shot assignment creation with no serial numbers
51
+ * additional LaTeX header commands available via config
52
+ * upgraded ycleptic dependencies to 2.0.3
53
+ * 0.1.3
54
+ * `combine` subcommand
55
+ * `build` subcommand
56
+ * renamed to `pygacity`
57
+ * 0.1.1
58
+ * reorganized package
59
+ * 0.0.1
60
+ * Initial version
61
+
62
+ ## Meta
63
+
64
+ Cameron F. Abrams – cfa22@drexel.edu
65
+
66
+ Distributed under the MIT license. See ``LICENSE`` for more information.
67
+
68
+ [https://github.com/cameronabrams](https://github.com/cameronabrams/)
69
+
70
+ ## Contributing
71
+
72
+ 1. Fork it (<https://github.com/cameronabrams/pygacity/fork>)
73
+ 2. Create your feature branch (`git checkout -b feature/fooBar`)
74
+ 3. Commit your changes (`git commit -am 'Add some fooBar'`)
75
+ 4. Push to the branch (`git push origin feature/fooBar`)
76
+ 5. Create a new Pull Request
@@ -0,0 +1,55 @@
1
+ # pygacity
2
+
3
+ > A Python package to enable high-throughput generation of problems suitable for exams and problem sets for thermodynamics courses
4
+
5
+ You may have learned how to use Python to solve thermodynamics problems, like equilibrium compositions for a reacting system, or phase compositions in vapor-liquid equilibrium. `Pygacity` takes this idea and uses Python to generate new problems. The problems are generated in such a way that they can be typeset into PDF's using LaTeX. `Pygacity` relies on the `pythontex` package in LaTeX to allow Python code to run during document compilation and results of those calculations automatically included in the document.
6
+
7
+ ## Installation
8
+
9
+ `Pygacity` is in development. Best to install it that way.
10
+
11
+ ```sh
12
+ git clone git@github.com:cameronabrams/pygacity.git
13
+ cd pygacity
14
+ pip install -e .
15
+ ```
16
+
17
+ `Pygacity` includes the LaTeX class file `autoprob.cls` under `[INSTALL-DIR]/pygacity/resources/autoprob-package/tex/latex/`. All `latex` commands that are managed by `pygacity` append this directory in a ``--include-directory`` argument. If you would like to use `autoprob.cls` outside of `pygacity`, you will need to make your LaTeX installation aware of `autoprob-package` root.
18
+
19
+ ## Release History
20
+
21
+ * 0.4.0
22
+ * examples
23
+ * 0.3.0
24
+ * Added multiple choice, short answer, and fill in the blank question types
25
+ * 0.2.0
26
+ * Package reorg
27
+ * updated config yaml
28
+ * 0.1.4
29
+ * single-shot assignment creation with no serial numbers
30
+ * additional LaTeX header commands available via config
31
+ * upgraded ycleptic dependencies to 2.0.3
32
+ * 0.1.3
33
+ * `combine` subcommand
34
+ * `build` subcommand
35
+ * renamed to `pygacity`
36
+ * 0.1.1
37
+ * reorganized package
38
+ * 0.0.1
39
+ * Initial version
40
+
41
+ ## Meta
42
+
43
+ Cameron F. Abrams – cfa22@drexel.edu
44
+
45
+ Distributed under the MIT license. See ``LICENSE`` for more information.
46
+
47
+ [https://github.com/cameronabrams](https://github.com/cameronabrams/)
48
+
49
+ ## Contributing
50
+
51
+ 1. Fork it (<https://github.com/cameronabrams/pygacity/fork>)
52
+ 2. Create your feature branch (`git checkout -b feature/fooBar`)
53
+ 3. Commit your changes (`git commit -am 'Add some fooBar'`)
54
+ 4. Push to the branch (`git push origin feature/fooBar`)
55
+ 5. Create a new Pull Request
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+ [project]
5
+ name = "pygacity"
6
+ version = "0.4.0"
7
+ authors = [
8
+ { name="Cameron F Abrams", email="cfa22@drexel.edu" },
9
+ ]
10
+ description = "A framework for exam and assignment generation using LaTeX and pythontex"
11
+ readme = "README.md"
12
+ requires-python = ">=3.7"
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ ]
17
+ dependencies = [
18
+ "numpy",
19
+ "pandas",
20
+ "scipy",
21
+ "iapws",
22
+ "sandlersteam",
23
+ "sandlerprops",
24
+ "roman",
25
+ "progressbar",
26
+ "pypdf2",
27
+ "jinja2",
28
+ ]
29
+ [tool.pytest.ini_options]
30
+ log_cli = true
31
+ [project.scripts]
32
+ pygacity="pygacity.cli:cli"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/pygacity"]
36
+
37
+ [tool.hatch.build]
38
+ include = [
39
+ "src/pygacity/resources/**",
40
+ ]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ include = [
44
+ "src/pygacity/**",
45
+ ]
File without changes
@@ -0,0 +1,132 @@
1
+ # Author: Cameron F. Abrams, <cfa22@drexel.edu>
2
+
3
+
4
+ import logging
5
+ import os
6
+ import shutil
7
+
8
+ import argparse as ap
9
+
10
+ from .generate.build import build, answerset_subcommand
11
+ from .util.pdfutils import combine_pdfs
12
+ from .util.stringthings import oxford, banner
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ def setup_logging(args):
17
+ loglevel_numeric = getattr(logging, args.logging_level.upper())
18
+ if args.log:
19
+ if os.path.exists(args.log):
20
+ shutil.copyfile(args.log, args.log+'.bak')
21
+ logging.basicConfig(filename=args.log,
22
+ filemode='w',
23
+ format='%(asctime)s %(name)s %(message)s',
24
+ level=loglevel_numeric
25
+ )
26
+ console = logging.StreamHandler()
27
+ console.setLevel(logging.INFO)
28
+ formatter = logging.Formatter('%(levelname)s> %(message)s')
29
+ console.setFormatter(formatter)
30
+ logging.getLogger('').addHandler(console)
31
+
32
+ def cli():
33
+ subcommands = {
34
+ 'build': dict(
35
+ func = build,
36
+ help = 'build document',
37
+ ),
38
+ 'answerset' : dict(
39
+ func = answerset_subcommand,
40
+ help = 'remake answer set document from a previous build',
41
+ ),
42
+ 'combine': dict(
43
+ func = combine_pdfs,
44
+ help = 'combine PDFs',
45
+ )
46
+ }
47
+ parser = ap.ArgumentParser(
48
+ prog='pygacity',
49
+ )
50
+ parser.add_argument(
51
+ '-b',
52
+ '--banner',
53
+ default=True,
54
+ action=ap.BooleanOptionalAction,
55
+ help='toggle banner message'
56
+ )
57
+ parser.add_argument(
58
+ '--logging-level',
59
+ type=str,
60
+ default='debug',
61
+ choices=[None, 'info', 'debug', 'warning'],
62
+ help='Logging level for messages written to diagnostic log'
63
+ )
64
+ parser.add_argument(
65
+ '-l',
66
+ '--log',
67
+ type=str,
68
+ default='pygacity-diagnostics.log',
69
+ help='File to which diagnostic log messages are written'
70
+ )
71
+ subparsers = parser.add_subparsers(
72
+ title="subcommands",
73
+ dest="command",
74
+ metavar="<command>",
75
+ required=True,
76
+ )
77
+ command_parsers={}
78
+ for k, specs in subcommands.items():
79
+ command_parsers[k] = subparsers.add_parser(
80
+ k,
81
+ help=specs['help'],
82
+ formatter_class=ap.RawDescriptionHelpFormatter
83
+ )
84
+ command_parsers[k].set_defaults(func=specs['func'])
85
+
86
+ command_parsers['build'].add_argument(
87
+ '-o',
88
+ '--overwrite',
89
+ type=bool,
90
+ default=False,
91
+ action=ap.BooleanOptionalAction,
92
+ help='completely remove old save dir and build new exams')
93
+ command_parsers['build'].add_argument(
94
+ '-s',
95
+ '--solutions',
96
+ type=bool,
97
+ default=True,
98
+ action=ap.BooleanOptionalAction,
99
+ help='build solutions document(s)')
100
+ command_parsers['build'].add_argument(
101
+ 'f',
102
+ help='mandatory YAML input file')
103
+ command_parsers['answerset'].add_argument(
104
+ 'f',
105
+ help='mandatory YAML input file used in a previous build to generate the answer set')
106
+ command_parsers['combine'].add_argument(
107
+ '-i',
108
+ '--input-pdfs',
109
+ type=str,
110
+ default=[],
111
+ nargs='+',
112
+ help='space-separated list of PDF file names to combine'
113
+ )
114
+ command_parsers['combine'].add_argument(
115
+ '-o',
116
+ '--pdf-out',
117
+ type=str,
118
+ default='out.pdf',
119
+ help='name of new output PDF to be created')
120
+
121
+ args = parser.parse_args()
122
+
123
+ setup_logging(args)
124
+
125
+ if args.banner:
126
+ banner(print)
127
+ if hasattr(args, 'func'):
128
+ args.func(args)
129
+ else:
130
+ my_list = oxford(list(subcommands.keys()))
131
+ print(f'No subcommand found. Expected one of {my_list}')
132
+ logger.info('Thanks for using pygacity!')
File without changes
@@ -0,0 +1,194 @@
1
+ # Author: Cameron F. Abrams, <cfa22@drexel.edu>
2
+ import yaml
3
+ import os
4
+ from collections import UserList
5
+ import pandas as pd
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ class AnswerSet:
11
+ _keys = ['label', 'value', 'units', 'formatter']
12
+ def __init__(self, serial: int = 0):
13
+ self.serial = serial
14
+ self.dumpname = f'answers-{serial:08d}.yaml'
15
+ self.D = {}
16
+ self.first_index = None
17
+
18
+ @classmethod
19
+ def from_yaml(cls, filename, delete=False):
20
+ """
21
+ Create an AnswerSet instance by loading from a YAML file of the same format as that
22
+ generated by the to_yaml() method.
23
+ """
24
+ root, ext = os.path.splitext(filename)
25
+ assert ext in ['.yaml', '.yml'], f'{filename} does not end in .yaml or .yml'
26
+ tokens = root.split('-')
27
+ assert len(tokens) == 2, f'{filename} should be of the format "answers-<serial#>.yaml"'
28
+ serial = int(tokens[1])
29
+ R = cls(serial)
30
+ with open(filename, 'r') as f:
31
+ R.D = yaml.safe_load(f)
32
+ if delete:
33
+ os.remove(filename)
34
+ return R
35
+
36
+ def register(self, index, label=None, value=None, units=None, formatter=None, group=None):
37
+ """
38
+ Register an answer entry for a particular question index.
39
+ """
40
+ if not self.first_index:
41
+ self.first_index = index
42
+ if not index in self.D:
43
+ self.D[index] = []
44
+ # if value is a numpy data type, convert to native python type
45
+ if hasattr(value, 'item'):
46
+ value = value.item()
47
+ self.D[index].append(dict( label=label,
48
+ value=value,
49
+ units=units,
50
+ formatter=formatter,
51
+ group=group))
52
+ logger.debug(f'AnswerSet.register index={index} label={label} value={value} units={units} formatter={formatter} group={group}')
53
+
54
+ def display(self, index, element=0):
55
+ D = None
56
+ if element < len(self.D[index]):
57
+ D = self.D[index][element]
58
+ if D:
59
+ fmt = D.get('formatter',None)
60
+ val = D.get('value',None)
61
+ label = D.get('label',None)
62
+ units = D.get('units',None)
63
+ vstr = ''
64
+ if val:
65
+ if fmt:
66
+ vstr = fmt.format(val)
67
+ else:
68
+ vstr = str(val)
69
+ if units:
70
+ vstr += f' {units}'
71
+ if label:
72
+ if vstr:
73
+ return f'{label} = {vstr}'
74
+ else:
75
+ return label
76
+ return ''
77
+
78
+ # def to_yaml(self):
79
+ # # check all indices for common bytes at the start, and remove them
80
+ # raw_indices = list(self.D.keys())
81
+ # common_prefix = os.path.commonprefix([str(x) for x in raw_indices])
82
+ # logger.debug(f'AnswerSet.to_yaml common prefix: "{common_prefix}"')
83
+ # if common_prefix:
84
+ # new_D = {}
85
+ # for index, AL in self.D.items():
86
+ # new_index = str(index)[len(common_prefix):]
87
+ # new_D[new_index] = AL
88
+ # self.D = new_D
89
+ # with open(self.dumpname, 'w') as f:
90
+ # yaml.safe_dump(self.D, f)
91
+
92
+ class AnswerSuperSet(UserList):
93
+
94
+ def __init__(self, initial: list[AnswerSet] = None):
95
+ self.data: list[AnswerSet] = initial if initial is not None else []
96
+ super().__init__(self.data)
97
+ if not self._check_congruency():
98
+ print(f'Error: There is a lack of congruency among answer sets')
99
+ self._make_dfs()
100
+
101
+ @classmethod
102
+ def from_dumpfiles(cls, files=[], delete=False):
103
+ data=[]
104
+ for f in files:
105
+ data.append(AnswerSet.from_yaml(f, delete=delete))
106
+ return cls(initial=data)
107
+
108
+ def to_latex(self):
109
+ result = ''
110
+ for group_name, group_data in self.groups.items():
111
+ df = group_data['df']
112
+ formatters = group_data.get('formatters', None)
113
+ logger.debug(f'AnswerSuperSet.to_latex group "{group_name}" with formatters: {formatters}')
114
+ result += df.to_latex(formatters=formatters, index=False, longtable=True)#,header=self.headings)
115
+ return result
116
+
117
+ def _check_congruency(self):
118
+ if len(self)>0:
119
+ indices=list(self.data[0].D.keys())
120
+ for l in self.data[1:]:
121
+ test_indices=list(l.D.keys())
122
+ check=all([x==y for x,y in zip(indices,test_indices)])
123
+ if not check:
124
+ return False
125
+ for i in indices:
126
+ ilen=len(self.data[0].D[i])
127
+ for l in self.data[1:]:
128
+ test_ilen=len(l.D[i])
129
+ check=ilen==test_ilen
130
+ if not check:
131
+ return False
132
+ return True
133
+
134
+ def _make_dfs(self):
135
+ # to do: groupify
136
+ serials = [x.serial for x in self.data]
137
+ # logger.debug(serials)
138
+ # self.headings = ['serials']
139
+ # keys = ['serials']
140
+ values = {'serials': serials}
141
+ pattern = self.data[0] # keys in first AnswerSet form the pattern all sets follow
142
+ self.formatters = {}
143
+ self.groups = {}
144
+ # keys in D may be prepended with a common prefix; remove it
145
+ common_prefix = os.path.commonprefix([str(x) for x in pattern.D.keys()])
146
+ logger.debug(f'Overall common prefix: "{common_prefix}"')
147
+ for dataset in self.data:
148
+ new_dataset_D = {}
149
+ for index in dataset.D.keys():
150
+ new_index = str(index)[len(common_prefix):]
151
+ new_dataset_D[new_index] = dataset.D[index]
152
+ dataset.D = new_dataset_D
153
+ for index, AL in pattern.D.items():
154
+ for a in AL:
155
+ key = f'{index}-{a["label"]}'
156
+ if 'units' in a and a['units']:
157
+ key += f' ({a["units"]})'
158
+ group = a.get('group', None)
159
+ if group:
160
+ if group not in self.groups:
161
+ self.groups[group] = dict(formatters={}, df=None, values={'serials': serials})
162
+ self.groups[group]['values'][key] = []
163
+ if 'formatter' in a:
164
+ self.groups[group]['formatters'][key] = a['formatter']
165
+ else:
166
+ values[key] = []
167
+ if 'formatter' in a:
168
+ self.formatters[key] = a['formatter']
169
+ # logger.debug(values)
170
+ for inst in self.data:
171
+ for index, AL in inst.D.items():
172
+ for a in AL:
173
+ key = f'{index}-{a["label"]}'
174
+ if 'units' in a and a['units']:
175
+ key += f' ({a["units"]})'
176
+ group = a.get('group', None)
177
+ if group:
178
+ self.groups[group]['values'][key].append(a['value'])
179
+ else:
180
+ values[key].append(a['value'])
181
+ # logger.debug(values)
182
+ if not self.groups:
183
+ DF = pd.DataFrame(values)
184
+ DF.sort_values(by='serials', inplace=True)
185
+ self.groups['base'] = dict(formatters=self.formatters, df=DF)
186
+ else:
187
+ for gname, gdata in self.groups.items():
188
+ logger.debug(f'Building DataFrame for group {gname} with values: {gdata["values"]}')
189
+ DF = pd.DataFrame(gdata['values'])
190
+ DF.sort_values(by='serials', inplace=True)
191
+ self.groups[gname]['df'] = DF
192
+ # print(self.DF)
193
+
194
+