molsysforge 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. molsysforge/__init__.py +3 -0
  2. molsysforge/__main__.py +3 -0
  3. molsysforge/_compat.py +59 -0
  4. molsysforge/acceptance.py +3 -0
  5. molsysforge/api.py +3 -0
  6. molsysforge/archive_transport.py +3 -0
  7. molsysforge/artifacts.py +3 -0
  8. molsysforge/auth.py +3 -0
  9. molsysforge/background.py +7 -0
  10. molsysforge/batch.py +3 -0
  11. molsysforge/build_command.py +3 -0
  12. molsysforge/build_config.py +3 -0
  13. molsysforge/chem/__init__.py +1 -0
  14. molsysforge/chem/conversion_checks.py +126 -0
  15. molsysforge/chem/duplicate_ligand.py +134 -0
  16. molsysforge/chem/fragment_inputs.py +311 -0
  17. molsysforge/chem/fragment_preparation.py +355 -0
  18. molsysforge/chem/fragment_proof.py +353 -0
  19. molsysforge/chem/fragment_terminals.py +104 -0
  20. molsysforge/chem/input_diagnostics.py +161 -0
  21. molsysforge/chem/input_safety.py +147 -0
  22. molsysforge/chem/input_sources.py +358 -0
  23. molsysforge/chem/inputs.py +626 -0
  24. molsysforge/chem/ligand_formats.py +241 -0
  25. molsysforge/chem/ligand_stereo.py +83 -0
  26. molsysforge/chem/lipids.py +18 -0
  27. molsysforge/chem/multicomponent.py +579 -0
  28. molsysforge/chem/pdb_layout.py +49 -0
  29. molsysforge/chem/pdb_normalization.py +269 -0
  30. molsysforge/chem/pdbqt.py +419 -0
  31. molsysforge/chem/pose_validation.py +190 -0
  32. molsysforge/chem/precheck.py +450 -0
  33. molsysforge/chem/preview.py +330 -0
  34. molsysforge/chem/protein_state_proof.py +263 -0
  35. molsysforge/chem/protein_states.py +201 -0
  36. molsysforge/chem/residues.py +62 -0
  37. molsysforge/chem/structure.py +113 -0
  38. molsysforge/chem/structure_inventory.py +128 -0
  39. molsysforge/chem/structure_policy.py +151 -0
  40. molsysforge/chem/terminal_topology.py +115 -0
  41. molsysforge/chem/validation.py +805 -0
  42. molsysforge/cli.py +435 -0
  43. molsysforge/commands/__init__.py +1 -0
  44. molsysforge/commands/_authenticated.py +63 -0
  45. molsysforge/commands/account.py +46 -0
  46. molsysforge/commands/attach.py +2 -0
  47. molsysforge/commands/auth.py +2 -0
  48. molsysforge/commands/batch.py +52 -0
  49. molsysforge/commands/batch_resume.py +2 -0
  50. molsysforge/commands/batch_status.py +2 -0
  51. molsysforge/commands/build.py +12 -0
  52. molsysforge/commands/build_resume.py +2 -0
  53. molsysforge/commands/check.py +41 -0
  54. molsysforge/commands/doctor.py +10 -0
  55. molsysforge/commands/download.py +2 -0
  56. molsysforge/commands/inputs.py +12 -0
  57. molsysforge/commands/inspect.py +10 -0
  58. molsysforge/commands/jobs.py +23 -0
  59. molsysforge/commands/jobs_attach.py +22 -0
  60. molsysforge/commands/jobs_clean.py +8 -0
  61. molsysforge/commands/jobs_export.py +16 -0
  62. molsysforge/commands/jobs_forget.py +8 -0
  63. molsysforge/commands/jobs_list.py +9 -0
  64. molsysforge/commands/jobs_reconcile.py +26 -0
  65. molsysforge/commands/jobs_relink.py +8 -0
  66. molsysforge/commands/jobs_remember.py +8 -0
  67. molsysforge/commands/jobs_report.py +67 -0
  68. molsysforge/commands/jobs_restore.py +8 -0
  69. molsysforge/commands/jobs_resume.py +17 -0
  70. molsysforge/commands/jobs_show.py +2 -0
  71. molsysforge/commands/jobs_status.py +9 -0
  72. molsysforge/commands/jobs_watch.py +16 -0
  73. molsysforge/commands/login.py +39 -0
  74. molsysforge/commands/logout.py +9 -0
  75. molsysforge/commands/plan.py +10 -0
  76. molsysforge/commands/prepare.py +30 -0
  77. molsysforge/commands/preview.py +22 -0
  78. molsysforge/commands/resume.py +2 -0
  79. molsysforge/commands/run.py +2 -0
  80. molsysforge/commands/split.py +9 -0
  81. molsysforge/commands/status.py +2 -0
  82. molsysforge/commands/sweep.py +66 -0
  83. molsysforge/commands/sweep_resume.py +2 -0
  84. molsysforge/commands/sweep_status.py +2 -0
  85. molsysforge/commands/update.py +10 -0
  86. molsysforge/commands/validate.py +63 -0
  87. molsysforge/commands/web_inspect.py +2 -0
  88. molsysforge/commands/web_login.py +44 -0
  89. molsysforge/commands/web_step.py +2 -0
  90. molsysforge/commands/web_upload.py +2 -0
  91. molsysforge/config.py +3 -0
  92. molsysforge/delivery.py +3 -0
  93. molsysforge/doctor.py +3 -0
  94. molsysforge/full_build.py +3 -0
  95. molsysforge/helptext.py +3 -0
  96. molsysforge/http_retry.py +3 -0
  97. molsysforge/i18n.py +3 -0
  98. molsysforge/input_sources.py +3 -0
  99. molsysforge/inputs.py +3 -0
  100. molsysforge/layout.py +3 -0
  101. molsysforge/locales/__init__.py +1 -0
  102. molsysforge/locales/helptext.py +9 -0
  103. molsysforge/locales/i18n.py +1087 -0
  104. molsysforge/locales/transfers.py +13 -0
  105. molsysforge/managed.py +3 -0
  106. molsysforge/multicomponent.py +3 -0
  107. molsysforge/pdb_normalization.py +3 -0
  108. molsysforge/pipeline/__init__.py +1 -0
  109. molsysforge/pipeline/acceptance.py +314 -0
  110. molsysforge/pipeline/archive_transport.py +3 -0
  111. molsysforge/pipeline/artifacts.py +53 -0
  112. molsysforge/pipeline/background.py +211 -0
  113. molsysforge/pipeline/batch.py +885 -0
  114. molsysforge/pipeline/batch_progress.py +153 -0
  115. molsysforge/pipeline/build_command.py +399 -0
  116. molsysforge/pipeline/build_config.py +162 -0
  117. molsysforge/pipeline/checked_inputs.py +531 -0
  118. molsysforge/pipeline/cleanup.py +264 -0
  119. molsysforge/pipeline/config.py +88 -0
  120. molsysforge/pipeline/delivery.py +251 -0
  121. molsysforge/pipeline/fragments.py +490 -0
  122. molsysforge/pipeline/full_build.py +547 -0
  123. molsysforge/pipeline/input_seal.py +43 -0
  124. molsysforge/pipeline/managed.py +613 -0
  125. molsysforge/pipeline/preview.py +119 -0
  126. molsysforge/pipeline/progress.py +3 -0
  127. molsysforge/pipeline/protein_states.py +169 -0
  128. molsysforge/pipeline/sweep.py +545 -0
  129. molsysforge/pipeline/updater.py +274 -0
  130. molsysforge/pipeline/workflow.py +284 -0
  131. molsysforge/pose_validation.py +3 -0
  132. molsysforge/precheck.py +3 -0
  133. molsysforge/presentation/__init__.py +1 -0
  134. molsysforge/presentation/arguments.py +160 -0
  135. molsysforge/presentation/execution.py +107 -0
  136. molsysforge/presentation/notifications.py +27 -0
  137. molsysforge/presentation/parameters.py +82 -0
  138. molsysforge/presentation/progress.py +309 -0
  139. molsysforge/presentation/prompts.py +8 -0
  140. molsysforge/presentation/reporting.py +212 -0
  141. molsysforge/presentation/summaries.py +70 -0
  142. molsysforge/presentation/terminal_output.py +531 -0
  143. molsysforge/preview.py +3 -0
  144. molsysforge/progress.py +3 -0
  145. molsysforge/reconcile.py +3 -0
  146. molsysforge/remote/__init__.py +1 -0
  147. molsysforge/remote/api.py +240 -0
  148. molsysforge/remote/archive_transport.py +140 -0
  149. molsysforge/remote/diagnostics.py +78 -0
  150. molsysforge/remote/fragment_terminals.py +77 -0
  151. molsysforge/remote/http_retry.py +147 -0
  152. molsysforge/remote/protein_states.py +161 -0
  153. molsysforge/remote/reconcile.py +114 -0
  154. molsysforge/remote/sessions.py +455 -0
  155. molsysforge/remote/transfers.py +46 -0
  156. molsysforge/remote/web.py +416 -0
  157. molsysforge/remote/web_state.py +121 -0
  158. molsysforge/reporting.py +3 -0
  159. molsysforge/run_logging.py +3 -0
  160. molsysforge/store/__init__.py +1 -0
  161. molsysforge/store/account_slots.py +114 -0
  162. molsysforge/store/accounts.py +67 -0
  163. molsysforge/store/auth.py +324 -0
  164. molsysforge/store/background.py +7 -0
  165. molsysforge/store/configuration.py +128 -0
  166. molsysforge/store/delivery.py +3 -0
  167. molsysforge/store/diagnostics.py +26 -0
  168. molsysforge/store/discovery.py +161 -0
  169. molsysforge/store/doctor.py +48 -0
  170. molsysforge/store/exclusive_move.py +32 -0
  171. molsysforge/store/execution_evidence.py +70 -0
  172. molsysforge/store/identifiers.py +9 -0
  173. molsysforge/store/indexing.py +19 -0
  174. molsysforge/store/json_records.py +23 -0
  175. molsysforge/store/layout.py +47 -0
  176. molsysforge/store/legacy.py +75 -0
  177. molsysforge/store/lifecycle.py +366 -0
  178. molsysforge/store/local_build.py +66 -0
  179. molsysforge/store/locking.py +49 -0
  180. molsysforge/store/managed.py +3 -0
  181. molsysforge/store/paths.py +135 -0
  182. molsysforge/store/provenance.py +105 -0
  183. molsysforge/store/quarantine.py +200 -0
  184. molsysforge/store/result_files.py +165 -0
  185. molsysforge/store/run_logging.py +27 -0
  186. molsysforge/store/run_manifest.py +20 -0
  187. molsysforge/store/settings.py +232 -0
  188. molsysforge/store/tasks.py +343 -0
  189. molsysforge/store/transfer_state.py +28 -0
  190. molsysforge/store/workers.py +66 -0
  191. molsysforge/structure.py +3 -0
  192. molsysforge/sweep.py +3 -0
  193. molsysforge/terminal_output.py +3 -0
  194. molsysforge/updater.py +3 -0
  195. molsysforge/validation.py +3 -0
  196. molsysforge/web.py +3 -0
  197. molsysforge/web_state.py +3 -0
  198. molsysforge/workflow.py +3 -0
  199. molsysforge-0.9.0.dist-info/METADATA +107 -0
  200. molsysforge-0.9.0.dist-info/RECORD +203 -0
  201. molsysforge-0.9.0.dist-info/WHEEL +4 -0
  202. molsysforge-0.9.0.dist-info/entry_points.txt +3 -0
  203. molsysforge-0.9.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,3 @@
