petroharness 1.2.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 (246) hide show
  1. petroharness/__init__.py +5 -0
  2. petroharness/agent/__init__.py +0 -0
  3. petroharness/agent/checks.py +379 -0
  4. petroharness/agent/claims.py +461 -0
  5. petroharness/agent/components/C10_reading/absent_note.md +1 -0
  6. petroharness/agent/components/C10_reading/absent_unit_note.md +1 -0
  7. petroharness/agent/components/C10_reading/brief_levels.md +1 -0
  8. petroharness/agent/components/C10_reading/brief_weaknesses.md +1 -0
  9. petroharness/agent/components/C10_reading/component.yaml +13 -0
  10. petroharness/agent/components/C10_reading/empty_note.md +1 -0
  11. petroharness/agent/components/C10_reading/settle_weaknesses.md +2 -0
  12. petroharness/agent/components/C10_reading/zones_left_note.md +1 -0
  13. petroharness/agent/components/C1_system/brief.md +70 -0
  14. petroharness/agent/components/C1_system/brief_direction.md +1 -0
  15. petroharness/agent/components/C1_system/brief_guide.md +3 -0
  16. petroharness/agent/components/C1_system/component.yaml +8 -0
  17. petroharness/agent/components/C2_guardrails/component.yaml +17 -0
  18. petroharness/agent/components/C2_guardrails/fix.md +3 -0
  19. petroharness/agent/components/C2_guardrails/flags.json +16 -0
  20. petroharness/agent/components/C2_guardrails/not_done.md +1 -0
  21. petroharness/agent/components/C2_guardrails/repair_contradictions.md +1 -0
  22. petroharness/agent/components/C2_guardrails/repair_keep.md +1 -0
  23. petroharness/agent/components/C2_guardrails/repair_leaks.md +1 -0
  24. petroharness/agent/components/C2_guardrails/repair_names.md +1 -0
  25. petroharness/agent/components/C2_guardrails/repair_numbers.md +1 -0
  26. petroharness/agent/components/C2_guardrails/repair_words.md +1 -0
  27. petroharness/agent/components/C2_guardrails/skip.md +1 -0
  28. petroharness/agent/components/C3_memory/component.yaml +9 -0
  29. petroharness/agent/components/C3_memory/earlier_head.md +1 -0
  30. petroharness/agent/components/C4_tools/argument_texts.json +15 -0
  31. petroharness/agent/components/C4_tools/basis.md +1 -0
  32. petroharness/agent/components/C4_tools/component.yaml +20 -0
  33. petroharness/agent/components/C4_tools/condition.md +1 -0
  34. petroharness/agent/components/C4_tools/grammar.md +1 -0
  35. petroharness/agent/components/C4_tools/library.md +1 -0
  36. petroharness/agent/components/C4_tools/tool_descriptions.json +32 -0
  37. petroharness/agent/components/C4_tools/zones_argument.md +1 -0
  38. petroharness/agent/components/C5_orchestration/component.yaml +30 -0
  39. petroharness/agent/components/C5_orchestration/direct_step.md +6 -0
  40. petroharness/agent/components/C5_orchestration/points_ask.md +1 -0
  41. petroharness/agent/components/C5_orchestration/points_scope.md +2 -0
  42. petroharness/agent/components/C5_orchestration/read.md +4 -0
  43. petroharness/agent/components/C5_orchestration/read_depth.md +5 -0
  44. petroharness/agent/components/C5_orchestration/read_outside.md +1 -0
  45. petroharness/agent/components/C5_orchestration/read_scope.md +1 -0
  46. petroharness/agent/components/C5_orchestration/read_scope_again.md +1 -0
  47. petroharness/agent/components/C5_orchestration/section_owners.json +29 -0
  48. petroharness/agent/components/C5_orchestration/settle.md +6 -0
  49. petroharness/agent/components/C5_orchestration/settle_lists.json +7 -0
  50. petroharness/agent/components/C5_orchestration/step1.md +10 -0
  51. petroharness/agent/components/C5_orchestration/step1_guide_call.md +1 -0
  52. petroharness/agent/components/C5_orchestration/step1_guides.md +1 -0
  53. petroharness/agent/components/C5_orchestration/step1_later.md +3 -0
  54. petroharness/agent/components/C5_orchestration/step1_reply.md +1 -0
  55. petroharness/agent/components/C5_orchestration/step_last.md +1 -0
  56. petroharness/agent/components/C5_orchestration/step_next.md +1 -0
  57. petroharness/agent/components/C5_orchestration/step_settled_check.md +1 -0
  58. petroharness/agent/components/C6_skills/component.yaml +10 -0
  59. petroharness/agent/components/C6_skills/guide_short.md +1 -0
  60. petroharness/agent/components/C6_skills/guides_head.md +1 -0
  61. petroharness/agent/components/C7_scripts/component.yaml +12 -0
  62. petroharness/agent/components/C7_scripts/one_value.md +1 -0
  63. petroharness/agent/components/C8_middleware/actions_left_out.md +1 -0
  64. petroharness/agent/components/C8_middleware/component.yaml +16 -0
  65. petroharness/agent/components/C8_middleware/done_waits.md +1 -0
  66. petroharness/agent/components/C8_middleware/edits_not_applied.md +1 -0
  67. petroharness/agent/components/C8_middleware/extra_left_out.md +1 -0
  68. petroharness/agent/components/C8_middleware/not_run.md +1 -0
  69. petroharness/agent/components/C8_middleware/not_run_guide.md +1 -0
  70. petroharness/agent/components/C8_middleware/nothing_new.md +1 -0
  71. petroharness/agent/components/C8_middleware/shown_above.md +1 -0
  72. petroharness/agent/components/C8_middleware/withheld.md +1 -0
  73. petroharness/agent/components/C8_middleware/withheld_last.md +1 -0
  74. petroharness/agent/components/C9_answer/ask_did_you_mean.md +1 -0
  75. petroharness/agent/components/C9_answer/ask_left_out.md +1 -0
  76. petroharness/agent/components/C9_answer/ask_listed_twice.md +1 -0
  77. petroharness/agent/components/C9_answer/ask_which_unit.md +1 -0
  78. petroharness/agent/components/C9_answer/aspects_rule.md +1 -0
  79. petroharness/agent/components/C9_answer/brief_direct.md +1 -0
  80. petroharness/agent/components/C9_answer/brief_later.md +1 -0
  81. petroharness/agent/components/C9_answer/component.yaml +25 -0
  82. petroharness/agent/components/C9_answer/figures.md +3 -0
  83. petroharness/agent/components/C9_answer/later_rule.md +1 -0
  84. petroharness/agent/components/C9_answer/outside_examples.json +5 -0
  85. petroharness/agent/components/C9_answer/outside_reply.md +1 -0
  86. petroharness/agent/components/C9_answer/points_rule.md +1 -0
  87. petroharness/agent/components/C9_answer/premise.md +1 -0
  88. petroharness/agent/components/C9_answer/reply_brief.md +8 -0
  89. petroharness/agent/components/C9_answer/scope_rule.md +1 -0
  90. petroharness/agent/components/C9_answer/table_rule.md +1 -0
  91. petroharness/agent/components/C9_answer/write.md +29 -0
  92. petroharness/agent/components/README.md +39 -0
  93. petroharness/agent/components.py +180 -0
  94. petroharness/agent/compose.py +281 -0
  95. petroharness/agent/compute.py +542 -0
  96. petroharness/agent/direction.py +462 -0
  97. petroharness/agent/engine/__init__.py +120 -0
  98. petroharness/agent/engine/base.py +88 -0
  99. petroharness/agent/engine/conditions.py +351 -0
  100. petroharness/agent/engine/curves.py +518 -0
  101. petroharness/agent/engine/measures.py +267 -0
  102. petroharness/agent/engine/output.py +168 -0
  103. petroharness/agent/graph.py +973 -0
  104. petroharness/agent/inventory.py +670 -0
  105. petroharness/agent/ledger.py +607 -0
  106. petroharness/agent/library/__init__.py +74 -0
  107. petroharness/agent/library/api.py +801 -0
  108. petroharness/agent/library/calculate.py +178 -0
  109. petroharness/agent/library/calibrate.py +261 -0
  110. petroharness/agent/library/check.py +271 -0
  111. petroharness/agent/library/classify.py +310 -0
  112. petroharness/agent/library/estimate.py +287 -0
  113. petroharness/agent/library/shared.py +561 -0
  114. petroharness/agent/library/summarize.py +104 -0
  115. petroharness/agent/map.py +267 -0
  116. petroharness/agent/notes.py +181 -0
  117. petroharness/agent/numbers.py +149 -0
  118. petroharness/agent/prompts.py +121 -0
  119. petroharness/agent/read.py +350 -0
  120. petroharness/agent/replies.py +313 -0
  121. petroharness/agent/schemas.py +386 -0
  122. petroharness/agent/selection.py +723 -0
  123. petroharness/agent/settle.py +119 -0
  124. petroharness/agent/state.py +265 -0
  125. petroharness/agent/tools.py +1160 -0
  126. petroharness/agent/toolset.py +258 -0
  127. petroharness/agent/vocabulary.py +171 -0
  128. petroharness/agent/writer.py +541 -0
  129. petroharness/ask.py +349 -0
  130. petroharness/basis.py +56 -0
  131. petroharness/cli.py +183 -0
  132. petroharness/config.py +247 -0
  133. petroharness/core/__init__.py +2 -0
  134. petroharness/core/files.py +16 -0
  135. petroharness/core/setup.py +231 -0
  136. petroharness/evidence/__init__.py +13 -0
  137. petroharness/evidence/audit.py +117 -0
  138. petroharness/evidence/graph.py +224 -0
  139. petroharness/evidence/links.py +44 -0
  140. petroharness/evidence/record.py +91 -0
  141. petroharness/evidence/report.py +95 -0
  142. petroharness/figures.py +562 -0
  143. petroharness/interval.py +352 -0
  144. petroharness/llm.py +212 -0
  145. petroharness/models.py +81 -0
  146. petroharness/options.py +79 -0
  147. petroharness/profile.py +29 -0
  148. petroharness/py.typed +0 -0
  149. petroharness/record/__init__.py +1 -0
  150. petroharness/record/analyzers.py +185 -0
  151. petroharness/record/card.py +731 -0
  152. petroharness/record/catalog.py +1311 -0
  153. petroharness/record/params.py +8 -0
  154. petroharness/record/result.py +57 -0
  155. petroharness/record/routes.py +149 -0
  156. petroharness/record/sections.py +204 -0
  157. petroharness/record/store.py +37 -0
  158. petroharness/registry.py +107 -0
  159. petroharness/resources/models/generic.yaml +13 -0
  160. petroharness/resources/models/k2_horizon_7b.yaml +21 -0
  161. petroharness/resources/policy/reference_v2.yaml +80 -0
  162. petroharness/resources/profiles/report_style.yaml +5 -0
  163. petroharness/resources/rules/catalog.yaml +13 -0
  164. petroharness/resources/rules/checks.yaml +90 -0
  165. petroharness/resources/rules/curves.yaml +319 -0
  166. petroharness/resources/rules/judgements.yaml +6 -0
  167. petroharness/resources/rules/relations.yaml +161 -0
  168. petroharness/resources/rules/shapes.yaml +23 -0
  169. petroharness/resources/rules/topics.yaml +92 -0
  170. petroharness/resources/skills/README.md +180 -0
  171. petroharness/resources/skills/researched/answer/SKILL.md +29 -0
  172. petroharness/resources/skills/researched/answer/sources.yaml +26 -0
  173. petroharness/resources/skills/researched/core_log_integration/SKILL.md +62 -0
  174. petroharness/resources/skills/researched/core_log_integration/sources.yaml +147 -0
  175. petroharness/resources/skills/researched/data_quality/SKILL.md +65 -0
  176. petroharness/resources/skills/researched/data_quality/sources.yaml +146 -0
  177. petroharness/resources/skills/researched/elastic_properties/SKILL.md +60 -0
  178. petroharness/resources/skills/researched/elastic_properties/sources.yaml +144 -0
  179. petroharness/resources/skills/researched/fluid_contacts/SKILL.md +62 -0
  180. petroharness/resources/skills/researched/fluid_contacts/sources.yaml +138 -0
  181. petroharness/resources/skills/researched/hydrocarbon_detection/SKILL.md +64 -0
  182. petroharness/resources/skills/researched/hydrocarbon_detection/sources.yaml +158 -0
  183. petroharness/resources/skills/researched/invasion_movability/SKILL.md +66 -0
  184. petroharness/resources/skills/researched/invasion_movability/sources.yaml +156 -0
  185. petroharness/resources/skills/researched/library.yaml +5 -0
  186. petroharness/resources/skills/researched/lithology_mineralogy/SKILL.md +66 -0
  187. petroharness/resources/skills/researched/lithology_mineralogy/sources.yaml +173 -0
  188. petroharness/resources/skills/researched/log_facies_stratigraphy/SKILL.md +62 -0
  189. petroharness/resources/skills/researched/log_facies_stratigraphy/sources.yaml +129 -0
  190. petroharness/resources/skills/researched/net_reservoir_pay/SKILL.md +65 -0
  191. petroharness/resources/skills/researched/net_reservoir_pay/sources.yaml +152 -0
  192. petroharness/resources/skills/researched/permeability_rock_quality/SKILL.md +66 -0
  193. petroharness/resources/skills/researched/permeability_rock_quality/sources.yaml +178 -0
  194. petroharness/resources/skills/researched/porosity/SKILL.md +63 -0
  195. petroharness/resources/skills/researched/porosity/sources.yaml +158 -0
  196. petroharness/resources/skills/researched/refs.yaml +540 -0
  197. petroharness/resources/skills/researched/route/SKILL.md +28 -0
  198. petroharness/resources/skills/researched/route/sources.yaml +19 -0
  199. petroharness/resources/skills/researched/shale_clay/SKILL.md +62 -0
  200. petroharness/resources/skills/researched/shale_clay/sources.yaml +152 -0
  201. petroharness/resources/skills/researched/statistics_data_analysis/SKILL.md +63 -0
  202. petroharness/resources/skills/researched/statistics_data_analysis/sources.yaml +157 -0
  203. petroharness/resources/skills/researched/water_saturation/SKILL.md +65 -0
  204. petroharness/resources/skills/researched/water_saturation/sources.yaml +185 -0
  205. petroharness/resources/topics.yaml +64 -0
  206. petroharness/session/__init__.py +12 -0
  207. petroharness/session/chat.py +201 -0
  208. petroharness/session/conversation.py +509 -0
  209. petroharness/session/earlier.py +150 -0
  210. petroharness/session/graph.py +227 -0
  211. petroharness/session/log.py +48 -0
  212. petroharness/tape.py +272 -0
  213. petroharness/tasks.py +86 -0
  214. petroharness/tools/__init__.py +1 -0
  215. petroharness/tools/spec.py +175 -0
  216. petroharness/ui/__init__.py +4 -0
  217. petroharness/ui/adapter.py +730 -0
  218. petroharness/ui/progress.py +266 -0
  219. petroharness/ui/server.py +721 -0
  220. petroharness/ui/static/img/petroharness_logo.svg +1 -0
  221. petroharness/ui/static/img/petroharness_logo_dark.png +0 -0
  222. petroharness/ui/static/img/petroharness_mark.png +0 -0
  223. petroharness/ui/static/img/petrophys_mark.png +0 -0
  224. petroharness/ui/static/index.html +3692 -0
  225. petroharness/ui/store.py +182 -0
  226. petroharness/ui/wellplot.py +271 -0
  227. petroharness/well/__init__.py +1 -0
  228. petroharness/well/calculations.py +43 -0
  229. petroharness/well/derived.py +50 -0
  230. petroharness/well/formation.py +298 -0
  231. petroharness/well/notes.py +83 -0
  232. petroharness/well/prepare.py +712 -0
  233. petroharness/well/runner.py +119 -0
  234. petroharness/well/settings.py +388 -0
  235. petroharness/well/stats.py +47 -0
  236. petroharness/well/summary.py +591 -0
  237. petroharness/well/tops.py +299 -0
  238. petroharness/well/user_zones.py +60 -0
  239. petroharness/well/view.py +639 -0
  240. petroharness-1.2.0.dist-info/METADATA +467 -0
  241. petroharness-1.2.0.dist-info/RECORD +246 -0
  242. petroharness-1.2.0.dist-info/WHEEL +5 -0
  243. petroharness-1.2.0.dist-info/entry_points.txt +2 -0
  244. petroharness-1.2.0.dist-info/licenses/LICENSE +396 -0
  245. petroharness-1.2.0.dist-info/licenses/THIRD_PARTY_DATA.md +60 -0
  246. petroharness-1.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,5 @@
