combinatory-synthesizer 0.0.1.dev2__py3-none-any.whl

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.
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.4
2
+ Name: combinatory-synthesizer
3
+ Version: 0.0.1.dev2
4
+ Summary: Type based synthesis framework using inhabitation in FCLP
5
+ Project-URL: Documentation, https://github.com/Jekannadar/cosy#readme
6
+ Project-URL: Issues, https://github.com/Jekannadar/cosy/issues
7
+ Project-URL: Source, https://github.com/Jekannadar/cosy
8
+ Author-email: Constantin Chaumet <constantin.chaumet@tu-dortmund.de>, Andrej Dudenhefner <andrej.dudenhefner@cs.tu-dortmund.de>, Felix Laarmann <felix.laarmann@tu-dortmund.de>, Christoph Stahl <christoph.stahl@tu-dortmund.de>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: Implementation :: CPython
17
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+
21
+ # CoSy
22
+
23
+ <div align="center">
24
+
25
+ <img src="https://raw.githubusercontent.com/tudo-seal/cosy/main/docs/assets/images/logo.svg" alt="CoSy logo" width="400" role="img">
26
+
27
+ | | |
28
+ |----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
29
+ | Package | [![PyPI - Version](https://img.shields.io/pypi/v/combinatory-synthesizer.svg?logo=pypi&label=&labelColor=grey&logoColor=gold&style=flat-square)](https://pypi.org/project/combinatory-synthesizer) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/combinatory-synthesizer.svg?logo=python&label=&labelColor=grey&logoColor=gold&style=flat-square)](https://pypi.org/project/combinatory-synthesizer) |
30
+ | License | [![License](https://img.shields.io/github/license/tudo-seal/cosy?color=9E2165&logo=apache&label=&labelColor=grey&style=flat-square)](https://opensource.org/licenses/Apache-2.0) |
31
+ | Package | [![CI - Test](https://img.shields.io/github/actions/workflow/status/tudo-seal/cosy/checks.yml?label=checks&style=flat-square)](https://github.com/tudo-seal/cosy/actions/workflows/checks.yml) [![CD - Release CoSy](https://img.shields.io/github/actions/workflow/status/tudo-seal/cosy/release.yml?label=release&style=flat-square)](https://github.com/tudo-seal/cosy/actions/workflows/release.yml) |
32
+ | Docs | [![Docs - Release](https://img.shields.io/github/actions/workflow/status/tudo-seal/cosy/check-docs.yml?label=checks&style=flat-square)](https://github.com/tudo-seal/cosy/actions/workflows/check-docs.yml) [![Docs - Checks](https://img.shields.io/github/actions/workflow/status/tudo-seal/cosy/deploy-docs.yml?label=deploy&style=flat-square)](https://github.com/tudo-seal/cosy/actions/workflows/deploy-docs.yml) |
33
+ | Coverage | [![codecov](https://img.shields.io/codecov/c/github/tudo-seal/cosy?token=40E83ABJV4&logo=codecov&label=&labelColor=grey&style=flat-square)](https://codecov.io/github/tudo-seal/cosy) |
34
+ | Traits | [![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg?style=flat-square)](https://hatch.pypa.io/latest/) [![Checked with mypy](https://img.shields.io/badge/endpoint?url=https://raw.githubusercontent.com/tudo-seal/cosy/main/docs/assets/badges/mypy.json&style=flat-square)](http://mypy-lang.org/) [![Checked with Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&color=4051b5&style=flat-square)](https://github.com/astral-sh/ruff) |
35
+
36
+ </div>
37
+
38
+ -----
39
+ `CoSy` enables synthesis of arbitrary artifacts from individual modular components.
40
+ It efficiently handles specification and constraints of these modular components,
41
+ describing how they connect and which performance criteria need to be satisfied.
42
+
43
+ ## APIs
44
+
45
+ `CoSy` can be used in two different ways.
46
+
47
+ - Using the `Synthesizer`. This enables using all features but is more complicated to use.
48
+ - Using the `Maestro`. This enables using less features, but is easy to use.
49
+
50
+ The `Synthesizer` is the recommended way for "power-users" to interact with `CoSy`.
51
+ Publications that primarily focus on type-theoretic aspects usually use it.
52
+
53
+ The `Maesto` is the cute creature playing with building blocks (modular components) on the logo.
54
+ This gifted architect is incredible at connecting these to satisfy any `target` a user may `query` for.
55
+ The `Maestro` API is intended to be easy to use, but the trade-off is lower flexibility.
56
+
57
+ For most technological applications of combinatory synthesis to other fields, e.g. synthesizing physical structures,
58
+ the `Maestro` is sufficient.
59
+
60
+ ## Examples
61
+
62
+ Examples currently all employ the `Maestro`.
63
+
64
+ - For a simple example for a theoretically minded computer scientist, see: [Fibonacci](https://tudo-seal.github.io/cosy/quick-start/)
65
+ - For a simple example for a practically minded engineer, see: [Robot Arm (WIP)](#)
66
+
67
+
68
+ ## Installation
69
+ Installation is as simple as running:
70
+
71
+ ```console
72
+ pip install combinatory-synthesizer
73
+ ```
74
+
75
+ `CoSy` itself has no dependencies at all, so it will play nice with any pre-existing projects.
76
+
77
+ ## Documentation
78
+ This README is intentionally left brief.
79
+ Please head over to the [documentation](https://tudo-seal.github.io/cosy/) to [get started](https://tudo-seal.github.io/cosy/quick-start/).
80
+
81
+ ## License
82
+
83
+ `CoSy` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
84
+
@@ -0,0 +1,16 @@
1
+ cosy/__init__.py,sha256=vDpogu7bCDt8NDZM_cSBKE-JvnjgL2qNbE8frUHW8Ng,448
2
+ cosy/_version.py,sha256=mVM0dlw1T7CyYPpDQHzojbWz-x3KuRltUFa7e_Km9-o,717
3
+ cosy/combinatorics.py,sha256=v72Lxvv-hd8LsR52aJc1jU-1ztXlTrgz5qNzRhF72hw,3374
4
+ cosy/inspector.py,sha256=rhN0KnRmwKuzU_8Q5w7sKsOWIyx0FWPoG6JruLdbpjI,6341
5
+ cosy/maestro.py,sha256=EtN47Iurxf3uGB7PqDrqv-trHiszyoMoYYcXeoesxHY,3010
6
+ cosy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ cosy/solution_space.py,sha256=9j4Rb7dgCMRHyAI7iWrG_1bh0YD7AJ3COByCoVt9ovE,15595
8
+ cosy/specification_builder.py,sha256=CusmeHWlpFjSzLjhoQ52_OJZSM5sqciZuI0RB7P1NmA,6181
9
+ cosy/subtypes.py,sha256=Oy40YM8plHz3bkaBoz3333f20q698puPem8_FBSP6jQ,7336
10
+ cosy/synthesizer.py,sha256=SJWm_f1xj21DejUS6hfaDmyDAB328e6RGQY6v9U5dLc,16659
11
+ cosy/tree.py,sha256=iN-GiWBlQgrkO19RFcCEghXGPnzRiYEF7Mc86MCVcE4,5538
12
+ cosy/types.py,sha256=tQv2ZJy8dv0Mb60CzwxYhXaIStDkyVGvYVjdwtUZ4w8,8402
13
+ combinatory_synthesizer-0.0.1.dev2.dist-info/METADATA,sha256=MX6pJagcaTLhucsGpw4jzvc-F9mXCIVSFm9r3pLe478,7303
14
+ combinatory_synthesizer-0.0.1.dev2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
15
+ combinatory_synthesizer-0.0.1.dev2.dist-info/licenses/LICENSE.txt,sha256=B05uMshqTA74s-0ltyHKI6yoPfJ3zYgQbvcXfDVGFf8,10280
16
+ combinatory_synthesizer-0.0.1.dev2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
cosy/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ __all__ = [
2
+ "Arrow",
3
+ "Constructor",
4
+ "Maestro",
5
+ "Intersection",
6
+ "Literal",
7
+ "Omega",
8
+ "SpecificationBuilder",
9
+ "Subtypes",
10
+ "Synthesizer",
11
+ "Type",
12
+ "Var",
13
+ ]
14
+
15
+ from cosy.maestro import Maestro
16
+ from cosy.specification_builder import SpecificationBuilder
17
+ from cosy.subtypes import Subtypes
18
+ from cosy.synthesizer import Synthesizer
19
+ from cosy.types import Arrow, Constructor, Intersection, Literal, Omega, Type, Var
cosy/_version.py ADDED
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.0.1.dev2'
32
+ __version_tuple__ = version_tuple = (0, 0, 1, 'dev2')
33
+
34
+ __commit_id__ = commit_id = None
cosy/combinatorics.py ADDED
@@ -0,0 +1,89 @@
1
+ from collections import deque
2
+ from collections.abc import Callable, Iterable, Sequence
3
+ from typing import TypeVar
4
+
5
+ S = TypeVar("S") # Type of Sets
6
+ E = TypeVar("E") # Type of Elements
7
+
8
+
9
+ def partition(predicate: Callable[[E], bool], elements: Iterable[E]) -> tuple[deque[E], deque[E]]:
10
+ """Partition elements of an Iterable according to a predicate. Narrowing types.
11
+
12
+ Returns: (elements not satisfying predicate, elements satisfying predicate)."""
13
+
14
+ partitioning: tuple[deque[E], deque[E]] = (deque[E](), deque[E]())
15
+ for element in elements:
16
+ if predicate(element):
17
+ partitioning[1].append(element)
18
+ else:
19
+ partitioning[0].append(element)
20
+ return partitioning
21
+
22
+
23
+ def maximal_elements(elements: Iterable[E], compare: Callable[[E, E], bool]) -> Sequence[E]:
24
+ """Enumerate maximal elements with respect to compare.
25
+
26
+ `compare(e1, e2) == True` iff `e1` smaller or equal to `e2`.
27
+ """
28
+ candidates: deque[E] = deque(elements)
29
+ if len(candidates) <= 1:
30
+ return candidates
31
+ new_candidates: deque[E] = deque()
32
+ result: deque[E] = deque()
33
+ while candidates:
34
+ e1 = candidates.pop()
35
+ while candidates:
36
+ e2 = candidates.pop()
37
+ if compare(e2, e1):
38
+ continue # e2 is redundant
39
+ if compare(e1, e2):
40
+ e1 = e2 # e1 is redundant
41
+ candidates.extendleft(new_candidates)
42
+ new_candidates.clear()
43
+ else:
44
+ new_candidates.appendleft(e2)
45
+ candidates, new_candidates = new_candidates, candidates
46
+ result.appendleft(e1)
47
+ return result
48
+
49
+
50
+ def minimal_covers(sets: Sequence[S], to_cover: Iterable[E], contains: Callable[[S, E], bool]) -> list[list[S]]:
51
+ """List minimal covers of elements in to_cover using given sets.
52
+
53
+ Properties of each `cover: list[S]`
54
+ - for every `e: E` in `to_cover` there is at least one `s: S` in `cover` such that
55
+ `contains(s, e) == True`
56
+ - no `s: S` can be removed from `cover`
57
+ """
58
+ # sets necessarily included in any cover
59
+ necessary_sets: set[int] = set()
60
+ # for each element e: sets containing e
61
+ relevant_sets: deque[set[int]] = deque()
62
+
63
+ for e in to_cover:
64
+ covering_sets = {j for j in range(len(sets)) if contains(sets[j], e)}
65
+ if len(covering_sets) == 0: # at least one element cannot be covered
66
+ return []
67
+ if len(covering_sets) == 1: # exactly one set is relevant
68
+ necessary_sets.add(covering_sets.pop())
69
+ else: # more than one set is relevant
70
+ relevant_sets.append(covering_sets)
71
+
72
+ # collect minimal covers (there is no smaller or equivalent cover)
73
+ covers: deque[set[int]] = deque()
74
+ covers.appendleft(necessary_sets)
75
+ for r in relevant_sets:
76
+ partitioning = partition(r.isdisjoint, covers)
77
+ covers = partitioning[0].copy()
78
+ for c1 in partitioning[1]:
79
+ js: set[int] = r.copy()
80
+ for c2 in partitioning[0]:
81
+ missing = c2.difference(c1)
82
+ if len(missing) == 1:
83
+ # c2 is a subset of c1 + {one missing element}
84
+ js.discard(missing.pop())
85
+ for j in js:
86
+ new_c = c1.copy()
87
+ new_c.add(j)
88
+ covers.append(new_c)
89
+ return [[sets[j] for j in c] for c in covers]
cosy/inspector.py ADDED
@@ -0,0 +1,152 @@
1
+ """Auxiliary functions for inspecting the specification.
2
+ The method `inspect` analyses the given component specifications, parameter space, and taxonomy,
3
+ and provides info, warnings, and reports errors if any.
4
+ """
5
+
6
+ import logging
7
+ from collections import deque
8
+ from collections.abc import Hashable, Mapping
9
+ from itertools import chain
10
+ from typing import TypeVar
11
+
12
+ from cosy.synthesizer import Specification, Taxonomy
13
+ from cosy.types import (
14
+ Abstraction,
15
+ Arrow,
16
+ Constructor,
17
+ Group,
18
+ Implication,
19
+ Intersection,
20
+ LiteralParameter,
21
+ TermParameter,
22
+ Type,
23
+ )
24
+
25
+ # type of components
26
+ C = TypeVar("C", bound=Hashable)
27
+
28
+
29
+ class Inspector:
30
+ """Inspector class for analyzing component specifications, parameter space, and taxonomy."""
31
+
32
+ _logger: logging.Logger
33
+
34
+ def __init__(self, logger=None):
35
+ if logger is None:
36
+ self._logger = logging.getLogger(__name__)
37
+ self._logger.setLevel(logging.DEBUG)
38
+ # handler = logging.StreamHandler()
39
+ # handler.setFormatter(logging.Formatter('%(levelname)s:%(name)s:%(message)s'))
40
+ # self._logger.addHandler(handler)
41
+ else:
42
+ self._logger = logger
43
+
44
+ @staticmethod
45
+ def _constructors(ty: Type) -> set[str]:
46
+ """
47
+ Get the constructors of a type.
48
+ """
49
+ constructors = set()
50
+ stack: deque[Type] = deque([ty])
51
+ while stack:
52
+ match stack.pop():
53
+ case Intersection(l, r):
54
+ stack.extend((l, r))
55
+ case Arrow(src, tgt):
56
+ stack.extend((src, tgt))
57
+ case Constructor(name, arg):
58
+ constructors.add(name)
59
+ stack.append(arg)
60
+
61
+ return constructors
62
+
63
+ def inspect(
64
+ self,
65
+ component_specifications: Mapping[C, Specification],
66
+ taxonomy: Taxonomy | None = None,
67
+ ):
68
+ """
69
+ Inspect the component specifications, parameter space, and taxonomy.
70
+ A `ValueError` is raised if the specifications are not well-formed, which includes:
71
+ - a component has two parameters/arguments with the same name (shadowing)
72
+ - a parameter name is used in the specification of a component but not abstracted via a parameter
73
+ - a group is used in a parameter but not defined in the parameter space
74
+
75
+ An info is logged if:
76
+ - a name is bound to different groups in different components
77
+ - a parameter is abstracted but not used in the specification (caveat: constraints cannot be checked)
78
+ - a group is not used in any component
79
+ - a concept is used only in one component
80
+ - a concept in the taxonomy is not used in any component
81
+ """
82
+
83
+ if taxonomy is None:
84
+ taxonomy = {}
85
+
86
+ all_groups: set[tuple[str, Group | Type]] = set()
87
+ all_constructors: list[set[str]] = []
88
+
89
+ for specification in component_specifications.values():
90
+ prefix: list[LiteralParameter | TermParameter] = []
91
+ # mapping from variable names to groups
92
+ groups: dict[str, Group | Type] = {}
93
+ # set of parameter names occurring in bodies
94
+ parameter_names: set[str] = set()
95
+ parameterized_type = specification
96
+ # set of constructors occurring in the specification
97
+ constructors: set[str] = set()
98
+
99
+ while not isinstance(parameterized_type, Type):
100
+ if isinstance(parameterized_type, Abstraction):
101
+ param = parameterized_type.parameter
102
+ if isinstance(param, LiteralParameter | TermParameter):
103
+ prefix.append(param)
104
+ if param.name in groups:
105
+ # check if parameter names are unique
106
+ msg = f"Duplicate name: {param.name}"
107
+ raise ValueError(msg)
108
+ groups[param.name] = param.group
109
+ for n, g in all_groups:
110
+ if n == param.name and g != param.group:
111
+ self._logger.info(
112
+ "%s is used both as %s and %s",
113
+ param.name,
114
+ param.group,
115
+ g,
116
+ )
117
+ all_groups.add((param.name, param.group))
118
+ if isinstance(param, TermParameter):
119
+ parameter_names.update(param.group.free_vars)
120
+ constructors.update(Inspector._constructors(param.group))
121
+ parameterized_type = parameterized_type.body
122
+ elif isinstance(parameterized_type, Implication):
123
+ parameterized_type = parameterized_type.body
124
+
125
+ parameter_names.update(parameterized_type.free_vars)
126
+ constructors.update(Inspector._constructors(parameterized_type))
127
+ all_constructors.append(constructors)
128
+ # check if every variable in the body is abstracted
129
+ for var in parameter_names:
130
+ if var not in groups:
131
+ msg = f"Variable {var} is not abstracted via a parameter"
132
+ raise ValueError(msg)
133
+
134
+ # check if every abstracted variable is used
135
+ for var, group in groups.items():
136
+ if isinstance(group, str) and var not in parameter_names:
137
+ self._logger.info("Variable %s is abstracted via a parameter but not used", var)
138
+
139
+ # check is some constructor is used only in one component
140
+ for constructors in all_constructors:
141
+ for constructor in constructors:
142
+ if sum(1 for cs in all_constructors if constructor in cs) == 1:
143
+ self._logger.info("Concept %s is used in only one component", constructor)
144
+
145
+ # check if every concept in the taxonomy is used
146
+ for name, subtypes in taxonomy.items():
147
+ for c in chain([name], subtypes):
148
+ if c not in set.union(*all_constructors):
149
+ self._logger.info("Concept %s is not used in any component", c)
150
+
151
+ # further ideas:
152
+ # check if each parameter of a non-iterable group without candidate values is in the codomain
cosy/maestro.py ADDED
@@ -0,0 +1,67 @@
1
+ from collections.abc import Callable, Hashable, Iterable, Sequence
2
+ from itertools import groupby
3
+ from typing import Any, Generic, TypeVar
4
+
5
+ from cosy.subtypes import Taxonomy
6
+ from cosy.synthesizer import Specification, Synthesizer
7
+ from cosy.types import Type
8
+
9
+ T = TypeVar("T", bound=Hashable)
10
+
11
+
12
+ class Maestro(Generic[T]):
13
+ named_components_with_specifications: Sequence[tuple[T, Callable, Specification]]
14
+ taxonomy: Taxonomy | None = None
15
+ _synthesizer: Synthesizer
16
+
17
+ def __init__(
18
+ self,
19
+ named_components_with_specifications: Sequence[tuple[T, Callable, Specification]],
20
+ taxonomy: Taxonomy | None = None,
21
+ ) -> None:
22
+ duplicate_component_names = [
23
+ key
24
+ for key, group in groupby(named_components_with_specifications, key=lambda x: x[0])
25
+ if len(list(group)) > 1
26
+ ]
27
+ if len(duplicate_component_names) != 0:
28
+ msg = f"Component's names should be unique, but the following names are duplicated: {duplicate_component_names}"
29
+ raise ValueError(msg)
30
+
31
+ non_callable_interpretations_by_component_name = [
32
+ name for name, interpretation, _ in named_components_with_specifications if not callable(interpretation)
33
+ ]
34
+ if len(non_callable_interpretations_by_component_name) != 0:
35
+ msg = f"Component's interpretations should be callable, but interpretations of components with the following names are not: {non_callable_interpretations_by_component_name}"
36
+ raise ValueError(msg)
37
+
38
+ self.named_components_with_specifications = named_components_with_specifications
39
+ self.taxonomy = taxonomy if taxonomy is not None else {}
40
+
41
+ self.component_specifications = {
42
+ name: specification for name, _, specification in self.named_components_with_specifications
43
+ }
44
+ self.component_interpretations = {
45
+ name: interpretation for name, interpretation, _ in self.named_components_with_specifications
46
+ }
47
+
48
+ self._synthesizer = Synthesizer(self.component_specifications, self.taxonomy)
49
+
50
+ def query(self, target: Type, max_count: int = 100) -> Iterable[Any]:
51
+ """
52
+ Query the Maestro for solutions that fulfill given target; by constructing a solution space and enumerating and interpreting the resulting trees.
53
+
54
+ :param target: The target for which solutions should be queried.
55
+ :param max_count: The maximum number of trees to enumerate.
56
+ :return: An iterable of interpreted trees, the results.
57
+ """
58
+ if not isinstance(target, Type):
59
+ msg = "Target must be of type Type"
60
+ raise TypeError(msg)
61
+ solution_space = self._synthesizer.construct_solution_space(target).prune()
62
+
63
+ trees = solution_space.enumerate_trees(
64
+ target, max_count=max_count, interpretation=self.component_interpretations
65
+ )
66
+ for tree in trees:
67
+ yield tree.interpret(interpretation=self.component_interpretations)
cosy/py.typed ADDED
File without changes