1
+ """Independent CHARMM-GUI API client; no upstream source is vendored."""
2
+
3
+ __version__ = "0.9.0"
@@ -0,0 +1,3 @@
1
+ from .cli import run
2
+
3
+ raise SystemExit(run())
molsysforge/_compat.py ADDED
@@ -0,0 +1,59 @@
1
+ """Explicit legacy Python imports; internal code must use canonical modules.
2
+
3
+ The compatibility registry is not an import hook. It is consulted only when
4
+ an external caller explicitly imports one of the small legacy shim files.
5
+ """
6
+
7
+ from importlib import import_module
8
+ import sys
9
+
10
+ MODULE_ALIASES = {
11
+ 'molsysforge.acceptance': 'molsysforge.pipeline.acceptance',
12
+ 'molsysforge.api': 'molsysforge.remote.api',
13
+ 'molsysforge.archive_transport': 'molsysforge.remote.archive_transport',
14
+ 'molsysforge.artifacts': 'molsysforge.pipeline.artifacts',
15
+ 'molsysforge.auth': 'molsysforge.store.auth',
16
+ 'molsysforge.background': 'molsysforge.pipeline.background',
17
+ 'molsysforge.batch': 'molsysforge.pipeline.batch',
18
+ 'molsysforge.build_command': 'molsysforge.pipeline.build_command',
19
+ 'molsysforge.build_config': 'molsysforge.pipeline.build_config',
20
+ 'molsysforge.config': 'molsysforge.pipeline.config',
21
+ 'molsysforge.delivery': 'molsysforge.pipeline.delivery',
22
+ 'molsysforge.doctor': 'molsysforge.store.doctor',
23
+ 'molsysforge.full_build': 'molsysforge.pipeline.full_build',
24
+ 'molsysforge.helptext': 'molsysforge.locales.helptext',
25
+ 'molsysforge.http_retry': 'molsysforge.remote.http_retry',
26
+ 'molsysforge.i18n': 'molsysforge.locales.i18n',
27
+ 'molsysforge.input_sources': 'molsysforge.chem.input_sources',
28
+ 'molsysforge.inputs': 'molsysforge.chem.inputs',
29
+ 'molsysforge.layout': 'molsysforge.store.layout',
30
+ 'molsysforge.managed': 'molsysforge.pipeline.managed',
31
+ 'molsysforge.multicomponent': 'molsysforge.chem.multicomponent',
32
+ 'molsysforge.pdb_normalization': 'molsysforge.chem.pdb_normalization',
33
+ 'molsysforge.pipeline.archive_transport': 'molsysforge.remote.archive_transport',
34
+ 'molsysforge.pipeline.progress': 'molsysforge.presentation.progress',
35
+ 'molsysforge.pose_validation': 'molsysforge.chem.pose_validation',
36
+ 'molsysforge.precheck': 'molsysforge.chem.precheck',
37
+ 'molsysforge.preview': 'molsysforge.pipeline.preview',
38
+ 'molsysforge.progress': 'molsysforge.presentation.progress',
39
+ 'molsysforge.reconcile': 'molsysforge.remote.reconcile',
40
+ 'molsysforge.reporting': 'molsysforge.presentation.reporting',
41
+ 'molsysforge.run_logging': 'molsysforge.store.run_logging',
42
+ 'molsysforge.store.background': 'molsysforge.pipeline.background',
43
+ 'molsysforge.store.delivery': 'molsysforge.pipeline.delivery',
44
+ 'molsysforge.store.managed': 'molsysforge.pipeline.managed',
45
+ 'molsysforge.structure': 'molsysforge.chem.structure',
46
+ 'molsysforge.sweep': 'molsysforge.pipeline.sweep',
47
+ 'molsysforge.terminal_output': 'molsysforge.presentation.terminal_output',
48
+ 'molsysforge.updater': 'molsysforge.pipeline.updater',
49
+ 'molsysforge.validation': 'molsysforge.chem.validation',
50
+ 'molsysforge.web': 'molsysforge.remote.web',
51
+ 'molsysforge.web_state': 'molsysforge.remote.web_state',
52
+ 'molsysforge.workflow': 'molsysforge.pipeline.workflow',
53
+ }
54
+
55
+
56
+ def install_alias(name):
57
+ module = import_module(MODULE_ALIASES[name])
58
+ sys.modules[name] = module
59
+ return module
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
molsysforge/api.py ADDED
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
molsysforge/auth.py ADDED
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
@@ -0,0 +1,7 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ import sys
3
+ from ._compat import install_alias
4
+ _implementation = install_alias("molsysforge.background" if __name__ == "__main__" else __name__)
5
+
6
+ if __name__ == "__main__":
7
+ sys.exit(_implementation.worker(sys.argv[1], int(sys.argv[2])))
molsysforge/batch.py ADDED
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
@@ -0,0 +1,3 @@
1
+ """Legacy import shim; targets are centralized in _compat.MODULE_ALIASES."""
2
+ from ._compat import install_alias
3
+ install_alias(__name__)
@@ -0,0 +1 @@
1
+ """chem layer."""
@@ -0,0 +1,126 @@
1
+ """Offline comparison gates for research conversion evidence, not a converter.
2
+
3
+ Inputs must be GROMACS-preprocessed topology text. No files, subprocesses or
4
+ network are accessed, and no production modeling route uses these gates yet.
5
+ The return value is locale-independent evidence, not terminal prose.
6
+ """
7
+
8
+ import math
9
+ import re
10
+
11
+
12
+ _TYPE = re.compile(r"[A-Za-z0-9_*+\-]+\Z")
13
+ _MAX_TEXT = 32 * 1024 * 1024
14
+ _MAX_MAPS = 128
15
+ _MAX_CELLS = 65536
16
+
17
+
18
+ def _cmap_records(text):
19
+ if not isinstance(text, str) or len(text) > _MAX_TEXT:
20
+ return None, {"code": "invalid_text"}
21
+ section, pending, records = "", [], {}
22
+ for number, raw in enumerate(text.splitlines(), 1):
23
+ code = raw.split(";", 1)[0].strip()
24
+ if not code:
25
+ continue
26
+ if code.startswith("#"):
27
+ return None, {"code": "unresolved_preprocessor", "line": number}
28
+ if code.startswith("["):
29
+ if pending:
30
+ return None, {"code": "unfinished_record", "line": number}
31
+ match = re.fullmatch(r"\[\s*([A-Za-z0-9_]+)\s*\]", code)
32
+ if match is None:
33
+ return None, {"code": "invalid_section", "line": number}
34
+ section = match[1].lower()
35
+ continue
36
+ if section != "cmaptypes":
37
+ continue
38
+ continued = code.endswith("\\")
39
+ pending.extend(code.rstrip("\\").split())
40
+ if len(pending) > _MAX_CELLS + 8:
41
+ return None, {"code": "oversized_grid", "line": number}
42
+ if continued:
43
+ continue
44
+ if (len(pending) < 8 or not all(_TYPE.fullmatch(v) for v in pending[:5])
45
+ or pending[5] != "1" or not all(re.fullmatch(r"[0-9]{1,5}", v) for v in pending[6:8])):
46
+ return None, {"code": "invalid_record", "line": number}
47
+ dimensions = tuple(int(v) for v in pending[6:8])
48
+ cells = dimensions[0] * dimensions[1]
49
+ if not all(dimensions) or cells > _MAX_CELLS or len(pending) != cells + 8:
50
+ return None, {"code": "invalid_grid_size", "line": number}
51
+ try:
52
+ values = tuple(float(v) for v in pending[8:])
53
+ except (ValueError, OverflowError):
54
+ return None, {"code": "invalid_grid_value", "line": number}
55
+ if not all(math.isfinite(v) for v in values):
56
+ return None, {"code": "nonfinite_grid_value", "line": number}
57
+ key = tuple(pending[:5])
58
+ if key in records:
59
+ return None, {"code": "duplicate_map", "line": number}
60
+ if len(records) >= _MAX_MAPS:
61
+ return None, {"code": "too_many_maps", "line": number}
62
+ records[key] = (dimensions, values)
63
+ pending = []
64
+ if pending:
65
+ return None, {"code": "unfinished_record"}
66
+ if not records:
67
+ return None, {"code": "no_cmap_parameters"}
68
+ return records, None
69
+
70
+
71
+ def compare_cmap_parameters(reference, candidate, *, relative_tolerance=1e-7, absolute_tolerance=1e-8):
72
+ """Compare every full-precision CMAP cell at its original ordered position.
73
+
74
+ Never sort grid values, transpose surfaces, reverse type keys or accept
75
+ matching sampled energies in place of matching parameters. Error locations
76
+ are bounded numeric/type metadata; raw topology lines are never reflected.
77
+ This proves only CMAP equality, not topology, restraint or energy equivalence.
78
+ """
79
+ if (not isinstance(relative_tolerance, (int, float)) or isinstance(relative_tolerance, bool)
80
+ or not isinstance(absolute_tolerance, (int, float)) or isinstance(absolute_tolerance, bool)
81
+ or relative_tolerance < 0 or absolute_tolerance < 0):
82
+ return {"passed": False, "error": {"code": "invalid_tolerance"}}
83
+ try:
84
+ relative_tolerance, absolute_tolerance = float(relative_tolerance), float(absolute_tolerance)
85
+ except (ValueError, OverflowError):
86
+ return {"passed": False, "error": {"code": "invalid_tolerance"}}
87
+ if not math.isfinite(relative_tolerance) or not math.isfinite(absolute_tolerance):
88
+ return {"passed": False, "error": {"code": "invalid_tolerance"}}
89
+ a, error = _cmap_records(reference)
90
+ if error:
91
+ return {"passed": False, "error": {"source": "reference", **error}}
92
+ b, error = _cmap_records(candidate)
93
+ if error:
94
+ return {"passed": False, "error": {"source": "candidate", **error}}
95
+ missing, extra = sorted(set(a) - set(b)), sorted(set(b) - set(a))
96
+ mismatches, checked, max_absolute, examples = 0, 0, 0.0, []
97
+ difference_overflow = False
98
+ for key in sorted(set(a) & set(b)):
99
+ dimensions, values = a[key]
100
+ other_dimensions, other_values = b[key]
101
+ if dimensions != other_dimensions:
102
+ mismatches += 1
103
+ if len(examples) < 8:
104
+ examples.append({"types": list(key), "code": "grid_dimensions_differ"})
105
+ continue
106
+ for index, (x, y) in enumerate(zip(values, other_values)):
107
+ checked += 1
108
+ difference = abs(x - y)
109
+ if math.isfinite(difference):
110
+ max_absolute = max(max_absolute, difference)
111
+ else:
112
+ difference_overflow = True
113
+ if not math.isclose(x, y, rel_tol=relative_tolerance, abs_tol=absolute_tolerance):
114
+ mismatches += 1
115
+ if len(examples) < 8:
116
+ examples.append({"types": list(key), "code": "grid_value_differs",
117
+ "row": index // dimensions[1], "column": index % dimensions[1]})
118
+ return {"passed": not (missing or extra or mismatches), "scope": "ordered_cmap_parameters_only",
119
+ "reference_map_count": len(a), "candidate_map_count": len(b),
120
+ "checked_cells": checked, "mismatches": mismatches,
121
+ "max_absolute_difference": None if difference_overflow else max_absolute,
122
+ **({"difference_overflow": True} if difference_overflow else {}),
123
+ "missing_map_count": len(missing), "extra_map_count": len(extra),
124
+ "missing_maps": [list(v) for v in missing[:8]], "extra_maps": [list(v) for v in extra[:8]],
125
+ "examples": examples, "relative_tolerance": relative_tolerance,
126
+ "absolute_tolerance": absolute_tolerance}
@@ -0,0 +1,134 @@
1
+ """Bounded coordinate-only duplicate-pose diagnostics, never chemistry repair."""
2
+
3
+ from collections import Counter, defaultdict
4
+ import math
5
+ from pathlib import Path
6
+
7
+ from ..store.auth import ToolError
8
+ from .residues import SIDECHAINS, ALIASES, MODIFIED
9
+
10
+ RMSD_LIMIT_A = 0.5
11
+
12
+
13
+ class _DiagnosticLimit(Exception):
14
+ pass
15
+
16
+
17
+ def _cost(left, right):
18
+ return sum((a - b) * (a - b) for a, b in zip(left.xyz, right.xyz))
19
+
20
+
21
+ def _minimum_assignment(costs, budget):
22
+ """Minimum-cost square assignment with an explicit diagnostic work bound."""
23
+ count = len(costs)
24
+ u, v, p, way = [0.] * (count + 1), [0.] * (count + 1), [0] * (count + 1), [0] * (count + 1)
25
+ for row in range(1, count + 1):
26
+ p[0], column = row, 0
27
+ minimum, used = [math.inf] * (count + 1), [False] * (count + 1)
28
+ while True:
29
+ used[column] = True
30
+ active_row, delta, next_column = p[column], math.inf, 0
31
+ for candidate in range(1, count + 1):
32
+ if used[candidate]:
33
+ continue
34
+ budget[0] -= 1
35
+ if budget[0] < 0:
36
+ raise _DiagnosticLimit
37
+ reduced = costs[active_row - 1][candidate - 1] - u[active_row] - v[candidate]
38
+ if reduced < minimum[candidate]:
39
+ minimum[candidate], way[candidate] = reduced, column
40
+ if minimum[candidate] < delta:
41
+ delta, next_column = minimum[candidate], candidate
42
+ for candidate in range(count + 1):
43
+ if used[candidate]:
44
+ u[p[candidate]] += delta
45
+ v[candidate] -= delta
46
+ else:
47
+ minimum[candidate] -= delta
48
+ column = next_column
49
+ if p[column] == 0:
50
+ break
51
+ while column:
52
+ previous = way[column]
53
+ p[column] = p[previous]
54
+ column = previous
55
+ return [(p[column] - 1, column - 1) for column in range(1, count + 1)]
56
+
57
+
58
+ def coordinate_match(reference, observed, budget):
59
+ """Find an element-preserving bijection below the RMSD limit, without fit.
60
+
61
+ The returned value proves a coordinate match, not molecular identity.
62
+ A sorted bijection is sufficient when already below the threshold; otherwise
63
+ minimum-cost assignment is used. No nearest-atom reuse or fitted alignment.
64
+ """
65
+ if not reference or len(reference) != len(observed) or Counter(a.element for a in reference) != Counter(a.element for a in observed):
66
+ return None
67
+ if any(len(atom.xyz) != 3 or not all(math.isfinite(value) for value in atom.xyz) for atom in reference + observed):
68
+ return None
69
+ count = len(reference)
70
+ groups = []
71
+ for element in sorted({a.element for a in reference}):
72
+ left = sorted((i for i, atom in enumerate(reference) if atom.element == element), key=lambda i: reference[i].xyz)
73
+ right = sorted((i for i, atom in enumerate(observed) if atom.element == element), key=lambda i: observed[i].xyz)
74
+ groups.append((left, right))
75
+ mapping = [(a, b) for left, right in groups for a, b in zip(left, right)]
76
+ total = math.fsum(_cost(reference[a], observed[b]) for a, b in mapping)
77
+ if total >= count * RMSD_LIMIT_A ** 2:
78
+ matrix_size = sum(len(left) ** 2 for left, _ in groups)
79
+ budget[0] -= matrix_size
80
+ if budget[0] < 0:
81
+ raise _DiagnosticLimit
82
+ matrices = [[[_cost(reference[a], observed[b]) for b in right] for a in left] for left, right in groups]
83
+ if math.fsum(min(row) for costs in matrices for row in costs) >= count * RMSD_LIMIT_A ** 2:
84
+ return None
85
+ mapping = [(left[a], right[b]) for (left, right), costs in zip(groups, matrices)
86
+ for a, b in _minimum_assignment(costs, budget)]
87
+ total = math.fsum(_cost(reference[a], observed[b]) for a, b in mapping)
88
+ rmsd = math.sqrt(total / count)
89
+ if rmsd >= RMSD_LIMIT_A:
90
+ return None
91
+ return {"rmsd_A": rmsd, "max_displacement_A": max(math.sqrt(_cost(reference[a], observed[b])) for a, b in mapping),
92
+ "heavy_atoms": count, "aligned": False, "chemical_identity_verified": False,
93
+ "scope": "unfitted_element_preserving_heavy_coordinate_bijection",
94
+ "atom_mapping": [{"ligand_index": a + 1, "protein_serial": observed[b].serial, "element": reference[a].element}
95
+ for a, b in sorted(mapping)]}
96
+
97
+
98
+ def enrich_duplicate_diagnostics(error, atoms, ligand, *, input_options=None):
99
+ """Enrich an existing blocking heterogen error; do not change acceptance."""
100
+ if error.key != "input.protein_hetero" or ligand is None or Path(ligand).suffix.lower() not in (".sdf", ".mol", ".mol2"):
101
+ return
102
+ from .inputs import read_ligand
103
+ try:
104
+ molecule = read_ligand(ligand, pose=(input_options or {}).get("ligand_pose"))
105
+ except (ToolError, OSError, ValueError):
106
+ return # Preserve the authoritative protein error if chemistry is unavailable.
107
+ reference = [atom for atom in molecule.atoms if atom.element not in ("H", "D", "T")]
108
+ groups = defaultdict(list)
109
+ for atom in atoms:
110
+ line = atom.line
111
+ if line.startswith("HETATM") and atom.element not in ("H", "D", "T"):
112
+ key = (atom.polymer_block, line[17:21].strip(), line[21:22].strip(), int(line[22:26]), line[26:27].strip(), line[72:76].strip())
113
+ groups[key].append(atom)
114
+ budget, additions = [4_000_000], []
115
+ for detail in error.details:
116
+ if not detail.get("kind") or detail.get("resname") in set(SIDECHAINS) | set(ALIASES) | set(MODIFIED):
117
+ continue
118
+ key = (detail.get("polymer_block", 0), detail["resname"], detail["chain"], detail["resid"], detail["icode"], detail["segment"])
119
+ try:
120
+ match = coordinate_match(reference, groups[key], budget)
121
+ except _DiagnosticLimit:
122
+ additions.append({"key": "input.duplicate_scan_limited", "params": {}})
123
+ break
124
+ if match is None:
125
+ continue
126
+ # Map back from the heavy-only reference to the original SDF indices.
127
+ full_index = {id(atom): index + 1 for index, atom in enumerate(molecule.atoms)}
128
+ for pair in match["atom_mapping"]:
129
+ pair["ligand_index"] = full_index[id(reference[pair["ligand_index"] - 1])]
130
+ match.update(ligand_source=str(Path(ligand).resolve()), selected_pose=molecule.provenance.get("selected_pose", 1))
131
+ detail["matching_ligand_coordinates"] = match
132
+ additions.append({"key": "input.duplicate_ligand_pose", "params": {"residue": detail["params"]["residue"],
133
+ "count": match["heavy_atoms"], "rmsd": f"{match['rmsd_A']:.4f}"}})
134
+ error.details.extend(additions)