1
+ """PetroHarness: answers petrophysics questions about an interval of a well from its raw LAS.
2
+ Petrophys calculates; the harness investigates and records; the model (any chat model on an OpenAI-compatible
3
+ endpoint; K2-Horizon-7B by default) interprets and writes."""
4
+
5
+ __version__ = "1.2.0"
File without changes
@@ -0,0 +1,379 @@
1
+ """Deterministic checks of a written answer against the record (numbers traced to evidence, data said missing that the
2
+ interval has, core-calibrated curves said absent or used where there are none), returned as WHAT / WHY / FIX
3
+ messages. They show facts; what the answer concludes is the model's (docs/DESIGN.md, G8). The writer's checker calls
4
+ them (src/petroharness/agent/writer.py)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Iterable, Optional
10
+
11
+ import numpy as np
12
+
13
+ from petroharness.record.catalog import Evidence
14
+ from petroharness.well.view import FormationView
15
+ from petroharness.agent.compose import strip_citations
16
+ from petroharness.agent.engine import ToolError
17
+ from petroharness.agent.ledger import evaluate
18
+
19
+ from petroharness import options
20
+ from petroharness.agent import numbers as N
21
+ from petroharness.agent.numbers import NUM as _NUM, number, shown_values # noqa: F401 (the one grammar)
22
+ _MINUS = str.maketrans({"\u2212": "-", "\ufe63": "-", "\uff0d": "-"}) # typographic minus signs: a model writes -0.42 as \u22120.42
23
+
24
+
25
+ def ascii_minus(text: str) -> str:
26
+ """Typographic minus signs (U+2212 and its variants) as ASCII '-': the number checks read a signed value only
27
+ with an ASCII minus (otherwise \u22120.419 reads as 0.419 and is flagged against a shown -0.419)."""
28
+ return (text or "").translate(_MINUS)
29
+
30
+
31
+ def _allowed_numbers(card: str, evidence: list[Evidence], question: str = "") -> np.ndarray:
32
+ """Numbers the answer may state: the evidence values and every number shown in the pack, the card and the
33
+ question (a threshold or percentile the question states; a percentage there also as a fraction)."""
34
+ vals: list[float] = []
35
+ for e in evidence:
36
+ vals.extend(float(v) for v in e.values if v is not None and np.isfinite(v))
37
+ vals += shown_values(ascii_minus(e.render()))
38
+ vals += shown_values(card)
39
+ for m in _NUM.finditer(question):
40
+ vals.append(number(m.group(1)))
41
+ if m.group(2):
42
+ vals.append(number(m.group(1)) / 100)
43
+ return np.unique(np.asarray(vals, dtype=float))
44
+
45
+
46
+ def _supported(x: float, decimals: int, allowed: np.ndarray, percent: bool) -> bool:
47
+ """x matches an allowed value at x's displayed precision, directly or as a fraction shown in percent; a percentage
48
+ also as the complement of a shown share (100 - p, or 100 x (1 - f): the share that is not), recomputed here."""
49
+ tol = N.tolerance(N.half_of(decimals), x)
50
+ if np.any(np.abs(allowed - x) <= tol):
51
+ return True
52
+ if not percent:
53
+ return False
54
+ frac, pct = allowed[(allowed >= 0) & (allowed <= 1)], allowed[(allowed >= 0) & (allowed <= 100)]
55
+ return bool(np.any(np.abs(allowed * 100 - x) <= tol) # a fraction written as a percentage
56
+ or np.any(np.abs(100 * (1 - frac) - x) <= tol) or np.any(np.abs(100 - pct - x) <= tol))
57
+
58
+
59
+ def _derived(x: float, decimals: int, stated: list[float], percent: bool = True, counts: list = None) -> bool:
60
+ """x is a difference (with its sign or without), sum, product or ratio of two supported numbers stated in the same sentence
61
+ (a percentage difference or share of them only where x is written as a percentage: "50 samples" is no
62
+ 100 x (12 - 8) / 8), or the total of a run of
63
+ them as the sentence lists them ("51 samples (DTC 9, RDEP 11, GR 11, PERM 12, NPHI 8)"); a count's run is read
64
+ over the sentence's counts, the shares written beside them left out ("3474 split as 662 (18.1%), 2799 (76.4%), 12
65
+ (0.3%) and 1 (0.0%)"): the answer shows its inputs, so the arithmetic is checkable."""
66
+ tol = N.tolerance(N.half_of(decimals), x)
67
+ run = counts if counts is not None and not percent else stated
68
+ least = 3 if options.get().tight_numbers else 2 # a mean of two is a midpoint: "0.12 to 0.24, mean 0.18"
69
+ for i in range(len(run)): # a total beside its breakdown, or the mean of the values listed
70
+ total = run[i] # ("roughly 1.63 (1.6911, 1.541, 1.6435)")
71
+ for j in range(i + 1, len(run)):
72
+ total += run[j]
73
+ if (j - i >= 2 and abs(total - x) <= tol) or (j - i + 1 >= least and abs(total / (j - i + 1) - x) <= tol):
74
+ return True
75
+ for i, a in enumerate(stated):
76
+ for b in stated[i + 1:]:
77
+ cands = [abs(a - b), a - b, b - a, a + b, a * b] # a change written with its sign ("78.375 to 74.625
78
+ # (-3.75)"); a product ("0.875 x 27.5 ft = 24.0625": a share of a thickness)
79
+ for num, den in ((a, b), (b, a)):
80
+ if den:
81
+ cands += [num / den] + ([100 * abs(num - den) / abs(den), 100 * num / den] if percent else [])
82
+ if any(abs(c - x) <= tol for c in cands): # a percentage: a change, or a share ("30 of 185 (16.2%)")
83
+ return True
84
+ return False
85
+
86
+
87
+ _NAME_SEP = r"[\s/_#-]"
88
+
89
+
90
+ def well_name_pattern(well: str) -> Optional[re.Pattern]:
91
+ """The well's name as prose may write it: its letter and digit runs in order (same case), joined by any of
92
+ space / _ # - (a file stem writes '/' as '_': '12_3-4 A' matches '12/3-4 A' and '12/3-4A'). Adjacent digit runs
93
+ need a separator, so the pattern never swallows a plain number. None for a name of one run or without digits:
94
+ it cannot be told from a number (or from a word), and the card states it anyway."""
95
+ tokens = re.findall(r"[A-Za-z]+|\d+", str(well))
96
+ if len(tokens) < 2 or not any(t.isdigit() for t in tokens):
97
+ return None
98
+ body = re.escape(tokens[0])
99
+ for prev, tok in zip(tokens, tokens[1:]):
100
+ body += (_NAME_SEP + "+" if prev.isdigit() and tok.isdigit() else _NAME_SEP + "*") + re.escape(tok)
101
+ return re.compile(rf"(?<![A-Za-z0-9]){body}(?![A-Za-z0-9])")
102
+
103
+
104
+ # the unit a worked-out number's inputs must stand in: a sentence (clauses joined by ";" are one: "PHIE mean 0.1258;
105
+ # PHIT mean 0.1260 (diff 0.0002)" in a table cell), ended by . ! ? or a line
106
+ SENTENCE = re.compile(r"(?<=[.!?])\s+|\n")
107
+
108
+
109
+ def _prepared(text: str, card: str, evidence, rules: dict, wells, question: str) -> tuple:
110
+ """(the text as the checker reads it: citations, the well's name and the ignore patterns out; the card; the
111
+ numbers allowed), the one reading of number_provenance and derivations."""
112
+ text, card, question = ascii_minus(text), ascii_minus(card), ascii_minus(question)
113
+ for pattern in filter(None, map(well_name_pattern, wells)):
114
+ question = pattern.sub(" ", question)
115
+ allowed = _allowed_numbers(card, evidence, question if rules.get("question", True) else "")
116
+ clean = N.spelled_as_digits(strip_citations(text)) # numbers written in words, read as the digits they write
117
+ for pattern in filter(None, map(well_name_pattern, wells)):
118
+ clean = pattern.sub(" ", clean)
119
+ for pat in rules.get("ignore", []):
120
+ clean = re.sub(pat, " ", clean)
121
+ return _regrouped(clean, allowed), card, allowed
122
+
123
+
124
+ # thousands grouped by spaces ("3 114.1112", "(10 000)", "5 192 samples"), the SI way: the digits of one number
125
+ _GROUPED = re.compile(r"(?<![A-Za-z_\d.,])\d{1,3}(?: \d{3})+(?:\.\d+)?(?!\d)")
126
+
127
+
128
+ def _regrouped(text: str, allowed: np.ndarray) -> str:
129
+ """Thousands written with spaces read as one number where that number is one the record shows (a
130
+ permeability answer wrote "3 114.1112 mD" and "Z6 (6 376)", and 20 of its numbers were read as pairs of others);
131
+ digits that stand apart otherwise ("2 300" for 2 and 300) stay as written."""
132
+ def one(m):
133
+ joined = m.group(0).replace(" ", "")
134
+ return joined if _supported(number(joined), N.decimals(joined), allowed, False) else m.group(0)
135
+ return _GROUPED.sub(one, text)
136
+
137
+
138
+ def derivations(text: str, card: str, evidence: list, flagged, checks: dict | None = None, wells=(),
139
+ question: str = "") -> dict:
140
+ """For a flagged number that is a difference (with its sign or without), sum, ratio or share of two numbers the
141
+ answer states elsewhere, each shown by a result: {the flagged number: "A - B"}. The repair names that arithmetic
142
+ so the writer keeps the number and writes its inputs beside it ("higher by 18.87 API" was
143
+ flagged because the two means stood in the next sentence, and the repair's 'or remove it' removed the answer). The
144
+ check itself stays the sentence's: this only says how to pass it."""
145
+ rules = (checks or {}).get("numbers", {})
146
+ clean, _, allowed = _prepared(text, card, evidence, rules, wells, question)
147
+ stated = []
148
+ for m in _NUM.finditer(clean):
149
+ raw, pct = m.group(1), bool(m.group(2))
150
+ x = number(raw)
151
+ if (raw, x) not in stated and _supported(x, N.decimals(raw), allowed, pct) and abs(x) >= 1e-12:
152
+ stated.append((raw, x))
153
+ out = {}
154
+ for item in flagged:
155
+ raw = str(item).rstrip("%")
156
+ pct = str(item).endswith("%")
157
+ try:
158
+ x = number(raw)
159
+ tol = N.tolerance(N.half_unit(raw), x)
160
+ except ValueError:
161
+ continue
162
+ said = _written(clean, raw, pct)
163
+ if said is not None: # the arithmetic written out beside it: its value, computed
164
+ expr, value = said
165
+ if abs(value - x) > tol:
166
+ out[item] = ("wrong", expr, f"{value:.{max(N.decimals(raw), 0)}f}")
167
+ continue
168
+ for i, (ra, a) in enumerate(stated):
169
+ for rb, b in stated[i + 1:]:
170
+ cands = [(f"{ra} - {rb}", a - b), (f"{rb} - {ra}", b - a), (f"{ra} + {rb}", a + b)]
171
+ cands += [(f"{ra} / {rb}", a / b), (f"{rb} / {ra}", b / a)] if a and b else []
172
+ if pct and a and b:
173
+ cands += [(f"100 x {ra} / {rb}", 100 * a / b), (f"100 x {rb} / {ra}", 100 * b / a)]
174
+ hit = next((e for e, v in cands if abs(abs(v) - abs(x)) <= tol and (v < 0) == (x < 0)), None)
175
+ if hit:
176
+ out[item] = ("elsewhere", hit)
177
+ break
178
+ if item in out:
179
+ break
180
+ return out
181
+
182
+
183
+ _NUMBER = r"-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?"
184
+ # one piece of written arithmetic: a number (not the digits of a name like Z1), an operator, a parenthesis, or an "x"
185
+ # standing alone as the multiplication sign; a run of them up to the "=" is the expression the answer computes
186
+ _TOKEN = rf"(?:(?<![\d.,_A-Za-wyz]){_NUMBER}|[-+*/()]|(?<![A-Za-z])x(?![A-Za-z]))"
187
+ _EXPRESSION = re.compile(rf"(?:{_TOKEN}\s*)+$")
188
+ _RESULT = re.compile(rf"(?:=|≈|~|is about|is)\s*~?\s*\+?({_NUMBER})\s*(%)?")
189
+
190
+
191
+ def _written(text: str, raw: str, pct: bool):
192
+ """The arithmetic the answer writes out right before a number ("0.1417 / 0.2688 ≈ 0.5277", "0.2 x (1 - 0.35) =
193
+ 0.13"): (the expression as written, its value, x 100 where the number is a percentage), else None. The expression
194
+ is the whole run of arithmetic before the "=" back to the clause start, computed with precedence by the ledger's
195
+ calculator (a fragment read left to right asked for 0.65 in "0.2 x (1 - 0.35) = 0.13", and for 0.52 in "1 - 0.35 x
196
+ 0.8 = 0.72", where the writer was right); an expression that does not parse names no value. The writer's
197
+ arithmetic slips (golden and benchmark answers: 4.375 / 5.1063 written 0.8569) are named with their value so the
198
+ repair corrects them."""
199
+ t = text.replace("\u00d7", "x").replace("\u00f7", "/").replace("\u2212", "-")
200
+ for m in _RESULT.finditer(t):
201
+ if m.group(1) != raw or bool(m.group(2)) != pct:
202
+ continue
203
+ run = _EXPRESSION.search(SENTENCE.split(t[:m.start()])[-1])
204
+ if not run:
205
+ continue
206
+ expr = " ".join(run.group(0).split())
207
+ expr = re.sub(r"^(?:(?:[)*/+x]|-(?=\s))\s*)+", "", expr) # a ")" or a spaced dash before it is not its own
208
+ while expr.startswith("(") and expr.count("(") > expr.count(")"): # a parenthesis it sits in
209
+ expr = expr[1:].lstrip()
210
+ try:
211
+ value, inputs = evaluate(re.sub(r"(?<=\d),(?=\d{3})", "", expr).replace("x", "*"))
212
+ except ToolError:
213
+ continue
214
+ if len(inputs) >= 2:
215
+ return expr, (100 * value if pct else value)
216
+ return None
217
+
218
+
219
+ def number_provenance(text: str, card: str, evidence: list[Evidence], checks: dict | None = None,
220
+ wells: Iterable[str] = (), question: str = "") -> tuple[list[str], int]:
221
+ """(unsupported numbers, numbers checked). The names in `wells` (the task's well) and the checks' `ignore`
222
+ patterns are removed first: they contain digits but are not numbers. Numbers the question states are supported
223
+ (checks numbers.question), and so count as inputs of a derived number in the same sentence."""
224
+ rules = (checks or {}).get("numbers", {})
225
+ clean, card, allowed = _prepared(text, card, evidence, rules, wells, question)
226
+ unsupported, total = [], 0
227
+ lines = None # each shown line's values, read once a pair needs them
228
+
229
+ def paired(k: str, n: str) -> bool: # one shown line holds k with N, or N - k with N
230
+ nonlocal lines
231
+ if lines is None: # every line of what is shown: the card's, and each result's
232
+ texts = card.splitlines() + [ln for e in evidence for ln in _lines_of(e)] # rows, as its values are
233
+ lines = [np.asarray(shown_values(ascii_minus(ln)), dtype=float) for ln in texts if ln.strip()]
234
+ dk, dn = N.decimals(k), N.decimals(n)
235
+ xk, xn = number(k), number(n)
236
+ return any(_supported(xn, dn, ln, False) and (_supported(xk, dk, ln, False) or _supported(xn - xk, dk, ln, False))
237
+ for ln in lines if ln.size >= 2)
238
+
239
+ tight = options.get().tight_numbers
240
+ named, asked = None, np.asarray(shown_values(ascii_minus(question)), dtype=float)
241
+
242
+ def on_a_line_naming(x: float, d: int, pct: bool, names: set) -> bool:
243
+ """x shown on a line that names one of `names`: on the line itself, in its result's first line (what the
244
+ result is about) or in its table's header row."""
245
+ return any(toks & names and _supported(x, d, vals, pct) for toks, vals in named_lines() if vals.size)
246
+
247
+ def named_lines() -> list:
248
+ nonlocal named
249
+ if named is None: # (names, values) of every shown line, once
250
+ named = []
251
+ for b, block in enumerate([card.splitlines()] + [_lines_of(e) for e in evidence]):
252
+ head, header = set(), set()
253
+ for j, ln in enumerate(block):
254
+ toks = set(_NAMES.findall(ln))
255
+ if b and j == 0:
256
+ head = toks
257
+ if not ln.lstrip().startswith("|"):
258
+ header = set()
259
+ elif _RULE.match(ln):
260
+ continue
261
+ elif not header:
262
+ header = toks or {""}
263
+ named.append((toks | head | header, np.asarray(shown_values(ascii_minus(ln)), dtype=float)))
264
+ return named
265
+
266
+ for sentence in SENTENCE.split(clean):
267
+ found, measured = [], set()
268
+ for m in _NUM.finditer(sentence):
269
+ raw, pct = m.group(1), bool(m.group(2))
270
+ found.append((raw, pct, N.decimals(raw), number(raw)))
271
+ if tight and _UNIT_AFTER.match(sentence, m.end()):
272
+ measured.add(len(found) - 1) # "net pay 12 m": a measure, not a count
273
+ stated = [x for _, pct, d, x in found if _supported(x, d, allowed, pct)]
274
+ counts = [x for _, pct, d, x in found if not pct and _supported(x, d, allowed, pct)]
275
+ in_pairs = set() # "k of N": judged as a pair, not number by number
276
+ for m in _PAIR.finditer(sentence):
277
+ k, n = m.group(1), m.group(2)
278
+ if min(number(k), number(n)) < rules.get("skip_integers_below", 20) or N.decimals(k) or N.decimals(n):
279
+ continue # a count is a whole number: "40.08/50.51" lists two values
280
+ in_pairs |= {k, n}
281
+ total += 1
282
+ if paired(k, n):
283
+ continue
284
+ xk = number(k)
285
+ others = lambda xs: (lambda i: xs[:i] + xs[i + 1:])(xs.index(xk)) if xk in xs else xs # not k itself
286
+ if (_supported(number(n), N.decimals(n), allowed, False) # k a total written with its arithmetic
287
+ and _derived(xk, N.decimals(k), others(stated), False, others(counts))): # ("32 + 17 + 75 = 124 of 229")
288
+ continue
289
+ unsupported.append(m.group(0))
290
+ for k, (raw, pct, decimals, x) in enumerate(found):
291
+ if decimals == 0 and not pct and abs(x) < rules.get("skip_integers_below", 20) and k not in measured:
292
+ continue # small counts and ordinals
293
+ if raw in in_pairs and not pct:
294
+ continue # read with its pair
295
+ total += 1
296
+ if _supported(x, decimals, allowed, pct):
297
+ names = (set(_NAMES.findall(sentence)) & set().union(*(t for t, _ in named_lines()))) if tight else ()
298
+ if names and not _supported(x, decimals, asked, pct) and not on_a_line_naming(x, decimals, pct, names):
299
+ unsupported.append(raw + ("%" if pct else "")) # shown, but not where what it is about is
300
+ continue
301
+ if rules.get("derived", True) and _derived(x, decimals, stated, pct, counts):
302
+ continue
303
+ unsupported.append(raw + ("%" if pct else ""))
304
+ return unsupported, total
305
+
306
+
307
+ # the names a line or a sentence gives what a number is about: a zone id or a curve's mnemonic; a table's rule row
308
+ _NAMES = re.compile(r"\b(?:Z\d+|[A-Z][A-Z0-9_]{1,})\b")
309
+ _RULE = re.compile(r"^\s*\|[-:| ]+\|\s*$")
310
+
311
+ # a unit right after a number: the number is a measure (a thickness, a depth, a value), not a count or an ordinal
312
+ _UNIT_AFTER = re.compile(r"\s?(?:m|ft|feet|metres?|meters?|mD|md|API|ohm\.?m|g/cm3|g/cc|v/v|us/ft|°F|degF|ppm)\b")
313
+
314
+
315
+ def _lines_of(e) -> list:
316
+ """A result's lines as the checker reads its values: every row of a ledger item (a direct question's writer reads
317
+ results whole, beyond the text a step was shown; the item's values are all its rows' numbers), else its text."""
318
+ rows = getattr(getattr(e, "item", None), "rows", None)
319
+ return [ln for ln, _ in rows] if rows else e.render().splitlines()
320
+
321
+
322
+ # "k of N", "k out of N", "k/N": a count stated with its population ("658 of 848" where no result
323
+ # shows 658 with 848)
324
+ _PAIR = re.compile(r"(?<![\w.])(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)\s*(?:of|out of|/)\s*(?:the\s+|all\s+)?"
325
+ r"(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(?![\d.]*\d)", re.I)
326
+
327
+
328
+ def availability_issues(text: str, view: FormationView, reg) -> list[str]:
329
+ """V4, clause by clause and only about calibrated porosity/permeability: a denial of PHIE_CC/PERM_CC that exist
330
+ where it speaks (the curves it names, in the zones it names), or a use of ones that do not exist. At most one
331
+ message; a conditional ('where PHIE_CC is missing', a fallback) states coverage and is not a denial."""
332
+ low = text.lower()
333
+ has_core = view.available("PHIE_CC") or view.available("PERM_CC")
334
+ negated, about_poroperm = reg.pattern("availability", "negated"), reg.pattern("availability", "about_poroperm")
335
+ denial, hypo = reg.pattern("availability", "denial"), reg.pattern("availability", "hypothetical")
336
+ calibrated = reg.pattern("availability", "calibrated_curve")
337
+
338
+ def core_where_said(sentence: str) -> bool:
339
+ """The core-corrected curves a denial is about exist where it speaks: the ones it names (else either), in the
340
+ zones it names (else anywhere in the interval). A curve absent from a named zone may be called absent there."""
341
+ named = [c for c in ("PHIE_CC", "PERM_CC") if c.lower() in sentence] or ["PHIE_CC", "PERM_CC"]
342
+ zones = [z for z in view.zones if re.search(rf"\b{re.escape(z.zone_id.lower())}\b", sentence)]
343
+ for c in named:
344
+ if not zones and view.available(c):
345
+ return True
346
+ for z in zones:
347
+ v = view.zone_values(z, c)
348
+ if v is not None and np.isfinite(v).any():
349
+ return True
350
+ return False
351
+
352
+ for sentence in re.split(r"(?<=[.!?])\s+|\n+|;\s*|:\s+", low): # clauses; each line (a table row) on its own
353
+ hypothetical = hypo.search(sentence)
354
+ if has_core and denial.search(sentence) and about_poroperm.search(sentence) and not hypothetical \
355
+ and core_where_said(sentence):
356
+ supplied = [c for c in ("PHIE_CC", "PERM_CC") if c in set(view.prep.input_curves) and view.available(c)]
357
+ origin = ("supplied in the LAS as core-corrected values" if supplied
358
+ else "calibrated on core from this well") # as the card's core fact
359
+ return ["WHAT: the answer says core-calibrated porosity/permeability is unavailable. WHY: PHIE_CC/PERM_CC "
360
+ f"exist in this interval ({origin}; see the card). FIX: report the "
361
+ "core-calibrated values from the evidence and label them as such. Statements about core plugs "
362
+ "inside the interval may stay."]
363
+ if not has_core and calibrated.search(sentence) and not negated.search(sentence):
364
+ return ["WHAT: the answer cites PHIE_CC/PERM_CC. WHY: no core-calibrated curves exist in this interval. "
365
+ "FIX: use the log-derived PHIE/PERM and state that core calibration is not available."]
366
+ return []
367
+
368
+
369
+ def data_denials(text: str, view: FormationView) -> list[str]:
370
+ """V9: data said to be missing while the interval has it (rules/checks.yaml data_denials)."""
371
+ out = []
372
+ for name, entry in (view.reg.checks.get("data_denials") or {}).items():
373
+ present = [c for c in entry.get("curves", []) if view.available(c)]
374
+ m = re.search(entry["pattern"], text, re.I) if present else None
375
+ if m:
376
+ out.append(f"WHAT: the answer says '{m.group(0)}', but this interval has {', '.join(present)}. WHY: the card "
377
+ f"lists the {name} curves present here and how they were used. FIX: use them as the card describes, "
378
+ "and say only what is actually missing.")
379
+ return out