instance_id
stringlengths 12
53
| patch
stringlengths 278
33.9k
| repo
stringlengths 7
48
| base_commit
stringlengths 40
40
| hints_text
stringclasses 189
values | test_patch
stringlengths 212
264k
| problem_statement
stringlengths 23
37.7k
| version
stringclasses 1
value | FAIL_TO_PASS
sequencelengths 1
902
| PASS_TO_PASS
sequencelengths 0
7.6k
| created_at
stringlengths 25
25
| __index_level_0__
int64 1.89k
4.13k
|
---|---|---|---|---|---|---|---|---|---|---|---|
devopshq__artifactory-cleanup-100 | diff --git a/README.md b/README.md
index c0a63ec..ee5afde 100644
--- a/README.md
+++ b/README.md
@@ -135,6 +135,12 @@ artifactory-cleanup --days-in-future=10
# Not satisfied with built-in rules? Write your own rules in python and connect them!
artifactory-cleanup --load-rules=myrule.py
docker run -v "$(pwd)":/app devopshq/artifactory-cleanup artifactory-cleanup --load-rules=myrule.py
+
+# Save the table summary in a file
+artifactory-cleanup --output=myfile.txt
+
+# Save the summary in a Json file
+artifactory-cleanup --output=myfile.txt --output-format=json
```
# Rules
diff --git a/artifactory_cleanup/cli.py b/artifactory_cleanup/cli.py
index 312c999..b168ecf 100644
--- a/artifactory_cleanup/cli.py
+++ b/artifactory_cleanup/cli.py
@@ -1,3 +1,4 @@
+import json
import logging
import sys
from datetime import timedelta, date
@@ -5,6 +6,7 @@ from datetime import timedelta, date
import requests
from hurry.filesize import size
from plumbum import cli
+from plumbum.cli.switches import Set
from prettytable import PrettyTable
from requests.auth import HTTPBasicAuth
@@ -62,6 +64,19 @@ class ArtifactoryCleanupCLI(cli.Application):
mandatory=False,
)
+ _output_file = cli.SwitchAttr(
+ "--output", help="Choose the output file", mandatory=False
+ )
+
+ _output_format = cli.SwitchAttr(
+ "--output-format",
+ Set("table", "json", case_sensitive=False),
+ help="Choose the output format",
+ default="table",
+ requires=["--output"],
+ mandatory=False,
+ )
+
@property
def VERSION(self):
# To prevent circular imports
@@ -83,6 +98,36 @@ class ArtifactoryCleanupCLI(cli.Application):
print(f"Simulating cleanup actions that will occur on {today}")
return today
+ def _format_table(self, result) -> PrettyTable:
+ table = PrettyTable()
+ table.field_names = ["Cleanup Policy", "Files count", "Size"]
+ table.align["Cleanup Policy"] = "l"
+
+ for policy_result in result["policies"]:
+ row = [
+ policy_result["name"],
+ policy_result["file_count"],
+ size(policy_result["size"]),
+ ]
+ table.add_row(row)
+
+ table.add_row(["", "", ""])
+ table.add_row(["Total size: {}".format(size(result["total_size"])), "", ""])
+ return table
+
+ def _print_table(self, result: dict):
+ print(self._format_table(result))
+
+ def _create_output_file(self, result, filename, format):
+ text = None
+ if format == "table":
+ text = self._format_table(result).get_string()
+ else:
+ text = json.dumps(result)
+
+ with open(filename, "w") as file:
+ file.write(text)
+
def main(self):
today = self._get_today()
if self._load_rules:
@@ -112,9 +157,7 @@ class ArtifactoryCleanupCLI(cli.Application):
if self._policy:
cleanup.only(self._policy)
- table = PrettyTable()
- table.field_names = ["Cleanup Policy", "Files count", "Size"]
- table.align["Cleanup Policy"] = "l"
+ result = {"policies": [], "total_size": 0}
total_size = 0
block_ctx_mgr, test_ctx_mgr = get_context_managers()
@@ -124,16 +167,21 @@ class ArtifactoryCleanupCLI(cli.Application):
if summary is None:
continue
total_size += summary.artifacts_size
- row = [
- summary.policy_name,
- summary.artifacts_removed,
- size(summary.artifacts_size),
- ]
- table.add_row(row)
- table.add_row(["", "", ""])
- table.add_row(["Total size: {}".format(size(total_size)), "", ""])
- print(table)
+ result["policies"].append(
+ {
+ "name": summary.policy_name,
+ "file_count": summary.artifacts_removed,
+ "size": summary.artifacts_size,
+ }
+ )
+
+ result["total_size"] = total_size
+
+ self._print_table(result)
+
+ if self._output_file:
+ self._create_output_file(result, self._output_file, self._output_format)
if __name__ == "__main__":
| devopshq/artifactory-cleanup | c523f319dc7835c5b3bd583f5ba187184df24dbc | diff --git a/tests/data/expected_output.txt b/tests/data/expected_output.txt
new file mode 100644
index 0000000..2471489
--- /dev/null
+++ b/tests/data/expected_output.txt
@@ -0,0 +1,8 @@
++--------------------------------------------------------+-------------+------+
+| Cleanup Policy | Files count | Size |
++--------------------------------------------------------+-------------+------+
+| Remove all files from repo-name-here older then 7 days | 1 | 528B |
+| Use your own rules! | 1 | 528B |
+| | | |
+| Total size: 1K | | |
++--------------------------------------------------------+-------------+------+
\ No newline at end of file
diff --git a/tests/test_cli.py b/tests/test_cli.py
index f5c5afe..2869e23 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1,4 +1,6 @@
+import json
import pytest
+from filecmp import cmp
from artifactory_cleanup import ArtifactoryCleanupCLI
@@ -69,3 +71,101 @@ def test_destroy(capsys, shared_datadir, requests_mock):
last_request.url
== "https://repo.example.com/artifactory/repo-name-here/path/to/file/filename1.json"
)
+
+
+@pytest.mark.usefixtures("requests_repo_name_here")
+def test_output_table(capsys, shared_datadir, requests_mock):
+ _, code = ArtifactoryCleanupCLI.run(
+ [
+ "ArtifactoryCleanupCLI",
+ "--config",
+ str(shared_datadir / "cleanup.yaml"),
+ "--load-rules",
+ str(shared_datadir / "myrule.py"),
+ ],
+ exit=False,
+ )
+ stdout, stderr = capsys.readouterr()
+ print(stdout)
+ assert code == 0, stdout
+ assert (
+ "| Cleanup Policy | Files count | Size |"
+ in stdout
+ )
+
+
+@pytest.mark.usefixtures("requests_repo_name_here")
+def test_output_table(capsys, shared_datadir, requests_mock, tmp_path):
+ output_file = tmp_path / "output.txt"
+ _, code = ArtifactoryCleanupCLI.run(
+ [
+ "ArtifactoryCleanupCLI",
+ "--config",
+ str(shared_datadir / "cleanup.yaml"),
+ "--load-rules",
+ str(shared_datadir / "myrule.py"),
+ "--output-format",
+ "table",
+ "--output",
+ str(output_file),
+ ],
+ exit=False,
+ )
+ stdout, stderr = capsys.readouterr()
+ print(stdout)
+ assert code == 0, stdout
+ assert cmp(output_file, shared_datadir / "expected_output.txt") is True
+
+
+@pytest.mark.usefixtures("requests_repo_name_here")
+def test_output_json(capsys, shared_datadir, requests_mock, tmp_path):
+ output_json = tmp_path / "output.json"
+ _, code = ArtifactoryCleanupCLI.run(
+ [
+ "ArtifactoryCleanupCLI",
+ "--config",
+ str(shared_datadir / "cleanup.yaml"),
+ "--load-rules",
+ str(shared_datadir / "myrule.py"),
+ "--output-format",
+ "json",
+ "--output",
+ str(output_json),
+ ],
+ exit=False,
+ )
+ stdout, stderr = capsys.readouterr()
+ assert code == 0, stdout
+ with open(output_json, "r") as file:
+ assert json.load(file) == {
+ "policies": [
+ {
+ "name": "Remove all files from repo-name-here older then 7 days",
+ "file_count": 1,
+ "size": 528,
+ },
+ {"name": "Use your own rules!", "file_count": 1, "size": 528},
+ ],
+ "total_size": 1056,
+ }
+
+
+@pytest.mark.usefixtures("requests_repo_name_here")
+def test_require_output_json(capsys, shared_datadir, requests_mock):
+ _, code = ArtifactoryCleanupCLI.run(
+ [
+ "ArtifactoryCleanupCLI",
+ "--config",
+ str(shared_datadir / "cleanup.yaml"),
+ "--load-rules",
+ str(shared_datadir / "myrule.py"),
+ "--output-format",
+ "json",
+ ],
+ exit=False,
+ )
+ assert code == 2, stdout
+ stdout, stderr = capsys.readouterr()
+ assert (
+ "Error: Given --output-format, the following are missing ['output']" in stdout
+ )
| Output format to Json
We would like a feature request to have the output table to Json format.
The PrettyTable libraries can do it : https://pypi.org/project/prettytable/
If I have time, I would propose a PR | 0.0 | [
"tests/test_cli.py::test_output_json",
"tests/test_cli.py::test_require_output_json",
"tests/test_cli.py::test_output_table"
] | [
"tests/test_cli.py::test_dry_mode",
"tests/test_cli.py::test_destroy",
"tests/test_cli.py::test_help"
] | 2023-03-17 06:28:51+00:00 | 1,893 |
|
devopsspiral__KubeLibrary-124 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7b2f42..e8800dd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,8 +5,14 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## In progress
+
+## [0.8.1] - 2022-12-16
+### Added
- Add proxy configuration fetched from `HTTP_PROXY` or `http_proxy` environment variable
+### Fixed
+Fix disabling cert validation [#124](https://github.com/devopsspiral/KubeLibrary/pull/124)
+
## [0.8.0] - 2022-10-27
### Added
- Add function list_namespaced_stateful_set_by_pattern [#114](https://github.com/devopsspiral/KubeLibrary/pull/113) by [@siaomingjeng](https://github.com/siaomingjeng)
diff --git a/src/KubeLibrary/KubeLibrary.py b/src/KubeLibrary/KubeLibrary.py
index 3f73adc..ebff896 100755
--- a/src/KubeLibrary/KubeLibrary.py
+++ b/src/KubeLibrary/KubeLibrary.py
@@ -1,6 +1,5 @@
import json
import re
-import ssl
import urllib3
from os import environ
@@ -276,7 +275,7 @@ class KubeLibrary:
def _add_api(self, reference, class_name):
self.__dict__[reference] = class_name(self.api_client)
if not self.cert_validation:
- self.__dict__[reference].api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'] = ssl.CERT_NONE
+ self.__dict__[reference].api_client.configuration.verify_ssl = False
def k8s_api_ping(self):
"""Performs GET on /api/v1/ for simple check of API availability.
diff --git a/src/KubeLibrary/version.py b/src/KubeLibrary/version.py
index 8675559..73baf8f 100644
--- a/src/KubeLibrary/version.py
+++ b/src/KubeLibrary/version.py
@@ -1,1 +1,1 @@
-version = "0.8.0"
+version = "0.8.1"
| devopsspiral/KubeLibrary | 7f4037c283a38751f9a31160944a17e7b80ec97b | diff --git a/test/test_KubeLibrary.py b/test/test_KubeLibrary.py
index b99291b..7cae67e 100644
--- a/test/test_KubeLibrary.py
+++ b/test/test_KubeLibrary.py
@@ -1,7 +1,6 @@
import json
import mock
import re
-import ssl
import unittest
from KubeLibrary import KubeLibrary
from KubeLibrary.exceptions import BearerTokenWithPrefixException
@@ -306,7 +305,7 @@ class TestKubeLibrary(unittest.TestCase):
kl = KubeLibrary(kube_config='test/resources/k3d', cert_validation=False)
for api in TestKubeLibrary.apis:
target = getattr(kl, api)
- self.assertEqual(target.api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'], ssl.CERT_NONE)
+ self.assertEqual(target.api_client.configuration.verify_ssl, False)
@responses.activate
def test_KubeLibrary_inits_with_bearer_token(self):
| certificate verify failed issue when using Get Namespaced Pod Exec
When using the Get Namespaced Pod Exec keywork on a k8s cluster using a custom CA, the following error occurs :
```
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get issuer certificate (_ssl.c:1129)
```
Other keywords (Read Namespaced Pod Status, List Namespaced Pod By Pattern ...) are working as expected.
As a quick fix, I'm adding the following line in the _add_api method of the library :
```
def _add_api(self, reference, class_name):
self.__dict__[reference] = class_name(self.api_client)
if not self.cert_validation:
self.__dict__[reference].api_client.rest_client.pool_manager.connection_pool_kw['cert_reqs'] = ssl.CERT_NONE
self.__dict__[reference].api_client.configuration.verify_ssl = False
```
Am I missing something regarding the library configuration ?
Versions :
```
KubeLibrary: 0.8.0
Python: 3.9.13
Kubernetes: 1.24
```
KubeLibrary :
```
Library KubeLibrary kube_config=${KUBECONFIG_FILE} cert_validation=False
KubeLibrary.Get Namespaced Pod Exec
... name=my-pod
... namespace=${namespace}
... argv_cmd=${command}
``` | 0.0 | [
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_deployment_by_pattern"
] | [
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_delete",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespace",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_with_bearer_token",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_endpoints",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_daemon_set",
"test/test_KubeLibrary.py::TestKubeLibrary::test_inits_all_api_clients",
"test/test_KubeLibrary.py::TestKubeLibrary::test_assert_pod_has_annotations",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_secret_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_create",
"test/test_KubeLibrary.py::TestKubeLibrary::test_get_namespaced_exec_without_container",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_cron_job",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_ingress",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_service_account_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_horizontal_pod_autoscaler",
"test/test_KubeLibrary.py::TestKubeLibrary::test_assert_container_has_env_vars",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_ingress",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_replace",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_job_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_with_context",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_daemon_set",
"test/test_KubeLibrary.py::TestKubeLibrary::test_get_matching_pods_in_namespace",
"test/test_KubeLibrary.py::TestKubeLibrary::test_get_namespaced_exec_not_argv_and_list",
"test/test_KubeLibrary.py::TestKubeLibrary::test_get_configmaps_in_namespace",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_cluster_role_binding",
"test/test_KubeLibrary.py::TestKubeLibrary::test_filter_containers_images",
"test/test_KubeLibrary.py::TestKubeLibrary::test_filter_pods_containers_statuses_by_name",
"test/test_KubeLibrary.py::TestKubeLibrary::test_evaluate_callable_from_k8s_client",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_persistent_volume_claim_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_init",
"test/test_KubeLibrary.py::TestKubeLibrary::test_get_kubelet_version",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_role_binding",
"test/test_KubeLibrary.py::TestKubeLibrary::test_generate_alphanumeric_str",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_from_kubeconfig",
"test/test_KubeLibrary.py::TestKubeLibrary::test_assert_pod_has_labels",
"test/test_KubeLibrary.py::TestKubeLibrary::test_filter_pods_containers_by_name",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_patch",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_inits_with_bearer_token_with_ca_crt",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_role",
"test/test_KubeLibrary.py::TestKubeLibrary::test_filter_containers_resources",
"test/test_KubeLibrary.py::TestKubeLibrary::test_get_namespaced_exec_with_container",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_fails_for_wrong_context",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_stateful_set_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_persistent_volume_claim",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_horizontal_pod_autoscaler",
"test/test_KubeLibrary.py::TestKubeLibrary::test_KubeLibrary_dynamic_get",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_service",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_service",
"test/test_KubeLibrary.py::TestKubeLibrary::test_inits_with_bearer_token_raises_BearerTokenWithPrefixException",
"test/test_KubeLibrary.py::TestKubeLibrary::test_read_namespaced_pod_status",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_replica_set_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_cron_job",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_namespaced_pod_by_pattern",
"test/test_KubeLibrary.py::TestKubeLibrary::test_list_cluster_role"
] | 2022-12-16 14:17:09+00:00 | 1,894 |
|
devsnd__tinytag-156 | diff --git a/README.md b/README.md
index 39bfda9..cec3e9d 100644
--- a/README.md
+++ b/README.md
@@ -66,7 +66,7 @@ List of possible attributes you can get with TinyTag:
tag.title # title of the song
tag.track # track number as string
tag.track_total # total number of tracks as string
- tag.year # year or data as string
+ tag.year # year or date as string
For non-common fields and fields specific to single file formats use extra
diff --git a/tinytag/tinytag.py b/tinytag/tinytag.py
index 66fff62..a581e66 100644
--- a/tinytag/tinytag.py
+++ b/tinytag/tinytag.py
@@ -484,7 +484,7 @@ class ID3(TinyTag):
FRAME_ID_TO_FIELD = { # Mapping from Frame ID to a field of the TinyTag
'COMM': 'comment', 'COM': 'comment',
'TRCK': 'track', 'TRK': 'track',
- 'TYER': 'year', 'TYE': 'year',
+ 'TYER': 'year', 'TYE': 'year', 'TDRC': 'year',
'TALB': 'album', 'TAL': 'album',
'TPE1': 'artist', 'TP1': 'artist',
'TIT2': 'title', 'TT2': 'title',
| devsnd/tinytag | 5107f8611192a166dfea4f75619377ab2d5bda49 | diff --git a/tinytag/tests/test_all.py b/tinytag/tests/test_all.py
index abbb5dc..743e48b 100644
--- a/tinytag/tests/test_all.py
+++ b/tinytag/tests/test_all.py
@@ -73,7 +73,7 @@ testfiles = OrderedDict([
('samples/utf-8-id3v2.mp3',
{'extra': {}, 'genre': 'Acustico',
'track_total': '21', 'track': '01', 'filesize': 2119, 'title': 'Gran dΓa',
- 'artist': 'Paso a paso', 'album': 'S/T', 'disc': '', 'disc_total': '0'}),
+ 'artist': 'Paso a paso', 'album': 'S/T', 'disc': '', 'disc_total': '0', 'year': '2003'}),
('samples/empty_file.mp3',
{'extra': {}, 'filesize': 0}),
('samples/silence-44khz-56k-mono-1s.mp3',
@@ -88,10 +88,11 @@ testfiles = OrderedDict([
'track_total': '12', 'genre': 'AlternRock',
'title': 'Out of the Woodwork', 'artist': 'Courtney Barnett',
'albumartist': 'Courtney Barnett', 'disc': '1',
- 'comment': 'Amazon.com Song ID: 240853806', 'composer': 'Courtney Barnett'}),
+ 'comment': 'Amazon.com Song ID: 240853806', 'composer': 'Courtney Barnett',
+ 'year': '2013'}),
('samples/utf16be.mp3',
{'extra': {}, 'title': '52-girls', 'filesize': 2048, 'track': '6', 'album': 'party mix',
- 'artist': 'The B52s', 'genre': 'Rock'}),
+ 'artist': 'The B52s', 'genre': 'Rock', 'year': '1981'}),
('samples/id3v22_image.mp3',
{'extra': {}, 'title': 'Kids (MGMT Cover) ', 'filesize': 35924,
'album': 'winniecooper.net ', 'artist': 'The Kooks', 'year': '2008',
@@ -189,7 +190,7 @@ testfiles = OrderedDict([
('samples/id3v24_genre_null_byte.mp3',
{'extra': {}, 'filesize': 256, 'album': '\u79d8\u5bc6', 'albumartist': 'aiko',
'artist': 'aiko', 'disc': '1', 'genre': 'Pop',
- 'title': '\u661f\u306e\u306a\u3044\u4e16\u754c', 'track': '10'}),
+ 'title': '\u661f\u306e\u306a\u3044\u4e16\u754c', 'track': '10', 'year': '2008'}),
('samples/vbr_xing_header_short.mp3',
{'filesize': 432, 'audio_offset': 133, 'bitrate': 24.0, 'channels': 1, 'duration': 0.144,
'extra': {}, 'samplerate': 8000}),
@@ -376,7 +377,7 @@ testfiles = OrderedDict([
{'extra': {}, 'channels': 2, 'duration': 0.2999546485260771, 'filesize': 6892,
'artist': 'Serhiy Storchaka', 'title': 'Pluck', 'album': 'Python Test Suite',
'bitrate': 176.4, 'samplerate': 11025, 'audio_offset': 116,
- 'comment': 'Audacity Pluck + Wahwah'}),
+ 'comment': 'Audacity Pluck + Wahwah', 'year': '2013'}),
('samples/M1F1-mulawC-AFsp.afc',
{'extra': {}, 'channels': 2, 'duration': 2.936625, 'filesize': 47148,
'bitrate': 256.0, 'samplerate': 8000, 'audio_offset': 154,
| [BUG] Parsing mp3 file w/ valid TDRC tag does not populate year
**Describe the bug**
When parsing a mp3 file w/ valid v2.4 metadata and a TDRC frame, TinyTag does not populate the year attribute in the output.
**To Reproduce**
Steps to reproduce the behavior:
1. Open a valid mp3 file w/ TinyTag
2. See `Found id3 Frame TDRC` in the program output
3. Resulting dict still has `"year": null`
**Expected behavior**
Valid timestamps (yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddTHH, yyyy-MM-ddTHH:mm
and yyyy-MM-ddTHH:mm:ss) should result in year attribute populated.
**Sample File**
https://www.dropbox.com/s/lz6vlzhw18znqp8/cdwal5Kw3Fc.mp3?dl=0 | 0.0 | [
"tinytag/tests/test_all.py::test_file_reading[samples/utf-8-id3v2.mp3-expected8]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v24-long-title.mp3-expected12]",
"tinytag/tests/test_all.py::test_file_reading[samples/utf16be.mp3-expected13]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v24_genre_null_byte.mp3-expected39]",
"tinytag/tests/test_all.py::test_file_reading[samples/pluck-pcm8.aiff-expected77]"
] | [
"tinytag/tests/test_all.py::test_file_reading[samples/vbri.mp3-expected0]",
"tinytag/tests/test_all.py::test_file_reading[samples/cbr.mp3-expected1]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header.mp3-expected2]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header_2channel.mp3-expected3]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22-test.mp3-expected4]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-44-s-v1.mp3-expected5]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v1-latin1.mp3-expected6]",
"tinytag/tests/test_all.py::test_file_reading[samples/UTF16.mp3-expected7]",
"tinytag/tests/test_all.py::test_file_reading[samples/empty_file.mp3-expected9]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-44khz-56k-mono-1s.mp3-expected10]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-22khz-mono-1s.mp3-expected11]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22_image.mp3-expected14]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22.TCO.genre.mp3-expected15]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_comment_utf_16_with_bom.mp3-expected16]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_comment_utf_16_double_bom.mp3-expected17]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_genre_id_out_of_bounds.mp3-expected18]",
"tinytag/tests/test_all.py::test_file_reading[samples/image-text-encoding.mp3-expected19]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v1_does_not_overwrite_id3v2.mp3-expected20]",
"tinytag/tests/test_all.py::test_file_reading[samples/nicotinetestdata.mp3-expected21]",
"tinytag/tests/test_all.py::test_file_reading[samples/chinese_id3.mp3-expected22]",
"tinytag/tests/test_all.py::test_file_reading[samples/cut_off_titles.mp3-expected23]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_xxx_lang.mp3-expected24]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr8.mp3-expected25]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr8stereo.mp3-expected26]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr11.mp3-expected27]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr11stereo.mp3-expected28]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr16.mp3-expected29]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr16stereo.mp3-expected30]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr22.mp3-expected31]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr22stereo.mp3-expected32]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr32.mp3-expected33]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr32stereo.mp3-expected34]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr44.mp3-expected35]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr44stereo.mp3-expected36]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr48.mp3-expected37]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr48stereo.mp3-expected38]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header_short.mp3-expected40]",
"tinytag/tests/test_all.py::test_file_reading[samples/empty.ogg-expected41]",
"tinytag/tests/test_all.py::test_file_reading[samples/multipagecomment.ogg-expected42]",
"tinytag/tests/test_all.py::test_file_reading[samples/multipage-setup.ogg-expected43]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.ogg-expected44]",
"tinytag/tests/test_all.py::test_file_reading[samples/corrupt_metadata.ogg-expected45]",
"tinytag/tests/test_all.py::test_file_reading[samples/composer.ogg-expected46]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.opus-expected47]",
"tinytag/tests/test_all.py::test_file_reading[samples/8khz_5s.opus-expected48]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.wav-expected49]",
"tinytag/tests/test_all.py::test_file_reading[samples/test3sMono.wav-expected50]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-tagged.wav-expected51]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-riff-tags.wav-expected52]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-22khz-mono-1s.wav-expected53]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_header_with_a_zero_byte.wav-expected54]",
"tinytag/tests/test_all.py::test_file_reading[samples/adpcm.wav-expected55]",
"tinytag/tests/test_all.py::test_file_reading[samples/riff_extra_zero.wav-expected56]",
"tinytag/tests/test_all.py::test_file_reading[samples/riff_extra_zero_2.wav-expected57]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac1sMono.flac-expected58]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac453sStereo.flac-expected59]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac1.5sStereo.flac-expected60]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac_application.flac-expected61]",
"tinytag/tests/test_all.py::test_file_reading[samples/no-tags.flac-expected62]",
"tinytag/tests/test_all.py::test_file_reading[samples/variable-block.flac-expected63]",
"tinytag/tests/test_all.py::test_file_reading[samples/106-invalid-streaminfo.flac-expected64]",
"tinytag/tests/test_all.py::test_file_reading[samples/106-short-picture-block-size.flac-expected65]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_id3_header.flac-expected66]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_padded_id3_header.flac-expected67]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_padded_id3_header2.flac-expected68]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac_with_image.flac-expected69]",
"tinytag/tests/test_all.py::test_file_reading[samples/test2.wma-expected70]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.m4a-expected71]",
"tinytag/tests/test_all.py::test_file_reading[samples/test2.m4a-expected72]",
"tinytag/tests/test_all.py::test_file_reading[samples/iso8859_with_image.m4a-expected73]",
"tinytag/tests/test_all.py::test_file_reading[samples/alac_file.m4a-expected74]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-tagged.aiff-expected75]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.aiff-expected76]",
"tinytag/tests/test_all.py::test_file_reading[samples/M1F1-mulawC-AFsp.afc-expected78]",
"tinytag/tests/test_all.py::test_pathlib_compatibility",
"tinytag/tests/test_all.py::test_binary_path_compatibility",
"tinytag/tests/test_all.py::test_override_encoding",
"tinytag/tests/test_all.py::test_mp3_length_estimation",
"tinytag/tests/test_all.py::test_unpad",
"tinytag/tests/test_all.py::test_mp3_image_loading",
"tinytag/tests/test_all.py::test_mp3_id3v22_image_loading",
"tinytag/tests/test_all.py::test_mp3_image_loading_without_description",
"tinytag/tests/test_all.py::test_mp3_image_loading_with_utf8_description",
"tinytag/tests/test_all.py::test_mp3_image_loading2",
"tinytag/tests/test_all.py::test_mp3_utf_8_invalid_string_raises_exception",
"tinytag/tests/test_all.py::test_mp3_utf_8_invalid_string_can_be_ignored",
"tinytag/tests/test_all.py::test_mp4_image_loading",
"tinytag/tests/test_all.py::test_flac_image_loading",
"tinytag/tests/test_all.py::test_aiff_image_loading",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp3_id3.x-ID3]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp3_fffb.x-ID3]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_ogg.x-Ogg]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_wav.x-Wave]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_flac.x-Flac]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_wma.x-Wma]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp4_m4a.x-MP4]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_aiff.x-Aiff]",
"tinytag/tests/test_all.py::test_show_hint_for_wrong_usage",
"tinytag/tests/test_all.py::test_to_str"
] | 2022-09-02 01:45:25+00:00 | 1,895 |
|
devsnd__tinytag-171 | diff --git a/tinytag/tinytag.py b/tinytag/tinytag.py
index a7a8a21..8ba376d 100644
--- a/tinytag/tinytag.py
+++ b/tinytag/tinytag.py
@@ -924,8 +924,10 @@ class Ogg(TinyTag):
'artist': 'artist',
'date': 'year',
'tracknumber': 'track',
+ 'tracktotal': 'track_total',
'totaltracks': 'track_total',
'discnumber': 'disc',
+ 'disctotal': 'disc_total',
'totaldiscs': 'disc_total',
'genre': 'genre',
'description': 'comment',
| devsnd/tinytag | 85a16fa18bcc534d1d61f10ca539955823945d5d | diff --git a/tinytag/tests/test_all.py b/tinytag/tests/test_all.py
index 8f4421c..0b70517 100644
--- a/tinytag/tests/test_all.py
+++ b/tinytag/tests/test_all.py
@@ -230,7 +230,7 @@ testfiles = OrderedDict([
'track': '1', 'disc': '1', 'title': 'Bad Apple!!', 'duration': 2.0, 'year': '2008.05.25',
'filesize': 10000, 'artist': 'nomico',
'album': 'Exserens - A selection of Alstroemeria Records',
- 'comment': 'ARCD0018 - Lovelight'}),
+ 'comment': 'ARCD0018 - Lovelight', 'disc_total': '1', 'track_total': '13'}),
('samples/8khz_5s.opus',
{'extra': {}, 'filesize': 7251, 'channels': 1, 'samplerate': 48000, 'duration': 5.0}),
| Fail to read track_total, but it is ok in foobar
I got some tracks from qobuz.
I have some problems in reading the track_total. It showed 'null' in track_total. The others is OK, such as artist, album etc....
But its track_total seems OK, when checked in foobar.
Why?
The attachment are an example flac file
[19. I m Not The Man You Think I Am.zip](https://github.com/devsnd/tinytag/files/10875229/19.I.m.Not.The.Man.You.Think.I.Am.zip)
| 0.0 | [
"tinytag/tests/test_all.py::test_file_reading[samples/test.opus-expected47]"
] | [
"tinytag/tests/test_all.py::test_file_reading[samples/vbri.mp3-expected0]",
"tinytag/tests/test_all.py::test_file_reading[samples/cbr.mp3-expected1]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header.mp3-expected2]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header_2channel.mp3-expected3]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22-test.mp3-expected4]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-44-s-v1.mp3-expected5]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v1-latin1.mp3-expected6]",
"tinytag/tests/test_all.py::test_file_reading[samples/UTF16.mp3-expected7]",
"tinytag/tests/test_all.py::test_file_reading[samples/utf-8-id3v2.mp3-expected8]",
"tinytag/tests/test_all.py::test_file_reading[samples/empty_file.mp3-expected9]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-44khz-56k-mono-1s.mp3-expected10]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-22khz-mono-1s.mp3-expected11]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v24-long-title.mp3-expected12]",
"tinytag/tests/test_all.py::test_file_reading[samples/utf16be.mp3-expected13]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22_image.mp3-expected14]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22.TCO.genre.mp3-expected15]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_comment_utf_16_with_bom.mp3-expected16]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_comment_utf_16_double_bom.mp3-expected17]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_genre_id_out_of_bounds.mp3-expected18]",
"tinytag/tests/test_all.py::test_file_reading[samples/image-text-encoding.mp3-expected19]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v1_does_not_overwrite_id3v2.mp3-expected20]",
"tinytag/tests/test_all.py::test_file_reading[samples/nicotinetestdata.mp3-expected21]",
"tinytag/tests/test_all.py::test_file_reading[samples/chinese_id3.mp3-expected22]",
"tinytag/tests/test_all.py::test_file_reading[samples/cut_off_titles.mp3-expected23]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_xxx_lang.mp3-expected24]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr8.mp3-expected25]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr8stereo.mp3-expected26]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr11.mp3-expected27]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr11stereo.mp3-expected28]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr16.mp3-expected29]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr16stereo.mp3-expected30]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr22.mp3-expected31]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr22stereo.mp3-expected32]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr32.mp3-expected33]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr32stereo.mp3-expected34]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr44.mp3-expected35]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr44stereo.mp3-expected36]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr48.mp3-expected37]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr48stereo.mp3-expected38]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v24_genre_null_byte.mp3-expected39]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header_short.mp3-expected40]",
"tinytag/tests/test_all.py::test_file_reading[samples/empty.ogg-expected41]",
"tinytag/tests/test_all.py::test_file_reading[samples/multipagecomment.ogg-expected42]",
"tinytag/tests/test_all.py::test_file_reading[samples/multipage-setup.ogg-expected43]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.ogg-expected44]",
"tinytag/tests/test_all.py::test_file_reading[samples/corrupt_metadata.ogg-expected45]",
"tinytag/tests/test_all.py::test_file_reading[samples/composer.ogg-expected46]",
"tinytag/tests/test_all.py::test_file_reading[samples/8khz_5s.opus-expected48]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.wav-expected49]",
"tinytag/tests/test_all.py::test_file_reading[samples/test3sMono.wav-expected50]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-tagged.wav-expected51]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-riff-tags.wav-expected52]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-22khz-mono-1s.wav-expected53]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_header_with_a_zero_byte.wav-expected54]",
"tinytag/tests/test_all.py::test_file_reading[samples/adpcm.wav-expected55]",
"tinytag/tests/test_all.py::test_file_reading[samples/riff_extra_zero.wav-expected56]",
"tinytag/tests/test_all.py::test_file_reading[samples/riff_extra_zero_2.wav-expected57]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac1sMono.flac-expected58]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac453sStereo.flac-expected59]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac1.5sStereo.flac-expected60]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac_application.flac-expected61]",
"tinytag/tests/test_all.py::test_file_reading[samples/no-tags.flac-expected62]",
"tinytag/tests/test_all.py::test_file_reading[samples/variable-block.flac-expected63]",
"tinytag/tests/test_all.py::test_file_reading[samples/106-invalid-streaminfo.flac-expected64]",
"tinytag/tests/test_all.py::test_file_reading[samples/106-short-picture-block-size.flac-expected65]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_id3_header.flac-expected66]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_padded_id3_header.flac-expected67]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_padded_id3_header2.flac-expected68]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac_with_image.flac-expected69]",
"tinytag/tests/test_all.py::test_file_reading[samples/test2.wma-expected70]",
"tinytag/tests/test_all.py::test_file_reading[samples/lossless.wma-expected71]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.m4a-expected72]",
"tinytag/tests/test_all.py::test_file_reading[samples/test2.m4a-expected73]",
"tinytag/tests/test_all.py::test_file_reading[samples/iso8859_with_image.m4a-expected74]",
"tinytag/tests/test_all.py::test_file_reading[samples/alac_file.m4a-expected75]",
"tinytag/tests/test_all.py::test_file_reading[samples/mpeg4_desc_cmt.m4a-expected76]",
"tinytag/tests/test_all.py::test_file_reading[samples/mpeg4_xa9des.m4a-expected77]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-tagged.aiff-expected78]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.aiff-expected79]",
"tinytag/tests/test_all.py::test_file_reading[samples/pluck-pcm8.aiff-expected80]",
"tinytag/tests/test_all.py::test_file_reading[samples/M1F1-mulawC-AFsp.afc-expected81]",
"tinytag/tests/test_all.py::test_file_reading[samples/invalid_sample_rate.aiff-expected82]",
"tinytag/tests/test_all.py::test_pathlib_compatibility",
"tinytag/tests/test_all.py::test_binary_path_compatibility",
"tinytag/tests/test_all.py::test_override_encoding",
"tinytag/tests/test_all.py::test_mp3_length_estimation",
"tinytag/tests/test_all.py::test_unpad",
"tinytag/tests/test_all.py::test_mp3_image_loading",
"tinytag/tests/test_all.py::test_mp3_id3v22_image_loading",
"tinytag/tests/test_all.py::test_mp3_image_loading_without_description",
"tinytag/tests/test_all.py::test_mp3_image_loading_with_utf8_description",
"tinytag/tests/test_all.py::test_mp3_image_loading2",
"tinytag/tests/test_all.py::test_mp3_utf_8_invalid_string_raises_exception",
"tinytag/tests/test_all.py::test_mp3_utf_8_invalid_string_can_be_ignored",
"tinytag/tests/test_all.py::test_mp4_image_loading",
"tinytag/tests/test_all.py::test_flac_image_loading",
"tinytag/tests/test_all.py::test_ogg_image_loading",
"tinytag/tests/test_all.py::test_aiff_image_loading",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp3_id3.x-ID3]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp3_fffb.x-ID3]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_ogg.x-Ogg]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_wav.x-Wave]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_flac.x-Flac]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_wma.x-Wma]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp4_m4a.x-MP4]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_aiff.x-Aiff]",
"tinytag/tests/test_all.py::test_show_hint_for_wrong_usage",
"tinytag/tests/test_all.py::test_to_str"
] | 2023-03-20 22:28:45+00:00 | 1,896 |
|
devsnd__tinytag-178 | diff --git a/tinytag/tinytag.py b/tinytag/tinytag.py
index a3f1305..595a101 100644
--- a/tinytag/tinytag.py
+++ b/tinytag/tinytag.py
@@ -170,40 +170,48 @@ class TinyTag(object):
return parser
@classmethod
- def get_parser_class(cls, filename, filehandle):
+ def get_parser_class(cls, filename=None, filehandle=None):
if cls != TinyTag: # if `get` is invoked on TinyTag, find parser by ext
return cls # otherwise use the class on which `get` was invoked
- parser_class = cls._get_parser_for_filename(filename)
- if parser_class is not None:
- return parser_class
+ if filename:
+ parser_class = cls._get_parser_for_filename(filename)
+ if parser_class is not None:
+ return parser_class
# try determining the file type by magic byte header
- parser_class = cls._get_parser_for_file_handle(filehandle)
- if parser_class is not None:
- return parser_class
+ if filehandle:
+ parser_class = cls._get_parser_for_file_handle(filehandle)
+ if parser_class is not None:
+ return parser_class
raise TinyTagException('No tag reader found to support filetype! ')
@classmethod
- def get(cls, filename, tags=True, duration=True, image=False, ignore_errors=False,
- encoding=None):
- try: # cast pathlib.Path to str
- import pathlib
- if isinstance(filename, pathlib.Path):
- filename = str(filename.absolute())
- except ImportError:
- pass
+ def get(cls, filename=None, tags=True, duration=True, image=False,
+ ignore_errors=False, encoding=None, file_obj=None):
+ should_open_file = (file_obj is None)
+ if should_open_file:
+ try:
+ file_obj = io.open(filename, 'rb')
+ except TypeError:
+ file_obj = io.open(str(filename.absolute()), 'rb') # Python 3.4/3.5 pathlib support
+ filename = file_obj.name
else:
- filename = os.path.expanduser(filename)
- size = os.path.getsize(filename)
- if not size > 0:
- return TinyTag(None, 0)
- with io.open(filename, 'rb') as af:
- parser_class = cls.get_parser_class(filename, af)
- tag = parser_class(af, size, ignore_errors=ignore_errors)
+ file_obj = io.BufferedReader(file_obj) # buffered reader to support peeking
+ try:
+ file_obj.seek(0, os.SEEK_END)
+ filesize = file_obj.tell()
+ file_obj.seek(0)
+ if filesize <= 0:
+ return TinyTag(None, filesize)
+ parser_class = cls.get_parser_class(filename, file_obj)
+ tag = parser_class(file_obj, filesize, ignore_errors=ignore_errors)
tag._filename = filename
tag._default_encoding = encoding
tag.load(tags=tags, duration=duration, image=image)
tag.extra = dict(tag.extra) # turn default dict into dict so that it can throw KeyError
return tag
+ finally:
+ if should_open_file:
+ file_obj.close()
def __str__(self):
return json.dumps(OrderedDict(sorted(self.as_dict().items())))
| devsnd/tinytag | 337c044ce51f9e707b8cd31d02896c9041a98afa | diff --git a/tinytag/tests/test_all.py b/tinytag/tests/test_all.py
index 0b70517..aa3a38e 100644
--- a/tinytag/tests/test_all.py
+++ b/tinytag/tests/test_all.py
@@ -510,6 +510,13 @@ def test_pathlib_compatibility():
TinyTag.get(filename)
+def test_bytesio_compatibility():
+ testfile = next(iter(testfiles.keys()))
+ filename = os.path.join(testfolder, testfile)
+ with io.open(filename, 'rb') as file_handle:
+ TinyTag.get(file_obj=io.BytesIO(file_handle.read()))
+
+
@pytest.mark.skipif(sys.platform == "win32", reason='Windows does not support binary paths')
def test_binary_path_compatibility():
binary_file_path = os.path.join(os.path.dirname(__file__).encode('utf-8'), b'\x01.mp3')
| Support BytesIo objects for tagging
It would be awesome to support BytesIO or any other IO types with TinyTag. This way it can be used in some scenarios where files are packaged and do not have a normal path. | 0.0 | [
"tinytag/tests/test_all.py::test_bytesio_compatibility"
] | [
"tinytag/tests/test_all.py::test_file_reading[samples/vbri.mp3-expected0]",
"tinytag/tests/test_all.py::test_file_reading[samples/cbr.mp3-expected1]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header.mp3-expected2]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header_2channel.mp3-expected3]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22-test.mp3-expected4]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-44-s-v1.mp3-expected5]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v1-latin1.mp3-expected6]",
"tinytag/tests/test_all.py::test_file_reading[samples/UTF16.mp3-expected7]",
"tinytag/tests/test_all.py::test_file_reading[samples/utf-8-id3v2.mp3-expected8]",
"tinytag/tests/test_all.py::test_file_reading[samples/empty_file.mp3-expected9]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-44khz-56k-mono-1s.mp3-expected10]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-22khz-mono-1s.mp3-expected11]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v24-long-title.mp3-expected12]",
"tinytag/tests/test_all.py::test_file_reading[samples/utf16be.mp3-expected13]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22_image.mp3-expected14]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v22.TCO.genre.mp3-expected15]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_comment_utf_16_with_bom.mp3-expected16]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_comment_utf_16_double_bom.mp3-expected17]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_genre_id_out_of_bounds.mp3-expected18]",
"tinytag/tests/test_all.py::test_file_reading[samples/image-text-encoding.mp3-expected19]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v1_does_not_overwrite_id3v2.mp3-expected20]",
"tinytag/tests/test_all.py::test_file_reading[samples/nicotinetestdata.mp3-expected21]",
"tinytag/tests/test_all.py::test_file_reading[samples/chinese_id3.mp3-expected22]",
"tinytag/tests/test_all.py::test_file_reading[samples/cut_off_titles.mp3-expected23]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_xxx_lang.mp3-expected24]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr8.mp3-expected25]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr8stereo.mp3-expected26]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr11.mp3-expected27]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr11stereo.mp3-expected28]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr16.mp3-expected29]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr16stereo.mp3-expected30]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr22.mp3-expected31]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr22stereo.mp3-expected32]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr32.mp3-expected33]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr32stereo.mp3-expected34]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr44.mp3-expected35]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr44stereo.mp3-expected36]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr48.mp3-expected37]",
"tinytag/tests/test_all.py::test_file_reading[samples/mp3/vbr/vbr48stereo.mp3-expected38]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3v24_genre_null_byte.mp3-expected39]",
"tinytag/tests/test_all.py::test_file_reading[samples/vbr_xing_header_short.mp3-expected40]",
"tinytag/tests/test_all.py::test_file_reading[samples/empty.ogg-expected41]",
"tinytag/tests/test_all.py::test_file_reading[samples/multipagecomment.ogg-expected42]",
"tinytag/tests/test_all.py::test_file_reading[samples/multipage-setup.ogg-expected43]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.ogg-expected44]",
"tinytag/tests/test_all.py::test_file_reading[samples/corrupt_metadata.ogg-expected45]",
"tinytag/tests/test_all.py::test_file_reading[samples/composer.ogg-expected46]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.opus-expected47]",
"tinytag/tests/test_all.py::test_file_reading[samples/8khz_5s.opus-expected48]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.wav-expected49]",
"tinytag/tests/test_all.py::test_file_reading[samples/test3sMono.wav-expected50]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-tagged.wav-expected51]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-riff-tags.wav-expected52]",
"tinytag/tests/test_all.py::test_file_reading[samples/silence-22khz-mono-1s.wav-expected53]",
"tinytag/tests/test_all.py::test_file_reading[samples/id3_header_with_a_zero_byte.wav-expected54]",
"tinytag/tests/test_all.py::test_file_reading[samples/adpcm.wav-expected55]",
"tinytag/tests/test_all.py::test_file_reading[samples/riff_extra_zero.wav-expected56]",
"tinytag/tests/test_all.py::test_file_reading[samples/riff_extra_zero_2.wav-expected57]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac1sMono.flac-expected58]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac453sStereo.flac-expected59]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac1.5sStereo.flac-expected60]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac_application.flac-expected61]",
"tinytag/tests/test_all.py::test_file_reading[samples/no-tags.flac-expected62]",
"tinytag/tests/test_all.py::test_file_reading[samples/variable-block.flac-expected63]",
"tinytag/tests/test_all.py::test_file_reading[samples/106-invalid-streaminfo.flac-expected64]",
"tinytag/tests/test_all.py::test_file_reading[samples/106-short-picture-block-size.flac-expected65]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_id3_header.flac-expected66]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_padded_id3_header.flac-expected67]",
"tinytag/tests/test_all.py::test_file_reading[samples/with_padded_id3_header2.flac-expected68]",
"tinytag/tests/test_all.py::test_file_reading[samples/flac_with_image.flac-expected69]",
"tinytag/tests/test_all.py::test_file_reading[samples/test2.wma-expected70]",
"tinytag/tests/test_all.py::test_file_reading[samples/lossless.wma-expected71]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.m4a-expected72]",
"tinytag/tests/test_all.py::test_file_reading[samples/test2.m4a-expected73]",
"tinytag/tests/test_all.py::test_file_reading[samples/iso8859_with_image.m4a-expected74]",
"tinytag/tests/test_all.py::test_file_reading[samples/alac_file.m4a-expected75]",
"tinytag/tests/test_all.py::test_file_reading[samples/mpeg4_desc_cmt.m4a-expected76]",
"tinytag/tests/test_all.py::test_file_reading[samples/mpeg4_xa9des.m4a-expected77]",
"tinytag/tests/test_all.py::test_file_reading[samples/test-tagged.aiff-expected78]",
"tinytag/tests/test_all.py::test_file_reading[samples/test.aiff-expected79]",
"tinytag/tests/test_all.py::test_file_reading[samples/pluck-pcm8.aiff-expected80]",
"tinytag/tests/test_all.py::test_file_reading[samples/M1F1-mulawC-AFsp.afc-expected81]",
"tinytag/tests/test_all.py::test_file_reading[samples/invalid_sample_rate.aiff-expected82]",
"tinytag/tests/test_all.py::test_pathlib_compatibility",
"tinytag/tests/test_all.py::test_binary_path_compatibility",
"tinytag/tests/test_all.py::test_override_encoding",
"tinytag/tests/test_all.py::test_mp3_length_estimation",
"tinytag/tests/test_all.py::test_unpad",
"tinytag/tests/test_all.py::test_mp3_image_loading",
"tinytag/tests/test_all.py::test_mp3_id3v22_image_loading",
"tinytag/tests/test_all.py::test_mp3_image_loading_without_description",
"tinytag/tests/test_all.py::test_mp3_image_loading_with_utf8_description",
"tinytag/tests/test_all.py::test_mp3_image_loading2",
"tinytag/tests/test_all.py::test_mp3_utf_8_invalid_string_raises_exception",
"tinytag/tests/test_all.py::test_mp3_utf_8_invalid_string_can_be_ignored",
"tinytag/tests/test_all.py::test_mp4_image_loading",
"tinytag/tests/test_all.py::test_flac_image_loading",
"tinytag/tests/test_all.py::test_ogg_image_loading",
"tinytag/tests/test_all.py::test_aiff_image_loading",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp3_id3.x-ID3]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp3_fffb.x-ID3]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_ogg.x-Ogg]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_wav.x-Wave]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_flac.x-Flac]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_wma.x-Wma]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_mp4_m4a.x-MP4]",
"tinytag/tests/test_all.py::test_detect_magic_headers[samples/detect_aiff.x-Aiff]",
"tinytag/tests/test_all.py::test_show_hint_for_wrong_usage",
"tinytag/tests/test_all.py::test_to_str"
] | 2023-06-02 19:58:04+00:00 | 1,897 |
|
dfm__emcee-295 | diff --git a/.travis.yml b/.travis.yml
index fa02161..4aa919c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -23,7 +23,7 @@ install:
- travis_retry python setup.py develop
script:
- - py.test -v emcee/tests --cov emcee
+ - pytest -v emcee/tests --cov emcee
after_success:
- coveralls
diff --git a/emcee/ensemble.py b/emcee/ensemble.py
index ae6a976..7d30afc 100644
--- a/emcee/ensemble.py
+++ b/emcee/ensemble.py
@@ -478,8 +478,8 @@ class EnsembleSampler(object):
@property
@deprecated("get_log_prob()")
def lnprobability(self): # pragma: no cover
- return self.get_log_prob()
-
+ log_prob = self.get_log_prob()
+ return np.swapaxes(log_prob, 0, 1)
@property
@deprecated("get_log_prob(flat=True)")
def flatlnprobability(self): # pragma: no cover
| dfm/emcee | 593a6b134170c47af6e31106244df78b6fb194db | diff --git a/emcee/tests/unit/test_sampler.py b/emcee/tests/unit/test_sampler.py
index 48a351a..ca38a56 100644
--- a/emcee/tests/unit/test_sampler.py
+++ b/emcee/tests/unit/test_sampler.py
@@ -47,11 +47,15 @@ def test_shapes(backend, moves, nwalkers=32, ndim=3, nsteps=10, seed=1234):
assert tau.shape == (ndim,)
# Check the shapes.
- assert sampler.chain.shape == (nwalkers, nsteps, ndim), \
- "incorrect coordinate dimensions"
+ with pytest.warns(DeprecationWarning):
+ assert sampler.chain.shape == (nwalkers, nsteps, ndim), \
+ "incorrect coordinate dimensions"
+ with pytest.warns(DeprecationWarning):
+ assert sampler.lnprobability.shape == (nwalkers, nsteps), \
+ "incorrect probability dimensions"
assert sampler.get_chain().shape == (nsteps, nwalkers, ndim), \
"incorrect coordinate dimensions"
- assert sampler.lnprobability.shape == (nsteps, nwalkers), \
+ assert sampler.get_log_prob().shape == (nsteps, nwalkers), \
"incorrect probability dimensions"
assert sampler.acceptance_fraction.shape == (nwalkers,), \
@@ -77,14 +81,14 @@ def test_errors(backend, nwalkers=32, ndim=3, nsteps=5, seed=1234):
# Test for not running.
with pytest.raises(AttributeError):
- sampler.chain
+ sampler.get_chain()
with pytest.raises(AttributeError):
- sampler.lnprobability
+ sampler.get_log_prob()
# What about not storing the chain.
sampler.run_mcmc(coords, nsteps, store=False)
with pytest.raises(AttributeError):
- sampler.chain
+ sampler.get_chain()
# Now what about if we try to continue using the sampler with an
# ensemble of a different shape.
@@ -121,12 +125,15 @@ def run_sampler(backend, nwalkers=32, ndim=3, nsteps=25, seed=1234,
def test_thin(backend):
with backend() as be:
with pytest.raises(ValueError):
- run_sampler(be, thin=-1)
+ with pytest.warns(DeprecationWarning):
+ run_sampler(be, thin=-1)
with pytest.raises(ValueError):
- run_sampler(be, thin=0.1)
+ with pytest.warns(DeprecationWarning):
+ run_sampler(be, thin=0.1)
thinby = 3
sampler1 = run_sampler(None)
- sampler2 = run_sampler(be, thin=thinby)
+ with pytest.warns(DeprecationWarning):
+ sampler2 = run_sampler(be, thin=thinby)
for k in ["get_chain", "get_log_prob"]:
a = getattr(sampler1, k)()[thinby-1::thinby]
b = getattr(sampler2, k)()
| sampler.lnprobability is transposed in emcee3?
tl;dr it looks like `sampler.lnprobability` is transposed in emcee 3 from what I would expect from emcee 2.
Sample code (copy pasta'd from the old docs):
```python
import numpy as np
import emcee
def lnprob(x, ivar):
return -0.5 * np.sum(ivar * x ** 2)
ndim, nwalkers = 10, 100
ivar = 1. / np.random.rand(ndim)
p0 = [np.random.rand(ndim) for i in range(nwalkers)]
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=[ivar])
_ = sampler.run_mcmc(p0, 1000)
print(emcee.__version__)
print(sampler.chain.shape, sampler.lnprobability.shape)
```
## Output from emcee 2.2.1
```
2.2.1
(100, 1000, 10) (100, 1000)
```
## Output from emcee 3.0rc2
```
3.0rc2
(100, 1000, 10) (1000, 100)
``` | 0.0 | [
"emcee/tests/unit/test_sampler.py::test_shapes[Backend-None]",
"emcee/tests/unit/test_sampler.py::test_shapes[Backend-moves1]",
"emcee/tests/unit/test_sampler.py::test_shapes[Backend-moves2]",
"emcee/tests/unit/test_sampler.py::test_shapes[Backend-moves3]"
] | [
"emcee/tests/unit/test_sampler.py::test_thin[Backend]",
"emcee/tests/unit/test_sampler.py::test_thin_by[Backend-True]",
"emcee/tests/unit/test_sampler.py::test_thin_by[Backend-False]",
"emcee/tests/unit/test_sampler.py::test_restart[Backend]",
"emcee/tests/unit/test_sampler.py::test_vectorize",
"emcee/tests/unit/test_sampler.py::test_pickle[Backend]"
] | 2019-04-11 00:18:44+00:00 | 1,898 |
|
dfm__emcee-354 | diff --git a/src/emcee/autocorr.py b/src/emcee/autocorr.py
index 5156372..4a804ff 100644
--- a/src/emcee/autocorr.py
+++ b/src/emcee/autocorr.py
@@ -49,7 +49,7 @@ def integrated_time(x, c=5, tol=50, quiet=False):
"""Estimate the integrated autocorrelation time of a time series.
This estimate uses the iterative procedure described on page 16 of
- `Sokal's notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ to
+ `Sokal's notes <https://www.semanticscholar.org/paper/Monte-Carlo-Methods-in-Statistical-Mechanics%3A-and-Sokal/0bfe9e3db30605fe2d4d26e1a288a5e2997e7225>`_ to
determine a reasonable window size.
Args:
diff --git a/src/emcee/backends/hdf.py b/src/emcee/backends/hdf.py
index d4e6d6c..9503512 100644
--- a/src/emcee/backends/hdf.py
+++ b/src/emcee/backends/hdf.py
@@ -2,7 +2,7 @@
from __future__ import division, print_function
-__all__ = ["HDFBackend", "TempHDFBackend"]
+__all__ = ["HDFBackend", "TempHDFBackend", "does_hdf5_support_longdouble"]
import os
from tempfile import NamedTemporaryFile
@@ -19,6 +19,25 @@ except ImportError:
h5py = None
+def does_hdf5_support_longdouble():
+ if h5py is None:
+ return False
+ with NamedTemporaryFile(prefix="emcee-temporary-hdf5",
+ suffix=".hdf5",
+ delete=False) as f:
+ f.close()
+
+ with h5py.File(f.name, "w") as hf:
+ g = hf.create_group("group")
+ g.create_dataset("data", data=np.ones(1, dtype=np.longdouble))
+ if g["data"].dtype != np.longdouble:
+ return False
+ with h5py.File(f.name, "r") as hf:
+ if hf["group"]["data"].dtype != np.longdouble:
+ return False
+ return True
+
+
class HDFBackend(Backend):
"""A backend that stores the chain in an HDF5 file using h5py
diff --git a/tox.ini b/tox.ini
index 6c09ae3..9f72a99 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = py{36,37}
+envlist = py{36,37,38}
[testenv]
description = Unit tests
| dfm/emcee | c14b212964cfc1543c41f0bd186cafb399e847f7 | diff --git a/src/emcee/tests/integration/test_longdouble.py b/src/emcee/tests/integration/test_longdouble.py
index a2142d5..b8d2c7a 100644
--- a/src/emcee/tests/integration/test_longdouble.py
+++ b/src/emcee/tests/integration/test_longdouble.py
@@ -2,6 +2,7 @@ import numpy as np
import pytest
import emcee
+from emcee.backends.hdf import does_hdf5_support_longdouble, TempHDFBackend
def test_longdouble_doesnt_crash_bug_312():
@@ -17,9 +18,11 @@ def test_longdouble_doesnt_crash_bug_312():
sampler.run_mcmc(p0, 100)
-@pytest.mark.parametrize("cls", [emcee.backends.Backend,
- emcee.backends.TempHDFBackend])
+@pytest.mark.parametrize("cls", emcee.backends.get_test_backends())
def test_longdouble_actually_needed(cls):
+ if (issubclass(cls, TempHDFBackend)
+ and not does_hdf5_support_longdouble()):
+ pytest.xfail("HDF5 does not support long double on this platform")
mjd = np.longdouble(58000.)
sigma = 100*np.finfo(np.longdouble).eps*mjd
diff --git a/src/emcee/tests/unit/test_backends.py b/src/emcee/tests/unit/test_backends.py
index e5466ec..370008e 100644
--- a/src/emcee/tests/unit/test_backends.py
+++ b/src/emcee/tests/unit/test_backends.py
@@ -2,12 +2,18 @@
import os
from itertools import product
+from tempfile import NamedTemporaryFile
-import h5py
import numpy as np
import pytest
from emcee import EnsembleSampler, backends, State
+from emcee.backends.hdf import does_hdf5_support_longdouble
+
+try:
+ import h5py
+except ImportError:
+ h5py = None
__all__ = ["test_backend", "test_reload"]
@@ -55,6 +61,7 @@ def _custom_allclose(a, b):
assert np.allclose(a[n], b[n])
+@pytest.mark.skipif(h5py is None, reason="HDF5 not available")
def test_uninit(tmpdir):
fn = str(tmpdir.join("EMCEE_TEST_FILE_DO_NOT_USE.h5"))
if os.path.exists(fn):
@@ -208,6 +215,7 @@ def test_restart(backend, dtype):
assert np.allclose(a, b), "inconsistent acceptance fraction"
+@pytest.mark.skipif(h5py is None, reason="HDF5 not available")
def test_multi_hdf5():
with backends.TempHDFBackend() as backend1:
run_sampler(backend1)
@@ -227,6 +235,9 @@ def test_multi_hdf5():
@pytest.mark.parametrize("backend", all_backends)
def test_longdouble_preserved(backend):
+ if (issubclass(backend, backends.TempHDFBackend)
+ and not does_hdf5_support_longdouble()):
+ pytest.xfail("HDF5 does not support long double on this platform")
nwalkers = 10
ndim = 2
nsteps = 5
@@ -252,14 +263,3 @@ def test_longdouble_preserved(backend):
assert s.log_prob.dtype == np.longdouble
assert np.all(s.log_prob == lp)
-
-
-def test_hdf5_dtypes():
- nwalkers = 10
- ndim = 2
- with backends.TempHDFBackend(dtype=np.longdouble) as b:
- assert b.dtype == np.longdouble
- b.reset(nwalkers, ndim)
- with h5py.File(b.filename, "r") as f:
- g = f["test"]
- assert g["chain"].dtype == np.longdouble
| long double tests fail on ppc64el
**General information:**
- emcee version: 3.0.2
- platform: ppc64el
- installation method (pip/conda/source/other?): Ubuntu/Debian package
**Problem description:**
Version 3.0.2 of emcee is not migrating to the release pocket of Ubuntu because tests are failing on ppc64el: https://autopkgtest.ubuntu.com/packages/e/emcee/groovy/ppc64el
### Expected behavior
tests pass
### Actual behavior:
test_longdouble_actually_needed[TempHDFBackend] and test_longdouble_preserved[TempHDFBackend] fail:
```
_______________ test_longdouble_actually_needed[TempHDFBackend] ________________
cls = <class 'emcee.backends.hdf.TempHDFBackend'>
@pytest.mark.parametrize("cls", [emcee.backends.Backend,
emcee.backends.TempHDFBackend])
def test_longdouble_actually_needed(cls):
mjd = np.longdouble(58000.)
sigma = 100*np.finfo(np.longdouble).eps*mjd
def log_prob(x):
assert x.dtype == np.longdouble
return -0.5 * np.sum(((x-mjd)/sigma) ** 2)
ndim, nwalkers = 1, 20
steps = 1000
p0 = sigma*np.random.randn(nwalkers, ndim).astype(np.longdouble) + mjd
assert not all(p0 == mjd)
with cls(dtype=np.longdouble) as backend:
sampler = emcee.EnsembleSampler(nwalkers,
ndim,
log_prob,
backend=backend)
sampler.run_mcmc(p0, steps)
samples = sampler.get_chain().reshape((-1,))
> assert samples.dtype == np.longdouble
E AssertionError: assert dtype('<f8') == <class 'numpy.float128'>
E + where dtype('<f8') = array([ 5.80000000e+04, -4.60105223e-27, 5.80000000e+04, ...,\n -6.24580733e-26, 5.80000000e+04, -7.38930048e-27]).dtype
E + and <class 'numpy.float128'> = np.longdouble
```
(the other failure is similar)
### What have you tried so far?
Googling and getting a headache :)
I know that "long double" on PowerPC / POWER is a strange pair-of-64-bit-doubles type so I'm not surprised that it's on POWER that I see the problem. I also see from searching that hd5/h5py/numpy have a history of problems in this area (e.g. https://github.com/h5py/h5py/issues/817) so I'm not sure what the resolution should be. Skipping these tests on ppc64el for now (maybe in an Ubuntu specific patch) might make sense -- it's not like the failure of these new tests indicates any kind of regression. | 0.0 | [
"src/emcee/tests/integration/test_longdouble.py::test_longdouble_actually_needed[Backend]",
"src/emcee/tests/unit/test_backends.py::test_longdouble_preserved[Backend]"
] | [] | 2020-08-18 14:48:36+00:00 | 1,899 |
|
dfm__emcee-386 | diff --git a/src/emcee/ensemble.py b/src/emcee/ensemble.py
index 45cc4ba..24faba3 100644
--- a/src/emcee/ensemble.py
+++ b/src/emcee/ensemble.py
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
import warnings
+from itertools import count
+from typing import Dict, List, Optional, Union
import numpy as np
-from itertools import count
from .backends import Backend
from .model import Model
@@ -61,6 +62,10 @@ class EnsembleSampler(object):
to accept a list of position vectors instead of just one. Note
that ``pool`` will be ignored if this is ``True``.
(default: ``False``)
+ parameter_names (Optional[Union[List[str], Dict[str, List[int]]]]):
+ names of individual parameters or groups of parameters. If
+ specified, the ``log_prob_fn`` will recieve a dictionary of
+ parameters, rather than a ``np.ndarray``.
"""
@@ -76,6 +81,7 @@ class EnsembleSampler(object):
backend=None,
vectorize=False,
blobs_dtype=None,
+ parameter_names: Optional[Union[Dict[str, int], List[str]]] = None,
# Deprecated...
a=None,
postargs=None,
@@ -157,6 +163,49 @@ class EnsembleSampler(object):
# ``args`` and ``kwargs`` pickleable.
self.log_prob_fn = _FunctionWrapper(log_prob_fn, args, kwargs)
+ # Save the parameter names
+ self.params_are_named: bool = parameter_names is not None
+ if self.params_are_named:
+ assert isinstance(parameter_names, (list, dict))
+
+ # Don't support vectorizing yet
+ msg = "named parameters with vectorization unsupported for now"
+ assert not self.vectorize, msg
+
+ # Check for duplicate names
+ dupes = set()
+ uniq = []
+ for name in parameter_names:
+ if name not in dupes:
+ uniq.append(name)
+ dupes.add(name)
+ msg = f"duplicate paramters: {dupes}"
+ assert len(uniq) == len(parameter_names), msg
+
+ if isinstance(parameter_names, list):
+ # Check for all named
+ msg = "name all parameters or set `parameter_names` to `None`"
+ assert len(parameter_names) == ndim, msg
+ # Convert a list to a dict
+ parameter_names: Dict[str, int] = {
+ name: i for i, name in enumerate(parameter_names)
+ }
+
+ # Check not too many names
+ msg = "too many names"
+ assert len(parameter_names) <= ndim, msg
+
+ # Check all indices appear
+ values = [
+ v if isinstance(v, list) else [v]
+ for v in parameter_names.values()
+ ]
+ values = [item for sublist in values for item in sublist]
+ values = set(values)
+ msg = f"not all values appear -- set should be 0 to {ndim-1}"
+ assert values == set(np.arange(ndim)), msg
+ self.parameter_names = parameter_names
+
@property
def random_state(self):
"""
@@ -251,8 +300,9 @@ class EnsembleSampler(object):
raise ValueError("'store' must be False when 'iterations' is None")
# Interpret the input as a walker state and check the dimensions.
state = State(initial_state, copy=True)
- if np.shape(state.coords) != (self.nwalkers, self.ndim):
- raise ValueError("incompatible input dimensions")
+ state_shape = np.shape(state.coords)
+ if state_shape != (self.nwalkers, self.ndim):
+ raise ValueError(f"incompatible input dimensions {state_shape}")
if (not skip_initial_state_check) and (
not walkers_independent(state.coords)
):
@@ -416,6 +466,10 @@ class EnsembleSampler(object):
if np.any(np.isnan(p)):
raise ValueError("At least one parameter value was NaN")
+ # If the parmaeters are named, then switch to dictionaries
+ if self.params_are_named:
+ p = ndarray_to_list_of_dicts(p, self.parameter_names)
+
# Run the log-probability calculations (optionally in parallel).
if self.vectorize:
results = self.log_prob_fn(p)
@@ -427,9 +481,7 @@ class EnsembleSampler(object):
map_func = self.pool.map
else:
map_func = map
- results = list(
- map_func(self.log_prob_fn, (p[i] for i in range(len(p))))
- )
+ results = list(map_func(self.log_prob_fn, p))
try:
log_prob = np.array([float(l[0]) for l in results])
@@ -444,8 +496,9 @@ class EnsembleSampler(object):
else:
try:
with warnings.catch_warnings(record=True):
- warnings.simplefilter("error",
- np.VisibleDeprecationWarning)
+ warnings.simplefilter(
+ "error", np.VisibleDeprecationWarning
+ )
try:
dt = np.atleast_1d(blob[0]).dtype
except Warning:
@@ -455,7 +508,8 @@ class EnsembleSampler(object):
"placed in an object array. Numpy has "
"deprecated this automatic detection, so "
"please specify "
- "blobs_dtype=np.dtype('object')")
+ "blobs_dtype=np.dtype('object')"
+ )
dt = np.dtype("object")
except ValueError:
dt = np.dtype("object")
@@ -557,8 +611,8 @@ class _FunctionWrapper(object):
def __init__(self, f, args, kwargs):
self.f = f
- self.args = [] if args is None else args
- self.kwargs = {} if kwargs is None else kwargs
+ self.args = args or []
+ self.kwargs = kwargs or {}
def __call__(self, x):
try:
@@ -605,3 +659,22 @@ def _scaled_cond(a):
return np.inf
c = b / bsum
return np.linalg.cond(c.astype(float))
+
+
+def ndarray_to_list_of_dicts(
+ x: np.ndarray,
+ key_map: Dict[str, Union[int, List[int]]],
+) -> List[Dict[str, Union[np.number, np.ndarray]]]:
+ """
+ A helper function to convert a ``np.ndarray`` into a list
+ of dictionaries of parameters. Used when parameters are named.
+
+ Args:
+ x (np.ndarray): parameter array of shape ``(N, n_dim)``, where
+ ``N`` is an integer
+ key_map (Dict[str, Union[int, List[int]]):
+
+ Returns:
+ list of dictionaries of parameters
+ """
+ return [{key: xi[val] for key, val in key_map.items()} for xi in x]
| dfm/emcee | f0489d74250e2034d76c3a812b9afae74c9ca191 | diff --git a/src/emcee/tests/unit/test_ensemble.py b/src/emcee/tests/unit/test_ensemble.py
new file mode 100644
index 0000000..f6f5ad2
--- /dev/null
+++ b/src/emcee/tests/unit/test_ensemble.py
@@ -0,0 +1,184 @@
+"""
+Unit tests of some functionality in ensemble.py when the parameters are named
+"""
+import string
+from unittest import TestCase
+
+import numpy as np
+import pytest
+
+from emcee.ensemble import EnsembleSampler, ndarray_to_list_of_dicts
+
+
+class TestNP2ListOfDicts(TestCase):
+ def test_ndarray_to_list_of_dicts(self):
+ # Try different numbers of keys
+ for n_keys in [1, 2, 10, 26]:
+ keys = list(string.ascii_lowercase[:n_keys])
+ key_set = set(keys)
+ key_dict = {key: i for i, key in enumerate(keys)}
+ # Try different number of walker/procs
+ for N in [1, 2, 3, 10, 100]:
+ x = np.random.rand(N, n_keys)
+
+ LOD = ndarray_to_list_of_dicts(x, key_dict)
+ assert len(LOD) == N, "need 1 dict per row"
+ for i, dct in enumerate(LOD):
+ assert dct.keys() == key_set, "keys are missing"
+ for j, key in enumerate(keys):
+ assert dct[key] == x[i, j], f"wrong value at {(i, j)}"
+
+
+class TestNamedParameters(TestCase):
+ """
+ Test that a keyword-based log-probability function instead of
+ a positional.
+ """
+
+ # Keyword based lnpdf
+ def lnpdf(self, pars) -> np.float64:
+ mean = pars["mean"]
+ var = pars["var"]
+ if var <= 0:
+ return -np.inf
+ return (
+ -0.5 * ((mean - self.x) ** 2 / var + np.log(2 * np.pi * var)).sum()
+ )
+
+ def lnpdf_mixture(self, pars) -> np.float64:
+ mean1 = pars["mean1"]
+ var1 = pars["var1"]
+ mean2 = pars["mean2"]
+ var2 = pars["var2"]
+ if var1 <= 0 or var2 <= 0:
+ return -np.inf
+ return (
+ -0.5
+ * (
+ (mean1 - self.x) ** 2 / var1
+ + np.log(2 * np.pi * var1)
+ + (mean2 - self.x - 3) ** 2 / var2
+ + np.log(2 * np.pi * var2)
+ ).sum()
+ )
+
+ def lnpdf_mixture_grouped(self, pars) -> np.float64:
+ mean1, mean2 = pars["means"]
+ var1, var2 = pars["vars"]
+ const = pars["constant"]
+ if var1 <= 0 or var2 <= 0:
+ return -np.inf
+ return (
+ -0.5
+ * (
+ (mean1 - self.x) ** 2 / var1
+ + np.log(2 * np.pi * var1)
+ + (mean2 - self.x - 3) ** 2 / var2
+ + np.log(2 * np.pi * var2)
+ ).sum()
+ + const
+ )
+
+ def setUp(self):
+ # Draw some data from a unit Gaussian
+ self.x = np.random.randn(100)
+ self.names = ["mean", "var"]
+
+ def test_named_parameters(self):
+ sampler = EnsembleSampler(
+ nwalkers=10,
+ ndim=len(self.names),
+ log_prob_fn=self.lnpdf,
+ parameter_names=self.names,
+ )
+ assert sampler.params_are_named
+ assert list(sampler.parameter_names.keys()) == self.names
+
+ def test_asserts(self):
+ # ndim name mismatch
+ with pytest.raises(AssertionError):
+ _ = EnsembleSampler(
+ nwalkers=10,
+ ndim=len(self.names) - 1,
+ log_prob_fn=self.lnpdf,
+ parameter_names=self.names,
+ )
+
+ # duplicate names
+ with pytest.raises(AssertionError):
+ _ = EnsembleSampler(
+ nwalkers=10,
+ ndim=3,
+ log_prob_fn=self.lnpdf,
+ parameter_names=["a", "b", "a"],
+ )
+
+ # vectorize turned on
+ with pytest.raises(AssertionError):
+ _ = EnsembleSampler(
+ nwalkers=10,
+ ndim=len(self.names),
+ log_prob_fn=self.lnpdf,
+ parameter_names=self.names,
+ vectorize=True,
+ )
+
+ def test_compute_log_prob(self):
+ # Try different numbers of walkers
+ for N in [4, 8, 10]:
+ sampler = EnsembleSampler(
+ nwalkers=N,
+ ndim=len(self.names),
+ log_prob_fn=self.lnpdf,
+ parameter_names=self.names,
+ )
+ coords = np.random.rand(N, len(self.names))
+ lnps, _ = sampler.compute_log_prob(coords)
+ assert len(lnps) == N
+ assert lnps.dtype == np.float64
+
+ def test_compute_log_prob_mixture(self):
+ names = ["mean1", "var1", "mean2", "var2"]
+ # Try different numbers of walkers
+ for N in [8, 10, 20]:
+ sampler = EnsembleSampler(
+ nwalkers=N,
+ ndim=len(names),
+ log_prob_fn=self.lnpdf_mixture,
+ parameter_names=names,
+ )
+ coords = np.random.rand(N, len(names))
+ lnps, _ = sampler.compute_log_prob(coords)
+ assert len(lnps) == N
+ assert lnps.dtype == np.float64
+
+ def test_compute_log_prob_mixture_grouped(self):
+ names = {"means": [0, 1], "vars": [2, 3], "constant": 4}
+ # Try different numbers of walkers
+ for N in [8, 10, 20]:
+ sampler = EnsembleSampler(
+ nwalkers=N,
+ ndim=5,
+ log_prob_fn=self.lnpdf_mixture_grouped,
+ parameter_names=names,
+ )
+ coords = np.random.rand(N, 5)
+ lnps, _ = sampler.compute_log_prob(coords)
+ assert len(lnps) == N
+ assert lnps.dtype == np.float64
+
+ def test_run_mcmc(self):
+ # Sort of an integration test
+ n_walkers = 4
+ sampler = EnsembleSampler(
+ nwalkers=n_walkers,
+ ndim=len(self.names),
+ log_prob_fn=self.lnpdf,
+ parameter_names=self.names,
+ )
+ guess = np.random.rand(n_walkers, len(self.names))
+ n_steps = 50
+ results = sampler.run_mcmc(guess, n_steps)
+ assert results.coords.shape == (n_walkers, len(self.names))
+ chain = sampler.chain
+ assert chain.shape == (n_walkers, n_steps, len(self.names))
| [ENH] support for dictionaries and/or namedtuples
## Proposal
The sampler API shares a lot of features with `scipy.optimize.minimize` -- given a model that can be typed as `Callable(List,...)` keep proposing samples to improve the model. This is fine for many problems, but one can imagine a scenario where it would be useful for model developers to handle samples with more than just a `List`. Handling parameters in a `List` means that writing a posterior *requires defining parameters positionally*. In contrast, in packages like pytorch one can refer to model parameters by name (eg. a `torch.nn.Linear` has a `weight` and `bias` named parameters).
This issue proposes enhancing the emcee API to allow for dictionary and/or namedtuple parameter constructs. Looking at the API for the `EnsembleSampler`, this would require an additional constructor argument, since the sampler does not inspect the state of the `log_prob_fn`.
Here is a minimum proposed implementation for supporting a dictionary:
```python
class EnsembleSampler(object):
def __init__(
self,
nwalkers: int,
ndim: int,
log_prob_fn: Callable(Union[List, Dict]),
parameter_names: Optional[List[str]] = None,
...
):
...
# Save the names
self.parameter_names = parameter_names
self.name_parameters: bool = parameter_names is not None
if self.name_parameters:
assert len(parameter_names) == ndim, f"names must match dimensions"
...
def sample(...):
...
with get_progress_bar(progress, total) as pbar:
i = 0
for _ in count() if iterations is None else range(iterations):
for _ in range(yield_step):
...
# If our parameters are named, return them in a named format
if self.name_parameters:
state = {key: value for key, value in zip(self.parameter_names, state)}
yield state
```
This allows for a lot more flexibility downstream for model developers. As a simple example, consider a model composed of two parts, that each can be updated in a way that doesn't affect the higher level model:
```python
class PartA:
__slots__ = ["param_a"]
param_a: float
def __call__(self):
...
class PartB:
__slots__ = ["param_b"]
param_b: float
def __call__(self):
...
class MyModel:
def __init__(self, a = PartA(), b = PartB()):
self.a = a
self.b = b
def log_likelihood_fn(self, params: Dict[str, float]):
# Update the composed parts of the model
for key in self.a.__slots__:
setattr(self.a, params[key])
for key in self.b.__slots__:
setattr(self.b, params[key])
# Final likelihood uses the results of A and B, but we don't
# care how they are implemented
return f(self.a(), self.b())
```
If this sounds like an attractive feature I would be happy to work on a PR. | 0.0 | [
"src/emcee/tests/unit/test_ensemble.py::TestNP2ListOfDicts::test_ndarray_to_list_of_dicts",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_asserts",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_compute_log_prob",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_compute_log_prob_mixture",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_compute_log_prob_mixture_grouped",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_named_parameters",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_run_mcmc"
] | [] | 2021-04-24 22:21:11+00:00 | 1,900 |
|
dfm__emcee-510 | diff --git a/src/emcee/ensemble.py b/src/emcee/ensemble.py
index 3212099..cfef4a5 100644
--- a/src/emcee/ensemble.py
+++ b/src/emcee/ensemble.py
@@ -489,10 +489,19 @@ class EnsembleSampler(object):
results = list(map_func(self.log_prob_fn, p))
try:
- log_prob = np.array([float(l[0]) for l in results])
- blob = [l[1:] for l in results]
+ # perhaps log_prob_fn returns blobs?
+
+ # deal with the blobs first
+ # if l does not have a len attribute (i.e. not a sequence, no blob)
+ # then a TypeError is raised. However, no error will be raised if
+ # l is a length-1 array, np.array([1.234]). In that case blob
+ # will become an empty list.
+ blob = [l[1:] for l in results if len(l) > 1]
+ if not len(blob):
+ raise IndexError
+ log_prob = np.array([_scalar(l[0]) for l in results])
except (IndexError, TypeError):
- log_prob = np.array([float(l) for l in results])
+ log_prob = np.array([_scalar(l) for l in results])
blob = None
else:
# Get the blobs dtype
@@ -502,7 +511,7 @@ class EnsembleSampler(object):
try:
with warnings.catch_warnings(record=True):
warnings.simplefilter(
- "error", np.VisibleDeprecationWarning
+ "error", np.exceptions.VisibleDeprecationWarning
)
try:
dt = np.atleast_1d(blob[0]).dtype
@@ -682,3 +691,16 @@ def ndarray_to_list_of_dicts(
list of dictionaries of parameters
"""
return [{key: xi[val] for key, val in key_map.items()} for xi in x]
+
+
+def _scalar(fx):
+ # Make sure a value is a true scalar
+ # 1.0, np.float64(1.0), np.array([1.0]), np.array(1.0)
+ if not np.isscalar(fx):
+ try:
+ fx = np.asarray(fx).item()
+ except (TypeError, ValueError) as e:
+ raise ValueError("log_prob_fn should return scalar") from e
+ return float(fx)
+ else:
+ return float(fx)
diff --git a/tox.ini b/tox.ini
index d759fa6..c566174 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,12 +1,12 @@
[tox]
-envlist = py{37,38,39,310}{,-extras},lint
+envlist = py{39,310,311,312}{,-extras},lint
[gh-actions]
python =
- 3.7: py37
- 3.8: py38
- 3.9: py39-extras
+ 3.9: py39
3.10: py310
+ 3.11: py311-extras
+ 3.12: py312
[testenv]
deps = coverage[toml]
| dfm/emcee | b68933df3df80634cf133cab7e92db0458fffe13 | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 3a3dc22..063f0c0 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -16,7 +16,7 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
- python-version: ["3.7", "3.8", "3.9", "3.10"]
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
os: ["ubuntu-latest"]
include:
- python-version: "3.9"
@@ -49,6 +49,30 @@ jobs:
COVERALLS_PARALLEL: true
COVERALLS_FLAG_NAME: ${{ matrix.python-version }}-${{ matrix.os }}
+ leading_edge:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ python-version: ["3.12"]
+ os: ["ubuntu-latest"]
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - name: Setup Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install dependencies
+ run: |
+ python -m pip install -U pip
+ python -m pip install pip install pytest "numpy>=2.0.0rc1"
+ python -m pip install -e.
+ - name: Run tests
+ run: pytest
+
coverage:
needs: tests
runs-on: ubuntu-latest
diff --git a/src/emcee/tests/unit/test_ensemble.py b/src/emcee/tests/unit/test_ensemble.py
index f0568b2..e7981c8 100644
--- a/src/emcee/tests/unit/test_ensemble.py
+++ b/src/emcee/tests/unit/test_ensemble.py
@@ -183,3 +183,37 @@ class TestNamedParameters(TestCase):
assert results.coords.shape == (n_walkers, len(self.names))
chain = sampler.chain
assert chain.shape == (n_walkers, n_steps, len(self.names))
+
+
+class TestLnProbFn(TestCase):
+ # checks that the log_prob_fn can deal with a variety of 'scalar-likes'
+ def lnpdf(self, x):
+ v = np.log(np.sqrt(np.pi) * np.exp(-((x / 2.0) ** 2)))
+ v = float(v[0])
+ assert np.isscalar(v)
+ return v
+
+ def lnpdf_arr1(self, x):
+ v = self.lnpdf(x)
+ return np.array([v])
+
+ def lnpdf_float64(self, x):
+ v = self.lnpdf(x)
+ return np.float64(v)
+
+ def lnpdf_arr0D(self, x):
+ v = self.lnpdf(x)
+ return np.array(v)
+
+ def test_deal_with_scalar_likes(self):
+ rng = np.random.default_rng()
+ fns = [
+ self.lnpdf,
+ self.lnpdf_arr1,
+ self.lnpdf_float64,
+ self.lnpdf_arr0D,
+ ]
+ for fn in fns:
+ init = rng.random((50, 1))
+ sampler = EnsembleSampler(50, 1, fn)
+ _ = sampler.run_mcmc(initial_state=init, nsteps=20)
| Incompatible with numpy 2.0.0rc1
Numpy 2 is around the corner with having its first release candidate: https://pypi.org/project/numpy/2.0.0rc1
`emcee` at least uses `VisibleDeprecationWarning` from numpy that will be removed with numpy 2: https://numpy.org/devdocs/release/2.0.0-notes.html
> Warnings and exceptions present in [numpy.exceptions](https://numpy.org/devdocs/reference/routines.exceptions.html#module-numpy.exceptions) (e.g, [ComplexWarning](https://numpy.org/devdocs/reference/generated/numpy.exceptions.ComplexWarning.html#numpy.exceptions.ComplexWarning), [VisibleDeprecationWarning](https://numpy.org/devdocs/reference/generated/numpy.exceptions.VisibleDeprecationWarning.html#numpy.exceptions.VisibleDeprecationWarning)) are no longer exposed in the main namespace.
So with the release of numpy 2, emcee will run into some troubles. | 0.0 | [
"src/emcee/tests/unit/test_ensemble.py::TestLnProbFn::test_deal_with_scalar_likes"
] | [
"src/emcee/tests/unit/test_ensemble.py::TestNP2ListOfDicts::test_ndarray_to_list_of_dicts",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_asserts",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_compute_log_prob",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_compute_log_prob_mixture",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_compute_log_prob_mixture_grouped",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_named_parameters",
"src/emcee/tests/unit/test_ensemble.py::TestNamedParameters::test_run_mcmc"
] | 2024-04-04 22:01:34+00:00 | 1,901 |
|
dfm__tess-atlas-108 | diff --git a/setup.py b/setup.py
index 0a7c68b..dabe2f7 100644
--- a/setup.py
+++ b/setup.py
@@ -31,15 +31,17 @@ INSTALL_REQUIRES = [
"lightkurve>=2.0.11",
"plotly>=4.9.0",
"arviz>=0.10.0",
- "corner",
+ "corner>=2.2.1",
"pandas",
"jupyter",
"ipykernel",
- "jupytext",
+ "jupytext<1.11,>=1.8", # pinned for jypyter-book
"kaleido",
"aesara-theano-fallback",
"theano-pymc>=1.1.2",
"jupyter-book",
+ "seaborn",
+ "jupyter_client==6.1.12", # pinned beacuse of nbconvert bug https://github.com/jupyter/nbconvert/pull/1549#issuecomment-818734169
]
EXTRA_REQUIRE = {"test": ["pytest>=3.6", "testbook>=0.2.3"]}
EXTRA_REQUIRE["dev"] = EXTRA_REQUIRE["test"] + [
@@ -101,6 +103,7 @@ if __name__ == "__main__":
"run_tois=tess_atlas.notebook_preprocessors.run_tois:main",
"runs_stats_plotter=tess_atlas.analysis.stats_plotter:main",
"make_webpages=tess_atlas.webbuilder.build_pages:main",
+ "make_slurm_job=tess_atlas.batch_job_generator.slurm_job_generator:main",
]
},
)
diff --git a/src/tess_atlas/batch_job_generator/__init__.py b/src/tess_atlas/batch_job_generator/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/src/tess_atlas/batch_job_generator/slurm_job_generator.py b/src/tess_atlas/batch_job_generator/slurm_job_generator.py
new file mode 100644
index 0000000..a1ed5a4
--- /dev/null
+++ b/src/tess_atlas/batch_job_generator/slurm_job_generator.py
@@ -0,0 +1,67 @@
+import argparse
+import os
+import shutil
+from typing import List
+
+import pandas as pd
+
+TEMPLATE_FILE = os.path.join(os.path.dirname(__file__), "slurm_template.sh")
+
+
+def make_slurm_file(outdir: str, toi_numbers: List[int], module_loads: str):
+ with open(TEMPLATE_FILE, "r") as f:
+ file_contents = f.read()
+ outdir = os.path.abspath(outdir)
+ logfile_name = os.path.join(outdir, "toi_slurm_jobs.log")
+ jobfile_name = os.path.join(outdir, "slurm_job.sh")
+ path_to_python = shutil.which("python")
+ path_to_env_activate = path_to_python.replace("python", "activate")
+ file_contents = file_contents.replace(
+ "{{{TOTAL NUM}}}", str(len(toi_numbers) - 1)
+ )
+ file_contents = file_contents.replace("{{{MODULE LOADS}}}", module_loads)
+ file_contents = file_contents.replace("{{{OUTDIR}}}", outdir)
+ file_contents = file_contents.replace(
+ "{{{LOAD ENV}}}", f"source {path_to_env_activate}"
+ )
+ file_contents = file_contents.replace("{{{LOG FILE}}}", logfile_name)
+ toi_str = " ".join([str(toi) for toi in toi_numbers])
+ file_contents = file_contents.replace("{{{TOI NUMBERS}}}", toi_str)
+ with open(jobfile_name, "w") as f:
+ f.write(file_contents)
+ print(f"Jobfile created, to run job: \nsbatch {jobfile_name}")
+
+
+def get_toi_numbers(toi_csv: str):
+ df = pd.read_csv(toi_csv)
+ return list(df.toi_numbers.values)
+
+
+def get_cli_args():
+ parser = argparse.ArgumentParser(
+ description="Create slurm job for analysing TOIs"
+ )
+ parser.add_argument(
+ "--toi_csv",
+ help="CSV with the toi numbers to analyse (csv needs a column with `toi_numbers`)",
+ )
+ parser.add_argument(
+ "--outdir", help="outdir for jobs", default="notebooks"
+ )
+ parser.add_argument(
+ "--module_loads",
+ help="String containing all module loads in one line (each module separated by a space)",
+ )
+ args = parser.parse_args()
+ return args.toi_csv, args.outdir, args.module_loads
+
+
+def main():
+ toi_csv, outdir, module_loads = get_cli_args()
+ os.makedirs(outdir, exist_ok=True)
+ toi_numbers = get_toi_numbers(toi_csv)
+ make_slurm_file(outdir, toi_numbers, module_loads)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/tess_atlas/batch_job_generator/slurm_template.sh b/src/tess_atlas/batch_job_generator/slurm_template.sh
new file mode 100644
index 0000000..250c930
--- /dev/null
+++ b/src/tess_atlas/batch_job_generator/slurm_template.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+#
+#SBATCH --job-name=run_tois
+#SBATCH --output={{{LOG FILE}}}
+#
+#SBATCH --ntasks=1
+#SBATCH --time=300:00
+#SBATCH --mem-per-cpu=500MB
+#
+#SBATCH --array=0-{{{TOTAL NUM}}}
+
+module load {{{MODULE LOADS}}}
+{{{LOAD ENV}}}
+
+
+TOI_NUMBERS=({{{TOI NUMBERS}}})
+
+srun run_toi ${TOI_NUMBERS[$SLURM_ARRAY_TASK_ID]} --outdir {{{OUTDIR}}}
diff --git a/src/tess_atlas/notebook_preprocessors/run_toi.py b/src/tess_atlas/notebook_preprocessors/run_toi.py
index 1f17ba7..a76c4f5 100644
--- a/src/tess_atlas/notebook_preprocessors/run_toi.py
+++ b/src/tess_atlas/notebook_preprocessors/run_toi.py
@@ -87,7 +87,7 @@ def execute_toi_notebook(notebook_filename):
def get_cli_args():
"""Get the TOI number from the CLI and return it"""
- parser = argparse.ArgumentParser(prog="run_toi_in_pool")
+ parser = argparse.ArgumentParser(prog="run_toi")
default_outdir = os.path.join(os.getcwd(), "notebooks")
parser.add_argument(
"toi_number", type=int, help="The TOI number to be analysed (e.g. 103)"
| dfm/tess-atlas | 6274de545082661de3677fb609fa7274f26afb47 | diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index d45d0c3..ca420da 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -26,7 +26,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
- pip install --use-feature=2020-resolver -U -e ".[dev]"
+ pip install -U -e ".[dev]"
# Test the py:light -> ipynb -> py:light round trip conversion
- name: roundtrip conversion test
diff --git a/tests/test_slurm_job_generator.py b/tests/test_slurm_job_generator.py
new file mode 100644
index 0000000..59a582a
--- /dev/null
+++ b/tests/test_slurm_job_generator.py
@@ -0,0 +1,24 @@
+import os
+import unittest
+
+from tess_atlas.batch_job_generator.slurm_job_generator import make_slurm_file
+
+
+class JobgenTest(unittest.TestCase):
+ def setUp(self):
+ self.start_dir = os.getcwd()
+ self.outdir = f"test_jobgen"
+ os.makedirs(self.outdir, exist_ok=True)
+
+ def tearDown(self):
+ import shutil
+
+ if os.path.exists(self.outdir):
+ shutil.rmtree(self.outdir)
+
+ def test_slurmfile(self):
+ make_slurm_file(self.outdir, [100, 101, 102], "module load 1")
+
+
+if __name__ == "__main__":
+ unittest.main()
| Cluster jobs failing to pre-process notebooks: TypeError: 'coroutine' object is not subscriptable | 0.0 | [
"tests/test_slurm_job_generator.py::JobgenTest::test_slurmfile"
] | [] | 2021-10-06 02:54:35+00:00 | 1,902 |
|
dgasmith__opt_einsum-11 | diff --git a/README.md b/README.md
index a792df7..9e4ed20 100644
--- a/README.md
+++ b/README.md
@@ -131,6 +131,35 @@ True
By contracting terms in the correct order we can see that this expression can be computed with N^4 scaling. Even with the overhead of finding the best order or 'path' and small dimensions, opt_einsum is roughly 900 times faster than pure einsum for this expression.
+
+## Reusing paths using ``contract_expression``
+
+If you expect to repeatedly use a particular contraction it can make things simpler and more efficient to not compute the path each time. Instead, supplying ``contract_expression`` with the contraction string and the shapes of the tensors generates a ``ContractExpression`` which can then be repeatedly called with any matching set of arrays. For example:
+
+```python
+>>> my_expr = oe.contract_expression("abc,cd,dbe->ea", (2, 3, 4), (4, 5), (5, 3, 6))
+>>> print(my_expr)
+<ContractExpression> for 'abc,cd,dbe->ea':
+ 1. 'dbe,cd->bce' [GEMM]
+ 2. 'bce,abc->ea' [GEMM]
+```
+
+Now we can call this expression with 3 arrays that match the original shapes without having to compute the path again:
+
+```python
+>>> x, y, z = (np.random.rand(*s) for s in [(2, 3, 4), (4, 5), (5, 3, 6)])
+>>> my_expr(x, y, z)
+array([[ 3.08331541, 4.13708916],
+ [ 2.92793729, 4.57945185],
+ [ 3.55679457, 5.56304115],
+ [ 2.6208398 , 4.39024187],
+ [ 3.66736543, 5.41450334],
+ [ 3.67772272, 5.46727192]])
+```
+
+Note that few checks are performed when calling the expression, and while it will work for a set of arrays with the same ranks as the original shapes but differing sizes, it might no longer be optimal.
+
+
## More details on paths
Finding the optimal order of contraction is not an easy problem and formally scales factorially with respect to the number of terms in the expression. First, lets discuss what a path looks like in opt_einsum:
diff --git a/opt_einsum/__init__.py b/opt_einsum/__init__.py
index 2b3430f..16c844a 100644
--- a/opt_einsum/__init__.py
+++ b/opt_einsum/__init__.py
@@ -1,4 +1,4 @@
-from .contract import contract, contract_path
+from .contract import contract, contract_path, contract_expression
from . import paths
from . import blas
from . import helpers
diff --git a/opt_einsum/contract.py b/opt_einsum/contract.py
index 43b78e9..4efb1a9 100644
--- a/opt_einsum/contract.py
+++ b/opt_einsum/contract.py
@@ -259,7 +259,7 @@ def contract_path(*operands, **kwargs):
def contract(*operands, **kwargs):
"""
contract(subscripts, *operands, out=None, dtype=None, order='K',
- casting='safe', use_blas=False, optimize=True, memory_limit=None)
+ casting='safe', use_blas=True, optimize=True, memory_limit=None)
Evaluates the Einstein summation convention on the operands. A drop in
replacment for NumPy's einsum function that optimizes the order of contraction
@@ -323,14 +323,10 @@ def contract(*operands, **kwargs):
See opt_einsum.contract_path or numpy.einsum
"""
-
- # Grab non-einsum kwargs
optimize_arg = kwargs.pop('optimize', True)
if optimize_arg is True:
optimize_arg = 'greedy'
- use_blas = kwargs.pop('use_blas', True)
-
valid_einsum_kwargs = ['out', 'dtype', 'order', 'casting']
einsum_kwargs = {k: v for (k, v) in kwargs.items() if k in valid_einsum_kwargs}
@@ -338,25 +334,38 @@ def contract(*operands, **kwargs):
if optimize_arg is False:
return np.einsum(*operands, **einsum_kwargs)
- # Make sure all keywords are valid
- valid_contract_kwargs = ['memory_limit', 'use_blas'] + valid_einsum_kwargs
- unknown_kwargs = [k for (k, v) in kwargs.items() if k not in valid_contract_kwargs]
+ # Grab non-einsum kwargs
+ use_blas = kwargs.pop('use_blas', True)
+ memory_limit = kwargs.pop('memory_limit', None)
+ gen_expression = kwargs.pop('gen_expression', False)
+
+ # Make sure remaining keywords are valid for einsum
+ unknown_kwargs = [k for (k, v) in kwargs.items() if k not in valid_einsum_kwargs]
if len(unknown_kwargs):
raise TypeError("Did not understand the following kwargs: %s" % unknown_kwargs)
- # Special handeling if out is specified
- specified_out = False
- out_array = einsum_kwargs.pop('out', None)
- if out_array is not None:
- specified_out = True
+ if gen_expression:
+ full_str = operands[0]
# Build the contraction list and operand
- memory_limit = kwargs.pop('memory_limit', None)
-
operands, contraction_list = contract_path(
*operands, path=optimize_arg, memory_limit=memory_limit, einsum_call=True, use_blas=use_blas)
- handle_out = False
+ # check if performing contraction or just building expression
+ if gen_expression:
+ return ContractExpression(full_str, contraction_list, **einsum_kwargs)
+
+ return _core_contract(operands, contraction_list, **einsum_kwargs)
+
+
+def _core_contract(operands, contraction_list, **einsum_kwargs):
+ """Inner loop used to perform an actual contraction given the output
+ from a ``contract_path(..., einsum_call=True)`` call.
+ """
+
+ # Special handeling if out is specified
+ out_array = einsum_kwargs.pop('out', None)
+ specified_out = out_array is not None
# Start contraction loop
for num, contraction in enumerate(contraction_list):
@@ -366,8 +375,7 @@ def contract(*operands, **kwargs):
tmp_operands.append(operands.pop(x))
# Do we need to deal with the output?
- if specified_out and ((num + 1) == len(contraction_list)):
- handle_out = True
+ handle_out = specified_out and ((num + 1) == len(contraction_list))
# Call tensordot
if blas:
@@ -412,3 +420,104 @@ def contract(*operands, **kwargs):
return out_array
else:
return operands[0]
+
+
+class ContractExpression:
+ """Helper class for storing an explicit ``contraction_list`` which can
+ then be repeatedly called solely with the array arguments.
+ """
+
+ def __init__(self, contraction, contraction_list, **einsum_kwargs):
+ self.contraction = contraction
+ self.contraction_list = contraction_list
+ self.einsum_kwargs = einsum_kwargs
+ self.num_args = len(contraction.split('->')[0].split(','))
+
+ def __call__(self, *arrays, **kwargs):
+ if len(arrays) != self.num_args:
+ raise ValueError("This `ContractExpression` takes exactly %s array arguments "
+ "but received %s." % (self.num_args, len(arrays)))
+
+ out = kwargs.pop('out', None)
+ if kwargs:
+ raise ValueError("The only valid keyword argument to a `ContractExpression` "
+ "call is `out=`. Got: %s." % kwargs)
+
+ try:
+ return _core_contract(list(arrays), self.contraction_list, out=out, **self.einsum_kwargs)
+ except ValueError as err:
+ original_msg = "".join(err.args) if err.args else ""
+ msg = ("Internal error while evaluating `ContractExpression`. Note that few checks are performed"
+ " - the number and rank of the array arguments must match the original expression. "
+ "The internal error was: '%s'" % original_msg, )
+ err.args = msg
+ raise
+
+ def __repr__(self):
+ return "ContractExpression('%s')" % self.contraction
+
+ def __str__(self):
+ s = "<ContractExpression> for '%s':" % self.contraction
+ for i, c in enumerate(self.contraction_list):
+ s += "\n %i. " % (i + 1)
+ s += "'%s'" % c[2] + (" [%s]" % c[-1] if c[-1] else "")
+ if self.einsum_kwargs:
+ s += "\neinsum_kwargs=%s" % self.einsum_kwargs
+ return s
+
+
+class _ShapeOnly(np.ndarray):
+ """Dummy ``numpy.ndarray`` which has a shape only - for generating
+ contract expressions.
+ """
+
+ def __init__(self, shape):
+ self.shape = shape
+
+
+def contract_expression(subscripts, *shapes, **kwargs):
+ """Generate an reusable expression for a given contraction with
+ specific shapes, which can for example be cached.
+
+ Parameters
+ ----------
+ subscripts : str
+ Specifies the subscripts for summation.
+ shapes : sequence of integer tuples
+ Shapes of the arrays to optimize the contraction for.
+ kwargs :
+ Passed on to ``contract_path`` or ``einsum``. See ``contract``.
+
+ Returns
+ -------
+ expr : ContractExpression
+ Callable with signature ``expr(*arrays)`` where the array's shapes
+ should match ``shapes``.
+
+ Notes
+ -----
+ - The `out` keyword argument should be supplied to the generated expression
+ rather than this function.
+ - The generated expression will work with any arrays which have
+ the same rank (number of dimensions) as the original shapes, however, if
+ the actual sizes are different, the expression may no longer be optimal.
+
+ Examples
+ --------
+
+ >>> expr = contract_expression("ab,bc->ac", (3, 4), (4, 5))
+ >>> a, b = np.random.rand(3, 4), np.random.rand(4, 5)
+ >>> c = expr(a, b)
+ >>> np.allclose(c, a @ b)
+ True
+
+ """
+ if not kwargs.get('optimize', True):
+ raise ValueError("Can only generate expressions for optimized contractions.")
+
+ if kwargs.get('out', None) is not None:
+ raise ValueError("`out` should only be specified when calling a `ContractExpression`, not when building it.")
+
+ dummy_arrays = [_ShapeOnly(s) for s in shapes]
+
+ return contract(subscripts, *dummy_arrays, gen_expression=True, **kwargs)
| dgasmith/opt_einsum | fd612f0966a555f8a9783669ad3842f2dbfd1462 | diff --git a/tests/test_contract.py b/tests/test_contract.py
index 016d784..6885522 100644
--- a/tests/test_contract.py
+++ b/tests/test_contract.py
@@ -5,7 +5,7 @@ Tets a series of opt_einsum contraction paths to ensure the results are the same
from __future__ import division, absolute_import, print_function
import numpy as np
-from opt_einsum import contract, contract_path, helpers
+from opt_einsum import contract, contract_path, helpers, contract_expression
import pytest
tests = [
@@ -127,3 +127,73 @@ def test_printing():
ein = contract_path(string, *views)
assert len(ein[1]) == 729
+
+
+@pytest.mark.parametrize("string", tests)
+@pytest.mark.parametrize("optimize", ['greedy', 'optimal'])
+@pytest.mark.parametrize("use_blas", [False, True])
+@pytest.mark.parametrize("out_spec", [False, True])
+def test_contract_expressions(string, optimize, use_blas, out_spec):
+ views = helpers.build_views(string)
+ shapes = [view.shape for view in views]
+ expected = contract(string, *views, optimize=False, use_blas=False)
+
+ expr = contract_expression(
+ string, *shapes, optimize=optimize, use_blas=use_blas)
+
+ if out_spec and ("->" in string) and (string[-2:] != "->"):
+ out, = helpers.build_views(string.split('->')[1])
+ expr(*views, out=out)
+ else:
+ out = expr(*views)
+
+ assert np.allclose(out, expected)
+
+ # check representations
+ assert string in expr.__repr__()
+ assert string in expr.__str__()
+
+
+def test_contract_expression_checks():
+ # check optimize needed
+ with pytest.raises(ValueError):
+ contract_expression("ab,bc->ac", (2, 3), (3, 4), optimize=False)
+
+ # check sizes are still checked
+ with pytest.raises(ValueError):
+ contract_expression("ab,bc->ac", (2, 3), (3, 4), (42, 42))
+
+ # check if out given
+ out = np.empty((2, 4))
+ with pytest.raises(ValueError):
+ contract_expression("ab,bc->ac", (2, 3), (3, 4), out=out)
+
+ # check still get errors when wrong ranks supplied to expression
+ expr = contract_expression("ab,bc->ac", (2, 3), (3, 4))
+
+ # too few arguments
+ with pytest.raises(ValueError) as err:
+ expr(np.random.rand(2, 3))
+ assert "`ContractExpression` takes exactly 2" in str(err)
+
+ # too many arguments
+ with pytest.raises(ValueError) as err:
+ expr(np.random.rand(2, 3), np.random.rand(2, 3), np.random.rand(2, 3))
+ assert "`ContractExpression` takes exactly 2" in str(err)
+
+ # wrong shapes
+ with pytest.raises(ValueError) as err:
+ expr(np.random.rand(2, 3, 4), np.random.rand(3, 4))
+ assert "Internal error while evaluating `ContractExpression`" in str(err)
+ with pytest.raises(ValueError) as err:
+ expr(np.random.rand(2, 4), np.random.rand(3, 4, 5))
+ assert "Internal error while evaluating `ContractExpression`" in str(err)
+ with pytest.raises(ValueError) as err:
+ expr(np.random.rand(2, 3), np.random.rand(3, 4),
+ out=np.random.rand(2, 4, 6))
+ assert "Internal error while evaluating `ContractExpression`" in str(err)
+
+ # should only be able to specify out
+ with pytest.raises(ValueError) as err:
+ expr(np.random.rand(2, 3), np.random.rand(3, 4), order='F')
+ assert "only valid keyword argument to a `ContractExpression`" in str(err)
| reusable einsum expressions
Essentially, I'm using ``opt_einsum`` for some tensor network calculations, and a significant proportion of time is spent in ``contract_path``, even for relatively large sized tensors and pre-calculated paths.
Specifically, a huge number of contractions with the same indices and shapes are performed over and over again and I already cache these using the path from ``contract_path``. However, it seems even with the path supplied, a large amount of time is spent parsing the input, in ``can_blas``, ``parse_einsum_input`` etc.
My suggestion would be something like:
```python
shapes = [(2, 3), (3, 4), (4, 5)]
my_expr = einsum_expression("ab,bc,cd->ad", *shapes)
for _ in many_repeats:
...
x, y, z = (rand(s) for s in shapes)
out = my_expr(x, y, z)
...
```
I.e. it would only accept arrays of the same dimensions (and probably an ``out`` argument) and would otherwise skip all parsing, using a ``contraction_list`` stored within the function.
Anyway, I'm about to knock something up to test for myself, but thought it might be of more general interest. | 0.0 | [
"tests/test_contract.py::test_compare[a,ab,abc->abc]",
"tests/test_contract.py::test_compare[a,b,ab->ab]",
"tests/test_contract.py::test_compare[ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_compare[ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_compare[abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_compare[acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_compare[acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_compare[cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_compare[abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_compare[bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_compare[chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_compare[chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_compare[bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_compare[ab,ab,c->]",
"tests/test_contract.py::test_compare[ab,ab,c->c]",
"tests/test_contract.py::test_compare[ab,ab,cd,cd->]",
"tests/test_contract.py::test_compare[ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_compare[ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_compare[ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_compare[ab,cd,ef->abcdef]",
"tests/test_contract.py::test_compare[ab,cd,ef->acdf]",
"tests/test_contract.py::test_compare[ab,cd,de->abcde]",
"tests/test_contract.py::test_compare[ab,cd,de->be]",
"tests/test_contract.py::test_compare[ab,bcd,cd->abcd]",
"tests/test_contract.py::test_compare[ab,bcd,cd->abd]",
"tests/test_contract.py::test_compare[eb,cb,fb->cef]",
"tests/test_contract.py::test_compare[dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_compare[bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_compare[dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_compare[fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_compare[abcd,ad]",
"tests/test_contract.py::test_compare[ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_compare[baa,dcf,af,cde->be]",
"tests/test_contract.py::test_compare[bd,db,eac->ace]",
"tests/test_contract.py::test_compare[fff,fae,bef,def->abd]",
"tests/test_contract.py::test_compare[efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_compare[ab,ab]",
"tests/test_contract.py::test_compare[ab,ba]",
"tests/test_contract.py::test_compare[abc,abc]",
"tests/test_contract.py::test_compare[abc,bac]",
"tests/test_contract.py::test_compare[abc,cba]",
"tests/test_contract.py::test_compare[ab,bc]",
"tests/test_contract.py::test_compare[ab,cb]",
"tests/test_contract.py::test_compare[ba,bc]",
"tests/test_contract.py::test_compare[ba,cb]",
"tests/test_contract.py::test_compare[abcd,cd]",
"tests/test_contract.py::test_compare[abcd,ab]",
"tests/test_contract.py::test_compare[abcd,cdef]",
"tests/test_contract.py::test_compare[abcd,cdef->feba]",
"tests/test_contract.py::test_compare[abcd,efdc]",
"tests/test_contract.py::test_compare[aab,bc->ac]",
"tests/test_contract.py::test_compare[ab,bcc->ac]",
"tests/test_contract.py::test_compare[aab,bcc->ac]",
"tests/test_contract.py::test_compare[baa,bcc->ac]",
"tests/test_contract.py::test_compare[aab,ccb->ac]",
"tests/test_contract.py::test_compare[aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_compare[ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_compare[bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_compare[bb,ff,be->e]",
"tests/test_contract.py::test_compare[bcb,bb,fc,fff->]",
"tests/test_contract.py::test_compare[fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_compare[afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_compare[adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_compare[bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_compare[dba,ead,cad->bce]",
"tests/test_contract.py::test_compare[aef,fbc,dca->bde]",
"tests/test_contract.py::test_compare_blas[a,ab,abc->abc]",
"tests/test_contract.py::test_compare_blas[a,b,ab->ab]",
"tests/test_contract.py::test_compare_blas[ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_compare_blas[ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_compare_blas[abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_compare_blas[acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_compare_blas[acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_compare_blas[cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_compare_blas[abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_compare_blas[bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_compare_blas[chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_compare_blas[chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_compare_blas[bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_compare_blas[ab,ab,c->]",
"tests/test_contract.py::test_compare_blas[ab,ab,c->c]",
"tests/test_contract.py::test_compare_blas[ab,ab,cd,cd->]",
"tests/test_contract.py::test_compare_blas[ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_compare_blas[ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_compare_blas[ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_compare_blas[ab,cd,ef->abcdef]",
"tests/test_contract.py::test_compare_blas[ab,cd,ef->acdf]",
"tests/test_contract.py::test_compare_blas[ab,cd,de->abcde]",
"tests/test_contract.py::test_compare_blas[ab,cd,de->be]",
"tests/test_contract.py::test_compare_blas[ab,bcd,cd->abcd]",
"tests/test_contract.py::test_compare_blas[ab,bcd,cd->abd]",
"tests/test_contract.py::test_compare_blas[eb,cb,fb->cef]",
"tests/test_contract.py::test_compare_blas[dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_compare_blas[bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_compare_blas[dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_compare_blas[fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_compare_blas[abcd,ad]",
"tests/test_contract.py::test_compare_blas[ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_compare_blas[baa,dcf,af,cde->be]",
"tests/test_contract.py::test_compare_blas[bd,db,eac->ace]",
"tests/test_contract.py::test_compare_blas[fff,fae,bef,def->abd]",
"tests/test_contract.py::test_compare_blas[efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_compare_blas[ab,ab]",
"tests/test_contract.py::test_compare_blas[ab,ba]",
"tests/test_contract.py::test_compare_blas[abc,abc]",
"tests/test_contract.py::test_compare_blas[abc,bac]",
"tests/test_contract.py::test_compare_blas[abc,cba]",
"tests/test_contract.py::test_compare_blas[ab,bc]",
"tests/test_contract.py::test_compare_blas[ab,cb]",
"tests/test_contract.py::test_compare_blas[ba,bc]",
"tests/test_contract.py::test_compare_blas[ba,cb]",
"tests/test_contract.py::test_compare_blas[abcd,cd]",
"tests/test_contract.py::test_compare_blas[abcd,ab]",
"tests/test_contract.py::test_compare_blas[abcd,cdef]",
"tests/test_contract.py::test_compare_blas[abcd,cdef->feba]",
"tests/test_contract.py::test_compare_blas[abcd,efdc]",
"tests/test_contract.py::test_compare_blas[aab,bc->ac]",
"tests/test_contract.py::test_compare_blas[ab,bcc->ac]",
"tests/test_contract.py::test_compare_blas[aab,bcc->ac]",
"tests/test_contract.py::test_compare_blas[baa,bcc->ac]",
"tests/test_contract.py::test_compare_blas[aab,ccb->ac]",
"tests/test_contract.py::test_compare_blas[aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_compare_blas[ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_compare_blas[bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_compare_blas[bb,ff,be->e]",
"tests/test_contract.py::test_compare_blas[bcb,bb,fc,fff->]",
"tests/test_contract.py::test_compare_blas[fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_compare_blas[afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_compare_blas[adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_compare_blas[bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_compare_blas[dba,ead,cad->bce]",
"tests/test_contract.py::test_compare_blas[aef,fbc,dca->bde]",
"tests/test_contract.py::test_printing",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ab]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,ba]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abc,abc]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abc,bac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abc,cba]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,bc]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,cb]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ba,bc]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ba,cb]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[False-False-greedy-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ab]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,ba]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abc,abc]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abc,bac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abc,cba]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,bc]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,cb]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ba,bc]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ba,cb]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[False-False-optimal-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ab]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,ba]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abc,abc]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abc,bac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abc,cba]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,bc]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,cb]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ba,bc]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ba,cb]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[False-True-greedy-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ab]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,ba]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abc,abc]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abc,bac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abc,cba]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,bc]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,cb]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ba,bc]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ba,cb]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[False-True-optimal-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ab]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,ba]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abc,abc]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abc,bac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abc,cba]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,bc]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,cb]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ba,bc]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ba,cb]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[True-False-greedy-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ab]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,ba]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abc,abc]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abc,bac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abc,cba]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,bc]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,cb]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ba,bc]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ba,cb]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[True-False-optimal-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ab]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,ba]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abc,abc]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abc,bac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abc,cba]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,bc]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,cb]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ba,bc]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ba,cb]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[True-True-greedy-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-a,ab,abc->abc]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-a,b,ab->ab]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ea,fb,gc,hd,abcd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ea,fb,abcd,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,ea,fb,gc,hd->efgh]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac0]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-acdf,jbje,gihb,hfac,gfac,gifabc,hfac1]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-cd,bdhe,aidb,hgca,gc,hgibcd,hgac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abhe,hidj,jgba,hiab,gab]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bde,cdh,agdb,hica,ibd,hgicd,hiac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-chd,bde,agbc,hiad,hgc,hgi,hiad]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-chd,bde,agbc,hiad,bdi,cgh,agdb]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bdhe,acad,hiab,agac,hibd]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab,c->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab,c->c]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab,cd,cd->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab,cd,cd->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab,cd,cd->cd]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab,cd,cd,ef,ef->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,cd,ef->abcdef]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,cd,ef->acdf]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,cd,de->abcde]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,cd,de->be]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,bcd,cd->abcd]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,bcd,cd->abd]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-eb,cb,fb->cef]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-dd,fb,be,cdb->cef]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bca,cdb,dbf,afc->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-dcc,fce,ea,dbf->ab]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-fdf,cdd,ccd,afe->ae]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,ad]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ed,fcd,ff,bcf->be]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-baa,dcf,af,cde->be]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bd,db,eac->ace]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-fff,fae,bef,def->abd]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-efc,dbc,acf,fd->abe]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ab]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,ba]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abc,abc]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abc,bac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abc,cba]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,bc]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,cb]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ba,bc]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ba,cb]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,cd]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,ab]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,cdef]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,cdef->feba]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-abcd,efdc]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-aab,bc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-aab,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-baa,bcc->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-aab,ccb->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-aab,fa,df,ecc->bde]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-ecb,fef,bad,ed->ac]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bcf,bbb,fbf,fc->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bb,ff,be->e]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bcb,bb,fc,fff->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-fbb,dfd,fc,fc->]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-afd,ba,cc,dc->bf]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-adb,bc,fa,cfc->d]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-bbd,bda,fc,db->acf]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-dba,ead,cad->bce]",
"tests/test_contract.py::test_contract_expressions[True-True-optimal-aef,fbc,dca->bde]",
"tests/test_contract.py::test_contract_expression_checks"
] | [] | 2017-12-04 01:27:21+00:00 | 1,903 |
|
dgasmith__opt_einsum-141 | diff --git a/opt_einsum/contract.py b/opt_einsum/contract.py
index b837b21..6e7550a 100644
--- a/opt_einsum/contract.py
+++ b/opt_einsum/contract.py
@@ -214,7 +214,7 @@ def contract_path(*operands, **kwargs):
indices = set(input_subscripts.replace(',', ''))
# Get length of each unique dimension and ensure all dimensions are correct
- dimension_dict = {}
+ size_dict = {}
for tnum, term in enumerate(input_list):
sh = input_shps[tnum]
@@ -224,18 +224,18 @@ def contract_path(*operands, **kwargs):
for cnum, char in enumerate(term):
dim = int(sh[cnum])
- if char in dimension_dict:
+ if char in size_dict:
# For broadcasting cases we always want the largest dim size
- if dimension_dict[char] == 1:
- dimension_dict[char] = dim
- elif dim not in (1, dimension_dict[char]):
+ if size_dict[char] == 1:
+ size_dict[char] = dim
+ elif dim not in (1, size_dict[char]):
raise ValueError("Size of label '{}' for operand {} ({}) does not match previous "
- "terms ({}).".format(char, tnum, dimension_dict[char], dim))
+ "terms ({}).".format(char, tnum, size_dict[char], dim))
else:
- dimension_dict[char] = dim
+ size_dict[char] = dim
# Compute size of each input array plus the output array
- size_list = [helpers.compute_size_by_dict(term, dimension_dict) for term in input_list + [output_subscript]]
+ size_list = [helpers.compute_size_by_dict(term, size_dict) for term in input_list + [output_subscript]]
memory_arg = _choose_memory_arg(memory_limit, size_list)
num_ops = len(input_list)
@@ -245,7 +245,7 @@ def contract_path(*operands, **kwargs):
# indices_in_input = input_subscripts.replace(',', '')
inner_product = (sum(len(x) for x in input_sets) - len(indices)) > 0
- naive_cost = helpers.flop_count(indices, inner_product, num_ops, dimension_dict)
+ naive_cost = helpers.flop_count(indices, inner_product, num_ops, size_dict)
# Compute the path
if not isinstance(path_type, (str, paths.PathOptimizer)):
@@ -256,10 +256,10 @@ def contract_path(*operands, **kwargs):
path = [tuple(range(num_ops))]
elif isinstance(path_type, paths.PathOptimizer):
# Custom path optimizer supplied
- path = path_type(input_sets, output_set, dimension_dict, memory_arg)
+ path = path_type(input_sets, output_set, size_dict, memory_arg)
else:
path_optimizer = paths.get_path_fn(path_type)
- path = path_optimizer(input_sets, output_set, dimension_dict, memory_arg)
+ path = path_optimizer(input_sets, output_set, size_dict, memory_arg)
cost_list = []
scale_list = []
@@ -275,10 +275,10 @@ def contract_path(*operands, **kwargs):
out_inds, input_sets, idx_removed, idx_contract = contract_tuple
# Compute cost, scale, and size
- cost = helpers.flop_count(idx_contract, idx_removed, len(contract_inds), dimension_dict)
+ cost = helpers.flop_count(idx_contract, idx_removed, len(contract_inds), size_dict)
cost_list.append(cost)
scale_list.append(len(idx_contract))
- size_list.append(helpers.compute_size_by_dict(out_inds, dimension_dict))
+ size_list.append(helpers.compute_size_by_dict(out_inds, size_dict))
tmp_inputs = [input_list.pop(x) for x in contract_inds]
tmp_shapes = [input_shps.pop(x) for x in contract_inds]
@@ -312,7 +312,7 @@ def contract_path(*operands, **kwargs):
return operands, contraction_list
path_print = PathInfo(contraction_list, input_subscripts, output_subscript, indices, path, scale_list, naive_cost,
- opt_cost, size_list, dimension_dict)
+ opt_cost, size_list, size_dict)
return path, path_print
@@ -393,15 +393,26 @@ def contract(*operands, **kwargs):
- ``'optimal'`` An algorithm that explores all possible ways of
contracting the listed tensors. Scales factorially with the number of
terms in the contraction.
+ - ``'dp'`` A faster (but essentially optimal) algorithm that uses
+ dynamic programming to exhaustively search all contraction paths
+ without outer-products.
+ - ``'greedy'`` An cheap algorithm that heuristically chooses the best
+ pairwise contraction at each step. Scales linearly in the number of
+ terms in the contraction.
+ - ``'random-greedy'`` Run a randomized version of the greedy algorithm
+ 32 times and pick the best path.
+ - ``'random-greedy-128'`` Run a randomized version of the greedy
+ algorithm 128 times and pick the best path.
- ``'branch-all'`` An algorithm like optimal but that restricts itself
to searching 'likely' paths. Still scales factorially.
- ``'branch-2'`` An even more restricted version of 'branch-all' that
only searches the best two options at each step. Scales exponentially
with the number of terms in the contraction.
- - ``'greedy'`` An algorithm that heuristically chooses the best pair
- contraction at each step.
- ``'auto'`` Choose the best of the above algorithms whilst aiming to
keep the path finding time below 1ms.
+ - ``'auto-hq'`` Aim for a high quality contraction, choosing the best
+ of the above algorithms whilst aiming to keep the path finding time
+ below 1sec.
memory_limit : {None, int, 'max_input'} (default: None)
Give the upper bound of the largest intermediate tensor contract will build.
@@ -412,7 +423,7 @@ def contract(*operands, **kwargs):
The default is None. Note that imposing a limit can make contractions
exponentially slower to perform.
- backend : str, optional (default: ``numpy``)
+ backend : str, optional (default: ``auto``)
Which library to use to perform the required ``tensordot``, ``transpose``
and ``einsum`` calls. Should match the types of arrays supplied, See
:func:`contract_expression` for generating expressions which convert
diff --git a/opt_einsum/path_random.py b/opt_einsum/path_random.py
index a49c06c..94b29a8 100644
--- a/opt_einsum/path_random.py
+++ b/opt_einsum/path_random.py
@@ -163,6 +163,8 @@ class RandomOptimizer(paths.PathOptimizer):
raise NotImplementedError
def __call__(self, inputs, output, size_dict, memory_limit):
+ self._check_args_against_first_call(inputs, output, size_dict)
+
# start a timer?
if self.max_time is not None:
t0 = time.time()
diff --git a/opt_einsum/paths.py b/opt_einsum/paths.py
index 4103224..b952bc2 100644
--- a/opt_einsum/paths.py
+++ b/opt_einsum/paths.py
@@ -43,6 +43,19 @@ class PathOptimizer(object):
where ``path`` is a list of int-tuples specifiying a contraction order.
"""
+
+ def _check_args_against_first_call(self, inputs, output, size_dict):
+ """Utility that stateful optimizers can use to ensure they are not
+ called with different contractions across separate runs.
+ """
+ args = (inputs, output, size_dict)
+ if not hasattr(self, '_first_call_args'):
+ # simply set the attribute as currently there is no global PathOptimizer init
+ self._first_call_args = args
+ elif args != self._first_call_args:
+ raise ValueError("The arguments specifiying the contraction that this path optimizer "
+ "instance was called with have changed - try creating a new instance.")
+
def __call__(self, inputs, output, size_dict, memory_limit=None):
raise NotImplementedError
@@ -336,6 +349,7 @@ class BranchBound(PathOptimizer):
>>> optimal(isets, oset, idx_sizes, 5000)
[(0, 2), (0, 1)]
"""
+ self._check_args_against_first_call(inputs, output, size_dict)
inputs = tuple(map(frozenset, inputs))
output = frozenset(output)
| dgasmith/opt_einsum | 95c1c80b081cce3f50b55422511d362e6fe1f0cd | diff --git a/opt_einsum/tests/test_paths.py b/opt_einsum/tests/test_paths.py
index 5105bbe..04769f6 100644
--- a/opt_einsum/tests/test_paths.py
+++ b/opt_einsum/tests/test_paths.py
@@ -299,6 +299,12 @@ def test_custom_random_greedy():
assert path_info.largest_intermediate == optimizer.best['size']
assert path_info.opt_cost == optimizer.best['flops']
+ # check error if we try and reuse the optimizer on a different expression
+ eq, shapes = oe.helpers.rand_equation(10, 4, seed=41)
+ views = list(map(np.ones, shapes))
+ with pytest.raises(ValueError):
+ path, path_info = oe.contract_path(eq, *views, optimize=optimizer)
+
def test_custom_branchbound():
eq, shapes = oe.helpers.rand_equation(8, 4, seed=42)
@@ -320,6 +326,12 @@ def test_custom_branchbound():
assert path_info.largest_intermediate == optimizer.best['size']
assert path_info.opt_cost == optimizer.best['flops']
+ # check error if we try and reuse the optimizer on a different expression
+ eq, shapes = oe.helpers.rand_equation(8, 4, seed=41)
+ views = list(map(np.ones, shapes))
+ with pytest.raises(ValueError):
+ path, path_info = oe.contract_path(eq, *views, optimize=optimizer)
+
@pytest.mark.skipif(sys.version_info < (3, 2), reason="requires python3.2 or higher")
def test_parallel_random_greedy():
| Possible bug in RandomGreedy path
I have found an interesting quirk of the RandomGreedy optimizer that may not have been intended. In my application, I need to repeat two contractions several times. I use the same optimizer to compute the paths in advance and cache the result. If I use RandomGreedy, then I get the wrong shape for the second contraction, which leads me to believe that there's some internal state of RandomGreedy that persists into computing the second path. Below is a MWE.
```python
import torch
import opt_einsum as oe
eqn1 = 'abc,bef,ahi,ehk,uvc,vwf,uxi,wxk->'
eqn2 = 'abd,beg,ahj,ehl,mndo,npgq,mrjs,prlt,uvo,vwq,uxs,wxt->'
shapes1 = [(1, 1, 2), (1, 1, 2), (1, 1, 2), (1, 1, 2),
(1, 1, 2), (1, 1, 2), (1, 1, 2), (1, 1, 2)]
shapes2 = [(1, 1, 2), (1, 1, 2), (1, 1, 2), (1, 1, 2), (1, 1, 2, 2), (1, 1, 2, 2),
(1, 1, 2, 2), (1, 1, 2, 2), (1, 1, 2), (1, 1, 2), (1, 1, 2), (1, 1, 2)]
tens1 = [torch.randn(*sh) for sh in shapes1]
tens2 = [torch.randn(*sh) for sh in shapes2]
for Opt in [oe.DynamicProgramming, oe.RandomGreedy]:
opt = Opt(minimize='flops')
expr1 = oe.contract_expression(eqn1, *[ten.shape for ten in tens1], optimize=opt)
expr2 = oe.contract_expression(eqn2, *[ten.shape for ten in tens2], optimize=opt)
print(expr1(*tens1))
print(expr2(*tens2))
```
The output of this program, using the latest PyPI release, is:
```
tensor(-0.0187)
tensor(0.4303)
tensor(-0.0187)
tensor([[[[[-0.4418]],
[[ 1.2737]]]]])
```
Lines 1 and 3 should match (and do), but so should 2 and 4 (and don't). | 0.0 | [
"opt_einsum/tests/test_paths.py::test_custom_random_greedy",
"opt_einsum/tests/test_paths.py::test_custom_branchbound"
] | [
"opt_einsum/tests/test_paths.py::test_size_by_dict",
"opt_einsum/tests/test_paths.py::test_flop_cost",
"opt_einsum/tests/test_paths.py::test_bad_path_option",
"opt_einsum/tests/test_paths.py::test_explicit_path",
"opt_einsum/tests/test_paths.py::test_path_optimal",
"opt_einsum/tests/test_paths.py::test_path_greedy",
"opt_einsum/tests/test_paths.py::test_memory_paths",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[greedy-eb,cb,fb->cef-order0]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-all-eb,cb,fb->cef-order1]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-2-eb,cb,fb->cef-order2]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[optimal-eb,cb,fb->cef-order3]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[dp-eb,cb,fb->cef-order4]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[greedy-dd,fb,be,cdb->cef-order5]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-all-dd,fb,be,cdb->cef-order6]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-2-dd,fb,be,cdb->cef-order7]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[optimal-dd,fb,be,cdb->cef-order8]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[optimal-dd,fb,be,cdb->cef-order9]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[dp-dd,fb,be,cdb->cef-order10]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[greedy-bca,cdb,dbf,afc->-order11]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-all-bca,cdb,dbf,afc->-order12]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-2-bca,cdb,dbf,afc->-order13]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[optimal-bca,cdb,dbf,afc->-order14]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[dp-bca,cdb,dbf,afc->-order15]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[greedy-dcc,fce,ea,dbf->ab-order16]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-all-dcc,fce,ea,dbf->ab-order17]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[branch-2-dcc,fce,ea,dbf->ab-order18]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[optimal-dcc,fce,ea,dbf->ab-order19]",
"opt_einsum/tests/test_paths.py::test_path_edge_cases[dp-dcc,fce,ea,dbf->ab-order20]",
"opt_einsum/tests/test_paths.py::test_optimal_edge_cases",
"opt_einsum/tests/test_paths.py::test_greedy_edge_cases",
"opt_einsum/tests/test_paths.py::test_dp_edge_cases_dimension_1",
"opt_einsum/tests/test_paths.py::test_dp_edge_cases_all_singlet_indices",
"opt_einsum/tests/test_paths.py::test_custom_dp_can_optimize_for_outer_products",
"opt_einsum/tests/test_paths.py::test_custom_dp_can_optimize_for_size",
"opt_einsum/tests/test_paths.py::test_custom_dp_can_set_cost_cap",
"opt_einsum/tests/test_paths.py::test_can_optimize_outer_products[greedy]",
"opt_einsum/tests/test_paths.py::test_can_optimize_outer_products[branch-2]",
"opt_einsum/tests/test_paths.py::test_can_optimize_outer_products[branch-all]",
"opt_einsum/tests/test_paths.py::test_can_optimize_outer_products[optimal]",
"opt_einsum/tests/test_paths.py::test_can_optimize_outer_products[dp]",
"opt_einsum/tests/test_paths.py::test_large_path[2]",
"opt_einsum/tests/test_paths.py::test_large_path[3]",
"opt_einsum/tests/test_paths.py::test_large_path[26]",
"opt_einsum/tests/test_paths.py::test_large_path[52]",
"opt_einsum/tests/test_paths.py::test_large_path[116]",
"opt_einsum/tests/test_paths.py::test_large_path[300]",
"opt_einsum/tests/test_paths.py::test_parallel_random_greedy",
"opt_einsum/tests/test_paths.py::test_custom_path_optimizer",
"opt_einsum/tests/test_paths.py::test_custom_random_optimizer",
"opt_einsum/tests/test_paths.py::test_optimizer_registration"
] | 2020-05-12 21:47:13+00:00 | 1,904 |
|
dgasmith__opt_einsum-145 | diff --git a/docs/source/backends.rst b/docs/source/backends.rst
index d297b19..7e48678 100644
--- a/docs/source/backends.rst
+++ b/docs/source/backends.rst
@@ -325,3 +325,47 @@ so again just the ``backend`` keyword needs to be supplied:
[-462.52362 , -121.12659 , -67.84769 , 624.5455 ],
[ 5.2839584, 36.44155 , 81.62852 , 703.15784 ]],
dtype=float32)
+
+
+Contracting arbitrary objects
+=============================
+
+There is one more explicit backend that can handle arbitrary arrays of objects,
+so long the *objects themselves* just support multiplication and addition (
+``__mul__`` and ``__add__`` dunder methods respectively). Use it by supplying
+``backend='object'``.
+
+For example, imagine we want to perform a contraction of arrays made up of
+`sympy <www.sympy.org>`_ symbols:
+
+.. code-block:: python
+
+ >>> import opt_einsum as oe
+ >>> import numpy as np
+ >>> import sympy
+
+ >>> # define the symbols
+ >>> a, b, c, d, e, f, g, h, i, j, k, l = [sympy.symbols(oe.get_symbol(i)) for i in range(12)]
+ >>> a * b + c * d
+ ππ+ππ
+
+ >>> # define the tensors (you might explicitly specify ``dtype=object``)
+ >>> X = np.array([[a, b], [c, d]])
+ >>> Y = np.array([[e, f], [g, h]])
+ >>> Z = np.array([[i, j], [k, l]])
+
+ >>> # contract the tensors!
+ >>> oe.contract('uv,vw,wu->u', X, Y, Z, backend='object')
+ array([i*(a*e + b*g) + k*(a*f + b*h), j*(c*e + d*g) + l*(c*f + d*h)],
+ dtype=object)
+
+There are a few things to note here:
+
+* The returned array is a ``numpy.ndarray`` but since it has ``dtype=object``
+ it can really hold *any* python objects
+* We had to explicitly use ``backend='object'``, since :func:`numpy.einsum`
+ would have otherwise been dispatched to, which can't handle ``dtype=object``
+ (though :func:`numpy.tensordot` in fact can)
+* Although an optimized pairwise contraction order is used, the looping in each
+ single contraction is **performed in python so performance will be
+ drastically lower than for numeric dtypes!**
diff --git a/opt_einsum/backends/dispatch.py b/opt_einsum/backends/dispatch.py
index 85a6ceb..f5777ae 100644
--- a/opt_einsum/backends/dispatch.py
+++ b/opt_einsum/backends/dispatch.py
@@ -8,6 +8,7 @@ import importlib
import numpy
+from . import object_arrays
from . import cupy as _cupy
from . import jax as _jax
from . import tensorflow as _tensorflow
@@ -49,6 +50,10 @@ _cached_funcs = {
('tensordot', 'numpy'): numpy.tensordot,
('transpose', 'numpy'): numpy.transpose,
('einsum', 'numpy'): numpy.einsum,
+ # also pre-populate with the arbitrary object backend
+ ('tensordot', 'object'): numpy.tensordot,
+ ('transpose', 'object'): numpy.transpose,
+ ('einsum', 'object'): object_arrays.object_einsum,
}
diff --git a/opt_einsum/backends/object_arrays.py b/opt_einsum/backends/object_arrays.py
new file mode 100644
index 0000000..3b394e1
--- /dev/null
+++ b/opt_einsum/backends/object_arrays.py
@@ -0,0 +1,60 @@
+"""
+Functions for performing contractions with array elements which are objects.
+"""
+
+import numpy as np
+import functools
+import operator
+
+
+def object_einsum(eq, *arrays):
+ """A ``einsum`` implementation for ``numpy`` arrays with object dtype.
+ The loop is performed in python, meaning the objects themselves need
+ only to implement ``__mul__`` and ``__add__`` for the contraction to be
+ computed. This may be useful when, for example, computing expressions of
+ tensors with symbolic elements, but note it will be very slow when compared
+ to ``numpy.einsum`` and numeric data types!
+
+ Parameters
+ ----------
+ eq : str
+ The contraction string, should specify output.
+ arrays : sequence of arrays
+ These can be any indexable arrays as long as addition and
+ multiplication is defined on the elements.
+
+ Returns
+ -------
+ out : numpy.ndarray
+ The output tensor, with ``dtype=object``.
+ """
+
+ # when called by ``opt_einsum`` we will always be given a full eq
+ lhs, output = eq.split('->')
+ inputs = lhs.split(',')
+
+ sizes = {}
+ for term, array in zip(inputs, arrays):
+ for k, d in zip(term, array.shape):
+ sizes[k] = d
+
+ out_size = tuple(sizes[k] for k in output)
+ out = np.empty(out_size, dtype=object)
+
+ inner = tuple(k for k in sizes if k not in output)
+ inner_size = tuple(sizes[k] for k in inner)
+
+ for coo_o in np.ndindex(*out_size):
+
+ coord = dict(zip(output, coo_o))
+
+ def gen_inner_sum():
+ for coo_i in np.ndindex(*inner_size):
+ coord.update(dict(zip(inner, coo_i)))
+ locs = (tuple(coord[k] for k in term) for term in inputs)
+ elements = (array[loc] for array, loc in zip(arrays, locs))
+ yield functools.reduce(operator.mul, elements)
+
+ out[coo_o] = functools.reduce(operator.add, gen_inner_sum())
+
+ return out
| dgasmith/opt_einsum | e88983faeb1221cc802ca8cefe2b425cfebe4880 | diff --git a/opt_einsum/tests/test_backends.py b/opt_einsum/tests/test_backends.py
index 905d2ba..2c05f35 100644
--- a/opt_einsum/tests/test_backends.py
+++ b/opt_einsum/tests/test_backends.py
@@ -431,3 +431,25 @@ def test_auto_backend_custom_array_no_tensordot():
# Shaped is an array-like object defined by opt_einsum - which has no TDOT
assert infer_backend(x) == 'opt_einsum'
assert parse_backend([x], 'auto') == 'numpy'
+
+
+@pytest.mark.parametrize("string", tests)
+def test_object_arrays_backend(string):
+ views = helpers.build_views(string)
+ ein = contract(string, *views, optimize=False, use_blas=False)
+ assert ein.dtype != object
+
+ shps = [v.shape for v in views]
+ expr = contract_expression(string, *shps, optimize=True)
+
+ obj_views = [view.astype(object) for view in views]
+
+ # try raw contract
+ obj_opt = contract(string, *obj_views, backend='object')
+ assert obj_opt.dtype == object
+ assert np.allclose(ein, obj_opt.astype(float))
+
+ # test expression
+ obj_opt = expr(*obj_views, backend='object')
+ assert obj_opt.dtype == object
+ assert np.allclose(ein, obj_opt.astype(float))
| Potential bug (outer tensor product)
This works...:
```python
>>> import mpmath
>>> import numpy
>>> m0 = numpy.eye(2)
>>> opt_einsum.contract('bc,ad->abcd', m0, m0)
array([[[[1., 0.], ...)
```
...but this breaks:
```python
>>> m1 = m0 + mpmath.mpc(0)
>>> opt_einsum.contract('bc,ad->abcd', m1, m1)
Traceback (most recent call last): (...)
TypeError: invalid data type for einsum
```
However, using opt_einsum with mpmath is otherwise OK in principle:
```python
>>> opt_einsum.contract('bc,cd->bd', m1, m1)
array([[mpc(real='1.0', imag='0.0'), mpc(real='0.0', imag='0.0')],
[mpc(real='0.0', imag='0.0'), mpc(real='1.0', imag='0.0')]],
dtype=object)
``` | 0.0 | [
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[ab,bc->ca]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[abc,bcd,dea]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[abc,def->fedcba]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[abc,bcd,df->fa]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[ijk,ikj]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[i,j->ij]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[ijk,k->ij]",
"opt_einsum/tests/test_backends.py::test_object_arrays_backend[AB,BC->CA]"
] | [
"opt_einsum/tests/test_backends.py::test_auto_backend_custom_array_no_tensordot"
] | 2020-07-02 04:12:10+00:00 | 1,905 |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 46