pitopt 1.1.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 (112) hide show
  1. pitopt/__init__.py +15 -0
  2. pitopt/__main__.py +7 -0
  3. pitopt/cli.py +207 -0
  4. pitopt/config.py +530 -0
  5. pitopt/core/__init__.py +1 -0
  6. pitopt/core/cancel.py +32 -0
  7. pitopt/core/design.py +475 -0
  8. pitopt/core/design_detail/__init__.py +5 -0
  9. pitopt/core/design_detail/angles.py +100 -0
  10. pitopt/core/design_detail/builder.py +230 -0
  11. pitopt/core/design_detail/config.py +416 -0
  12. pitopt/core/design_detail/footprint.py +199 -0
  13. pitopt/core/design_detail/offset.py +114 -0
  14. pitopt/core/design_detail/parameters.py +336 -0
  15. pitopt/core/design_detail/ramp.py +533 -0
  16. pitopt/core/design_detail/reconcile.py +210 -0
  17. pitopt/core/design_detail/stack.py +245 -0
  18. pitopt/core/design_detail/validate.py +198 -0
  19. pitopt/core/economics.py +245 -0
  20. pitopt/core/limits.py +136 -0
  21. pitopt/core/pitsurface.py +108 -0
  22. pitopt/core/planning.py +223 -0
  23. pitopt/core/precedence.py +486 -0
  24. pitopt/core/reblock.py +272 -0
  25. pitopt/core/reserves.py +339 -0
  26. pitopt/core/schedule.py +360 -0
  27. pitopt/core/sensitivity.py +100 -0
  28. pitopt/core/shells.py +100 -0
  29. pitopt/core/solver.py +182 -0
  30. pitopt/core/verify.py +310 -0
  31. pitopt/io/__init__.py +3 -0
  32. pitopt/io/blockmodel.py +210 -0
  33. pitopt/io/console.py +75 -0
  34. pitopt/io/datasets.py +204 -0
  35. pitopt/io/datfile.py +93 -0
  36. pitopt/io/design_export.py +360 -0
  37. pitopt/io/dxf.py +259 -0
  38. pitopt/io/excel.py +231 -0
  39. pitopt/io/pdf.py +376 -0
  40. pitopt/io/plot.py +66 -0
  41. pitopt/io/results.py +594 -0
  42. pitopt/io/viz.py +371 -0
  43. pitopt/mcp_server.py +632 -0
  44. pitopt/pipeline.py +1022 -0
  45. pitopt/provenance.py +62 -0
  46. pitopt/ui/__init__.py +3 -0
  47. pitopt/ui/design_service.py +412 -0
  48. pitopt/ui/mcp_controller.py +509 -0
  49. pitopt/ui/onboard.py +403 -0
  50. pitopt/ui/server.py +1145 -0
  51. pitopt/ui/staging.py +49 -0
  52. pitopt/ui/static/css/app.css +301 -0
  53. pitopt/ui/static/css/chat.css +657 -0
  54. pitopt/ui/static/css/design.css +62 -0
  55. pitopt/ui/static/fonts/IBMPlexMono-400.woff2 +0 -0
  56. pitopt/ui/static/fonts/IBMPlexMono-500.woff2 +0 -0
  57. pitopt/ui/static/fonts/IBMPlexMono-600.woff2 +0 -0
  58. pitopt/ui/static/fonts/IBMPlexSans-var.woff2 +0 -0
  59. pitopt/ui/static/fonts/OFL.txt +93 -0
  60. pitopt/ui/static/i18n/en.json +1229 -0
  61. pitopt/ui/static/img/design.webp +0 -0
  62. pitopt/ui/static/img/og-pitopt-2026-11.png +0 -0
  63. pitopt/ui/static/img/pitbypit.webp +0 -0
  64. pitopt/ui/static/img/pushback.webp +0 -0
  65. pitopt/ui/static/img/summary.webp +0 -0
  66. pitopt/ui/static/img/tutorial-marvin.webp +0 -0
  67. pitopt/ui/static/index.html +24 -0
  68. pitopt/ui/static/js/actions.js +4 -0
  69. pitopt/ui/static/js/app.js +223 -0
  70. pitopt/ui/static/js/charts.js +279 -0
  71. pitopt/ui/static/js/chat-panel.js +1210 -0
  72. pitopt/ui/static/js/commands.js +1025 -0
  73. pitopt/ui/static/js/csp-boot.js +48 -0
  74. pitopt/ui/static/js/design/core.js +194 -0
  75. pitopt/ui/static/js/design/plan.js +105 -0
  76. pitopt/ui/static/js/design/planview.js +49 -0
  77. pitopt/ui/static/js/design/section.js +80 -0
  78. pitopt/ui/static/js/design/three.js +45 -0
  79. pitopt/ui/static/js/design/ui.js +175 -0
  80. pitopt/ui/static/js/i18n.js +205 -0
  81. pitopt/ui/static/js/manage.js +119 -0
  82. pitopt/ui/static/js/modal.js +16 -0
  83. pitopt/ui/static/js/run.js +81 -0
  84. pitopt/ui/static/js/store.js +103 -0
  85. pitopt/ui/static/js/tutorial-guide.js +140 -0
  86. pitopt/ui/static/js/util.js +98 -0
  87. pitopt/ui/static/js/views/blocks.js +106 -0
  88. pitopt/ui/static/js/views/common.js +37 -0
  89. pitopt/ui/static/js/views/design_ekspor.js +69 -0
  90. pitopt/ui/static/js/views/design_generate.js +76 -0
  91. pitopt/ui/static/js/views/design_penampang.js +72 -0
  92. pitopt/ui/static/js/views/design_ramp.js +109 -0
  93. pitopt/ui/static/js/views/design_sektor.js +117 -0
  94. pitopt/ui/static/js/views/design_sumber.js +75 -0
  95. pitopt/ui/static/js/views/design_validasi.js +88 -0
  96. pitopt/ui/static/js/views/misc.js +128 -0
  97. pitopt/ui/static/js/views/params.js +189 -0
  98. pitopt/ui/static/js/views/pitbypit.js +65 -0
  99. pitopt/ui/static/js/views/plan.js +140 -0
  100. pitopt/ui/static/js/views/summary.js +94 -0
  101. pitopt/ui/static/js/views/upload.js +503 -0
  102. pitopt/ui/static/js/views/view3d.js +85 -0
  103. pitopt/ui/static/js/views/workspace.js +103 -0
  104. pitopt/ui/static/landing.html +487 -0
  105. pitopt-1.1.0.dist-info/METADATA +180 -0
  106. pitopt-1.1.0.dist-info/RECORD +112 -0
  107. pitopt-1.1.0.dist-info/WHEEL +5 -0
  108. pitopt-1.1.0.dist-info/entry_points.txt +3 -0
  109. pitopt-1.1.0.dist-info/licenses/LICENSE +661 -0
  110. pitopt-1.1.0.dist-info/licenses/NOTICE +19 -0
  111. pitopt-1.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +52 -0
  112. pitopt-1.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,210 @@
1
+ """
2
+ What the practical design mines against what the optimiser shell holds.
3
+
4
+ Every block is classified by its centre, one bench at a time: inside the
5
+ shell and the design, only in the design (material the design takes that the
6
+ optimiser did not pay for: dilution), or only in the shell (material the
7
+ optimiser wanted that the design leaves behind). The tonnage table is the sum
8
+ of that classification and nothing else, so the table and the per-block map
9
+ cannot disagree.
10
+
11
+ Dilution is split by why the design reaches beyond the shell, because the
12
+ remedies differ. Three designs are cut at every bench, each containing the
13
+ last:
14
+
15
+ batter the walls at the geometry the sectors call for
16
+ min width the floor widened to the minimum mining width
17
+ ramp the road cut
18
+
19
+ A block the design takes and the shell does not is assigned to the first of
20
+ these that contains it: walls, then floor width, then ramp. Nothing is
21
+ counted twice.
22
+
23
+ The road cut. Above the road the material within its width is mined out, and
24
+ the wall rises from the road's outer edge at the sector's face angle. The
25
+ ordinary wall leans outward faster than that, because its benches carry
26
+ berms, so the cut sticks out of the ordinary wall by
27
+
28
+ (road width - berm) - h * berm / H
29
+
30
+ at a height h above the road: the widening the overall angle pays for at each
31
+ crossing, shrinking to nothing a few benches higher. At any elevation the cut
32
+ is therefore every stretch of road below it, widened by that lean.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import math
37
+ from dataclasses import dataclass, field
38
+
39
+ import numpy as np
40
+ import pandas as pd
41
+ import shapely
42
+ from shapely.geometry import Polygon
43
+ from shapely.geometry.base import BaseGeometry
44
+
45
+ from .angles import sector_mask
46
+ from .config import DesignLimitsConfig
47
+ from .parameters import BLOCKED, OK, WARNING, SectorGeometry
48
+ from .ramp import Ramp
49
+ from .stack import BenchStack
50
+
51
+ CAUSES = ("batter", "min_width", "ramp")
52
+
53
+
54
+ @dataclass
55
+ class Tally:
56
+ """Blocks, ore and waste counts, tonnes and value of a set of blocks."""
57
+
58
+ blocks: int = 0
59
+ ore_blocks: int = 0
60
+ waste_blocks: int = 0
61
+ rock_tonnes: float = 0.0
62
+ ore_tonnes: float = 0.0
63
+ value: float = 0.0
64
+
65
+ @classmethod
66
+ def of(cls, blocks: pd.DataFrame, mask: np.ndarray) -> Tally:
67
+ ore = (blocks["destination"].to_numpy() == 1) & mask
68
+ return cls(
69
+ blocks=int(mask.sum()), ore_blocks=int(ore.sum()), waste_blocks=int(mask.sum() - ore.sum()),
70
+ rock_tonnes=float(blocks["rock_tonnes"].to_numpy()[mask].sum()),
71
+ ore_tonnes=float(blocks["ore_tonnes"].to_numpy()[ore].sum()),
72
+ value=float(blocks["value"].to_numpy()[mask].sum()),
73
+ )
74
+
75
+
76
+ @dataclass
77
+ class Reconciliation:
78
+ shell: Tally # every block inside the optimiser shell
79
+ design: Tally # every block inside the practical design
80
+ gained: dict[str, Tally] # in the design, not the shell, by cause
81
+ left_behind: Tally # in the shell, not the design
82
+ per_bench: pd.DataFrame # one row per bench, category and cause
83
+ raster: dict | None = None # the uniform raster design's totals, when it was run
84
+ warn_pct: float = 5.0
85
+ block_pct: float = 10.0
86
+ in_design: np.ndarray = field(default_factory=lambda: np.zeros(0, dtype=bool), repr=False)
87
+ cause: np.ndarray = field(default_factory=lambda: np.zeros(0, dtype=object), repr=False)
88
+
89
+ @property
90
+ def gained_total(self) -> Tally:
91
+ return _sum(self.gained.values())
92
+
93
+ def change_pct(self, metric: str) -> float:
94
+ """Practical design against the shell, per cent; nan when the shell has none of it."""
95
+ base = getattr(self.shell, metric)
96
+ return 100.0 * (getattr(self.design, metric) - base) / base if base else float("nan")
97
+
98
+ def status(self, metric: str) -> str:
99
+ change = abs(self.change_pct(metric))
100
+ if np.isnan(change) or change <= self.warn_pct:
101
+ return OK
102
+ return WARNING if change <= self.block_pct else BLOCKED
103
+
104
+ def residual(self) -> dict[str, float]:
105
+ """design - (shell + gained - left behind), per figure. Zero to rounding: it is the same classification
106
+ counted two ways, so anything else is a bug."""
107
+ gained = self.gained_total
108
+ return {f: getattr(self.design, f) - (getattr(self.shell, f) + getattr(gained, f) - getattr(self.left_behind, f))
109
+ for f in ("blocks", "ore_blocks", "waste_blocks", "rock_tonnes", "ore_tonnes", "value")}
110
+
111
+
112
+ def _sum(tallies) -> Tally:
113
+ total = Tally()
114
+ for t in tallies:
115
+ for f in total.__dataclass_fields__:
116
+ setattr(total, f, getattr(total, f) + getattr(t, f))
117
+ return total
118
+
119
+
120
+ def _levels(blocks: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
121
+ """Distinct block-centre elevations, and each block's index into them."""
122
+ return np.unique(np.round(blocks["z"].to_numpy(), 6), return_inverse=True)
123
+
124
+
125
+ def _road_cut(ramp: Ramp, sectors: list[SectorGeometry]):
126
+ """The road as short straight pieces, each with the elevation it sits at, and how fast the wall cut above it
127
+ leans outward per metre of height (the cotangent of the face angle of the sector the piece lies in)."""
128
+ a = np.column_stack([ramp.x[:-1], ramp.y[:-1]])
129
+ b = np.column_stack([ramp.x[1:], ramp.y[1:]])
130
+ mid = (a + b) / 2.0
131
+ bearing = np.degrees(np.arctan2(mid[:, 0] - ramp.centre[0], mid[:, 1] - ramp.centre[1])) % 360.0
132
+ lean = np.zeros(len(mid))
133
+ assigned = np.zeros(len(mid), dtype=bool)
134
+ for sector in sectors:
135
+ hit = sector_mask(sector, bearing) & ~assigned
136
+ lean[hit] = 1.0 / math.tan(math.radians(sector.face_angle_deg))
137
+ assigned |= hit
138
+ pieces = shapely.linestrings(np.stack([a, b], axis=1))
139
+ return pieces, (ramp.z[:-1] + ramp.z[1:]) / 2.0, lean
140
+
141
+
142
+ def _road_cut_at(rl: float, road, half_width: float, window: float) -> BaseGeometry:
143
+ """The road cut at one elevation: every stretch of road at or below it, widened by the lean of the wall
144
+ above it. `window` drops road so far below that the ordinary wall has already moved past it."""
145
+ pieces, z, lean = road
146
+ below = (z <= rl) & (rl - z <= window)
147
+ if not below.any():
148
+ return Polygon()
149
+ return shapely.union_all(shapely.buffer(pieces[below], half_width + (rl - z[below]) * lean[below], quad_segs=8))
150
+
151
+
152
+ def reconcile(blocks: pd.DataFrame, in_pit: np.ndarray, plain: BenchStack, stack: BenchStack, ramp: Ramp | None,
153
+ limits: DesignLimitsConfig, raster: dict | None = None) -> Reconciliation:
154
+ """Classify every block against the shell and the three nested designs.
155
+
156
+ `plain` is the stack with the floor as the optimiser has it and `stack` the one with the floor widened; they
157
+ are the same object when nothing was widened."""
158
+ x, y = blocks["x"].to_numpy(), blocks["y"].to_numpy()
159
+ levels, level_of = _levels(blocks)
160
+ in_batter, in_width, in_design = (np.zeros(len(blocks), dtype=bool) for _ in range(3))
161
+ road = window = None
162
+ if ramp is not None and len(ramp.x) > 1:
163
+ road = _road_cut(ramp, stack.sectors)
164
+ window = _cut_window(ramp, stack)
165
+
166
+ for i, level in enumerate(levels):
167
+ bench = stack.bench_at(level)
168
+ if bench is None:
169
+ continue
170
+ idx = np.flatnonzero(level_of == i)
171
+ section = plain.section_at(level)
172
+ in_batter[idx] = shapely.contains_xy(section, x[idx], y[idx])
173
+ widened = section if stack is plain else stack.section_at(level)
174
+ in_width[idx] = shapely.contains_xy(widened, x[idx], y[idx]) if widened is not section else in_batter[idx]
175
+ cut = _road_cut_at(level, road, ramp.sizing.width_m / 2.0, window) if road is not None else None
176
+ full = widened if cut is None or cut.is_empty else widened.union(cut)
177
+ in_design[idx] = shapely.contains_xy(full, x[idx], y[idx]) if full is not widened else in_width[idx]
178
+
179
+ cause = np.where(in_batter, "batter", np.where(in_width, "min_width", np.where(in_design, "ramp", "")))
180
+ new = in_design & ~in_pit
181
+ gained = {c: Tally.of(blocks, new & (cause == c)) for c in CAUSES}
182
+ return Reconciliation(
183
+ Tally.of(blocks, in_pit), Tally.of(blocks, in_design), gained, Tally.of(blocks, in_pit & ~in_design),
184
+ _per_bench(blocks, in_pit, in_design, cause, level_of, levels), raster,
185
+ limits.recon_warn_pct, limits.recon_block_pct, in_design, cause,
186
+ )
187
+
188
+
189
+ def _cut_window(ramp: Ramp, stack: BenchStack) -> float:
190
+ """How far above a stretch of road its cut can still stick out of the ordinary wall: where the excess
191
+ (road width - berm) - h * berm / H reaches zero, in the sector with the least berm."""
192
+ height = stack.benches[0].crest_rl - stack.benches[-1].toe_rl
193
+ windows = [(ramp.sizing.width_m - s.berm_width) * s.bench_height / s.berm_width if s.berm_width > 0 else height
194
+ for s in stack.sectors]
195
+ return min(height, max(windows) + stack.sectors[0].bench_height)
196
+
197
+
198
+ def _per_bench(blocks, in_pit, in_design, cause, level_of, levels) -> pd.DataFrame:
199
+ """One row per elevation, category and cause: the map of screen 5 as a table."""
200
+ category = np.where(in_pit & in_design, "both", np.where(in_design, "design_only", np.where(in_pit, "shell_only", "")))
201
+ ore = blocks["destination"].to_numpy() == 1
202
+ frame = pd.DataFrame({
203
+ "rl": levels[level_of], "category": category, "cause": np.where(category == "design_only", cause, ""),
204
+ "blocks": 1, "ore_blocks": ore.astype(int), "waste_blocks": (~ore).astype(int),
205
+ "rock_tonnes": blocks["rock_tonnes"].to_numpy(),
206
+ "ore_tonnes": np.where(ore, blocks["ore_tonnes"].to_numpy(), 0.0), "value": blocks["value"].to_numpy(),
207
+ })
208
+ frame = frame[frame["category"] != ""]
209
+ return frame.groupby(["rl", "category", "cause"], as_index=False).sum().sort_values(
210
+ ["rl", "category", "cause"], ascending=[False, True, True]).reset_index(drop=True)
@@ -0,0 +1,245 @@
1
+ """
2
+ The bench stack: crest and toe outline of every bench, built from one
3
+ anchor outline by repeated offsetting.
4
+
5
+ Bench k counted from the anchor has its crest at
6
+
7
+ crest_offset(k) = k * run + floor(k / N) * berm
8
+
9
+ from the anchor outline and its toe one face run further in (PRD F-DES-6).
10
+ With `anchor: floor` the anchor is the floor outline and the walls are
11
+ offset outward as the stack climbs; with `anchor: crest` it is the crest and
12
+ the stack steps inward as it descends. The offset distance depends on the
13
+ sector the wall faces, mixed across boundaries, so the same routine builds a
14
+ uniform pit and a sectored one.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from collections.abc import Callable
20
+ from dataclasses import dataclass, field
21
+
22
+ import shapely
23
+ from shapely.geometry import Polygon
24
+ from shapely.geometry.base import BaseGeometry
25
+
26
+ from ..cancel import CancelToken
27
+ from .config import DesignDetailConfig
28
+ from .offset import _areal, azimuth_profile, offset
29
+ from .parameters import SectorGeometry
30
+
31
+ MAX_BENCHES = 200 # a guard against a mistyped bench height, not a design limit
32
+
33
+
34
+ @dataclass
35
+ class Bench:
36
+ """One bench. `index` counts from the top: 1 is the highest bench."""
37
+
38
+ index: int
39
+ crest_rl: float
40
+ toe_rl: float
41
+ crest: BaseGeometry
42
+ toe: BaseGeometry
43
+ crest_offsets: dict[str, float] # per sector: distance of the crest ring from the anchor outline
44
+ toe_offsets: dict[str, float]
45
+
46
+ @property
47
+ def height(self) -> float:
48
+ return self.crest_rl - self.toe_rl
49
+
50
+
51
+ @dataclass
52
+ class BenchStack:
53
+ benches: list[Bench] # top to bottom
54
+ anchor: str
55
+ anchor_rl: float
56
+ sectors: list[SectorGeometry]
57
+ warnings: list[str] = field(default_factory=list)
58
+ collapsed_at: int | None = None # bench, counted from the crest, that has no area left (crest anchor only)
59
+ anchor_outline: BaseGeometry | None = None
60
+ config: DesignDetailConfig | None = None
61
+
62
+ def bench_at(self, rl: float) -> Bench | None:
63
+ """The bench whose face spans this elevation; None above the crest or below the floor."""
64
+ for bench in self.benches:
65
+ if bench.toe_rl - 1e-9 <= rl <= bench.crest_rl + 1e-9:
66
+ return bench
67
+ return None
68
+
69
+ def section_at(self, rl: float) -> BaseGeometry:
70
+ """The excavation as cut by a horizontal plane at this elevation: the ring at the matching point up
71
+ the face, between the bench's toe and its crest. Empty outside the built stack."""
72
+ bench = self.bench_at(rl)
73
+ if bench is None:
74
+ return Polygon()
75
+ fraction = (rl - bench.toe_rl) / bench.height
76
+ if self.anchor == "shell":
77
+ if fraction <= 1e-9:
78
+ return bench.toe
79
+ if fraction >= 1.0 - 1e-9:
80
+ return bench.crest
81
+ offsets = [fraction * s.face_run for s in self.sectors]
82
+ return ring_outline(bench.toe, self.sectors, offsets, self.config, grow=True)[0]
83
+ offsets = [bench.toe_offsets[s.name] + fraction * (bench.crest_offsets[s.name] - bench.toe_offsets[s.name])
84
+ for s in self.sectors]
85
+ return ring_outline(self.anchor_outline, self.sectors, offsets, self.config, grow=self.anchor == "floor")[0]
86
+
87
+
88
+ def bench_count(top_rl: float, bottom_rl: float, bench_height: float) -> int:
89
+ """Whole benches between two elevations; a partial one at the top counts
90
+ as a bench, since the wall still has to reach the crest."""
91
+ n = math.ceil((top_rl - bottom_rl) / bench_height - 1e-9)
92
+ if n < 1:
93
+ raise ValueError(f"crest {top_rl:g} is not above the floor {bottom_rl:g}")
94
+ if n > MAX_BENCHES:
95
+ raise ValueError(f"{n} benches of {bench_height:g} m between {bottom_rl:g} and {top_rl:g}: check the bench height")
96
+ return n
97
+
98
+
99
+ def _distance(config: DesignDetailConfig, sectors: list[SectorGeometry], offsets: list[float]):
100
+ """A number when every sector asks for the same distance, else a
101
+ bearing-dependent function. The number path is shapely's own buffer,
102
+ the one that supports a mitre join."""
103
+ if max(offsets) - min(offsets) < 1e-9:
104
+ return offsets[0], False
105
+ return azimuth_profile(sectors, offsets, config.blend_deg), True
106
+
107
+
108
+ def ring_outline(anchor_outline: BaseGeometry, sectors: list[SectorGeometry], offsets: list[float],
109
+ config: DesignDetailConfig, *, grow: bool) -> tuple[BaseGeometry, bool]:
110
+ """The anchor outline moved out (or in) by each sector's distance. The second value says whether the
111
+ distance varied by sector, which is when a mitre join gives way to a round one."""
112
+ distance, variable = _distance(config, sectors, offsets)
113
+ style = "round" if variable else config.join_style
114
+ return offset(anchor_outline, distance, grow=grow, join_style=style, miter_limit=config.miter_limit), variable
115
+
116
+
117
+ def build_bench_stack(anchor_outline: BaseGeometry, anchor_rl: float, n_benches: int, sectors: list[SectorGeometry],
118
+ config: DesignDetailConfig, on_bench: Callable[[Bench, int], None] | None = None,
119
+ cancel: CancelToken | None = None) -> BenchStack:
120
+ """Build `n_benches` benches from an anchor outline.
121
+
122
+ `on_bench(bench, n_done)` is called as each bench is finished, in the order they are built, so a viewer can
123
+ draw the pit while it is still being computed; `cancel` is checked before each one.
124
+
125
+ Floor anchor: benches are numbered upward internally and reported from
126
+ the top, so a bench keeps the same index whichever way it was built."""
127
+ heights = {s.bench_height for s in sectors}
128
+ if len(heights) != 1:
129
+ raise ValueError("sectors with different bench heights are not supported: benches must share elevations")
130
+ height = heights.pop()
131
+ grow = config.anchor == "floor"
132
+ stack = BenchStack([], config.anchor, anchor_rl, sectors, anchor_outline=anchor_outline, config=config)
133
+ mitre_dropped = False
134
+
135
+ def ring(k: int, far: bool) -> tuple[BaseGeometry, dict[str, float], bool]:
136
+ """The ring of bench k nearer the anchor (`far=False`) or a face run further from it."""
137
+ offsets = [s.toe_offset(k) if far else s.crest_offset(k) for s in sectors]
138
+ outline, variable = ring_outline(anchor_outline, sectors, offsets, config, grow=grow)
139
+ return outline, {s.name: o for s, o in zip(sectors, offsets)}, variable
140
+
141
+ if anchor_outline.is_empty:
142
+ raise ValueError("the anchor outline is empty: nothing to build a pit from")
143
+
144
+ built: list[Bench] = []
145
+ for k in range(n_benches):
146
+ if cancel is not None:
147
+ cancel.check()
148
+ near, near_off, v_near = ring(k, far=False)
149
+ far, far_off, v_far = ring(k, far=True)
150
+ mitre_dropped |= (v_near or v_far) and config.join_style == "mitre"
151
+ if grow: # k counts upward from the floor: the near ring is the toe, the far ring the crest
152
+ crest, toe, crest_off, toe_off = far, near, far_off, near_off
153
+ crest_rl, toe_rl = anchor_rl + (k + 1) * height, anchor_rl + k * height
154
+ else: # k counts downward from the crest: the near ring is the crest
155
+ crest, toe, crest_off, toe_off = near, far, near_off, far_off
156
+ crest_rl, toe_rl = anchor_rl - k * height, anchor_rl - (k + 1) * height
157
+ if crest.is_empty or toe.is_empty:
158
+ stack.collapsed_at = k + 1
159
+ stack.warnings.append(
160
+ f"bench {k + 1} from the crest has no area left at RL {toe_rl:g}: the pit closes above its floor"
161
+ )
162
+ break
163
+ bench = Bench(n_benches - k if grow else k + 1, crest_rl, toe_rl, crest, toe, crest_off, toe_off)
164
+ built.append(bench)
165
+ if on_bench is not None:
166
+ on_bench(bench, len(built))
167
+
168
+ ordered = sorted(built, key=lambda b: -b.crest_rl)
169
+ for i, bench in enumerate(ordered, start=1):
170
+ bench.index = i
171
+ stack.benches = ordered
172
+ if mitre_dropped:
173
+ stack.warnings.append("mitre join needs one distance all round; the sector boundaries use round joins instead")
174
+ return stack
175
+
176
+
177
+ def build_shell_constrained_stack(
178
+ shell_footprints: list[BaseGeometry],
179
+ floor_rl: float,
180
+ n_benches: int,
181
+ sectors: list[SectorGeometry],
182
+ config: DesignDetailConfig,
183
+ on_bench: Callable[[Bench, int], None] | None = None,
184
+ cancel: CancelToken | None = None,
185
+ ) -> BenchStack:
186
+ """Build `n_benches` benches upward from `floor_rl`, honouring each elevation's shell footprint while
187
+ stepping outward from the bench below by the catch berm so walls never overhang."""
188
+ heights = {s.bench_height for s in sectors}
189
+ if len(heights) != 1:
190
+ raise ValueError("sectors with different bench heights are not supported: benches must share elevations")
191
+ height = heights.pop()
192
+ if not shell_footprints or shell_footprints[0].is_empty:
193
+ raise ValueError("the floor shell footprint is empty: nothing to build a pit from")
194
+
195
+ stack = BenchStack([], "shell", floor_rl, sectors, anchor_outline=shell_footprints[0], config=config)
196
+ face_runs = [s.face_run for s in sectors]
197
+ mitre_dropped = False
198
+ built: list[Bench] = []
199
+ prev_crest: BaseGeometry | None = None
200
+
201
+ for k in range(n_benches):
202
+ if cancel is not None:
203
+ cancel.check()
204
+ if k == 0:
205
+ toe = shell_footprints[0]
206
+ v_berm = False
207
+ else:
208
+ assert prev_crest is not None
209
+ berm_offsets = [s.crest_offset(k) - s.toe_offset(k - 1) for s in sectors]
210
+ if max(berm_offsets) > 0:
211
+ min_toe, v_berm = ring_outline(prev_crest, sectors, berm_offsets, config, grow=True)
212
+ else:
213
+ min_toe, v_berm = prev_crest, False
214
+ if k < len(shell_footprints) and not shell_footprints[k].is_empty:
215
+ toe = shapely.union_all([min_toe, shell_footprints[k]])
216
+ if not toe.is_valid:
217
+ toe = toe.buffer(0)
218
+ toe = _areal(toe)
219
+ else:
220
+ toe = min_toe
221
+ crest, v_crest = ring_outline(toe, sectors, face_runs, config, grow=True)
222
+ mitre_dropped |= (v_berm or v_crest) and config.join_style == "mitre"
223
+ toe_rl = floor_rl + k * height
224
+ crest_rl = floor_rl + (k + 1) * height
225
+ bench = Bench(
226
+ n_benches - k,
227
+ crest_rl,
228
+ toe_rl,
229
+ crest,
230
+ toe,
231
+ {s.name: s.toe_offset(k) for s in sectors},
232
+ {s.name: s.crest_offset(k) for s in sectors},
233
+ )
234
+ built.append(bench)
235
+ prev_crest = crest
236
+ if on_bench is not None:
237
+ on_bench(bench, len(built))
238
+
239
+ ordered = sorted(built, key=lambda b: -b.crest_rl)
240
+ for i, bench in enumerate(ordered, start=1):
241
+ bench.index = i
242
+ stack.benches = ordered
243
+ if mitre_dropped:
244
+ stack.warnings.append("mitre join needs one distance all round; the sector boundaries use round joins instead")
245
+ return stack
@@ -0,0 +1,198 @@
1
+ """
2
+ The checks that say whether a design can be built and defended.
3
+
4
+ Five headline validations, each returning findings with a status of OK,
5
+ warning or blocked:
6
+
7
+ ira inter-ramp angle per sector against its limit
8
+ osa overall angle per sector against its limit, ramp counted
9
+ reconciliation tonnes, ore and value of the design against the shell
10
+ ramp the road is one continuous path, as wide as the fleet needs
11
+ self_intersection no bench outline crosses itself and no wall overhangs
12
+
13
+ and two more: `min_width` for the floor, and `shape_fit`, which is not in
14
+ the PRD's original five. It exists because the offset construction
15
+ (build_bench_stack, PRD F-DES-6) never looks at the shell again once the
16
+ anchor outline is taken: every bench's wall is the last bench's wall
17
+ moved out by a fixed, formula-derived distance, nothing else. That
18
+ matches a shell that is one cone widening steadily from its floor to its
19
+ crest (porphyry, most hard-rock open pits — confirmed by comparing every
20
+ bench's own area against the shell's at the same elevation: never below
21
+ about 104% of it on the bundled porphyry example, i.e. the design is
22
+ always at least as wide as the true shell there). It is wrong for a
23
+ shell whose footprint balloons at a middle elevation and pinches at both
24
+ ends — a wide, shallow, undulating deposit such as mineral-sands strip
25
+ mining, or a stratiform seam — because offsetting outward from a floor
26
+ or crest that is a sliver of the shell's true width never catches up to
27
+ it. Found by running the engine against a real mineral-sands mine's shell:
28
+ the practical design came out 96.8% smaller than the shell (the existing
29
+ raster design agrees with the shell to +1.6% on the same run), and the
30
+ worst bench there tracks the shell at 6.3% of its true area — no berm or
31
+ grade tuning fixes that, because the fault is the shape, not a number.
32
+
33
+ `shape_fit` catches this directly: at every bench, on both the toe and
34
+ the crest, it compares that ring's own area against the shell's true
35
+ footprint area at the matching elevation, and reports the bench and
36
+ side where the two agree the least. Below `SHAPE_WARN_RATIO` the design
37
+ may fall short of the shell's true width somewhere up the wall; below
38
+ `SHAPE_BLOCK_RATIO` it does not fit a single-cone offset at all, and the
39
+ reconciliation figures that follow should not be trusted without reading
40
+ this finding first. `source` on `design.detail` (final_shell today, PRD
41
+ F-DES-6 leaves pushback for later) is a separate question from whether
42
+ the shape itself fits.
43
+
44
+ A finding names what it checked, where, the value and the limit, so the
45
+ report can say why and not only that. Statuses are stored, not
46
+ recomputed later: what was written to a file is what was decided.
47
+ """
48
+ from __future__ import annotations
49
+
50
+ from dataclasses import dataclass
51
+
52
+ from shapely import is_valid_reason
53
+
54
+ from .angles import SectorOSA
55
+ from .config import DesignLimitsConfig
56
+ from .footprint import ShellFit
57
+ from .parameters import BLOCKED, OK, WARNING
58
+ from .ramp import Ramp
59
+ from .reconcile import Reconciliation
60
+ from .stack import BenchStack
61
+
62
+ CHECKS = ("shape_fit", "ira", "osa", "reconciliation", "ramp", "self_intersection", "min_width")
63
+ _RANK = {OK: 0, WARNING: 1, BLOCKED: 2}
64
+
65
+ # A bench's own area (toe or crest), as a fraction of the shell's true footprint area at the matching
66
+ # elevation — the worst such ratio anywhere in the stack. Calibrated against the three real shells on hand:
67
+ # the bundled porphyry example never dips below ~104% (the design is always a little larger than the shell
68
+ # there, which is what a correctly-widening cone should do), the bundled tin example's worst point is ~87%
69
+ # (a mild edge effect near its floor), and a real mineral-sands mine's shell — the shape this check exists
70
+ # for — falls to 6.3%. WARN and BLOCK sit between the good pair and the bad one with visible margin either
71
+ # side; revisit if a legitimate shell is ever found to sit inside that gap.
72
+ SHAPE_WARN_RATIO = 0.7
73
+ SHAPE_BLOCK_RATIO = 0.4
74
+
75
+
76
+ @dataclass
77
+ class Finding:
78
+ check: str
79
+ scope: str # a sector, a bench, a metric; "" for the whole design
80
+ status: str
81
+ message: str
82
+ value: float | None = None
83
+ limit: float | None = None
84
+
85
+
86
+ @dataclass
87
+ class Validation:
88
+ findings: list[Finding]
89
+
90
+ def status(self, check: str | None = None) -> str:
91
+ """Worst status of one check, or of all of them."""
92
+ chosen = [f.status for f in self.findings if check is None or f.check == check]
93
+ return max(chosen, key=_RANK.__getitem__, default=OK)
94
+
95
+ def by_check(self) -> dict[str, str]:
96
+ return {c: self.status(c) for c in CHECKS}
97
+
98
+ def problems(self) -> list[Finding]:
99
+ return [f for f in self.findings if f.status != OK]
100
+
101
+
102
+ def _angle(check: str, sector, value: float, limit: float | None, status: str, label: str) -> Finding:
103
+ if limit is None:
104
+ return Finding(check, sector, OK, f"{label} {value:.1f} deg, no limit set", value, None)
105
+ margin = limit - value
106
+ verb = {OK: "within", WARNING: "within the margin of", BLOCKED: "over"}[status]
107
+ return Finding(check, sector, status, f"{label} {value:.1f} deg is {verb} the {limit:g} deg limit ({margin:+.1f} deg)",
108
+ value, limit)
109
+
110
+
111
+ def _shape_fit_finding(fit: ShellFit) -> Finding:
112
+ status = BLOCKED if fit.ratio < SHAPE_BLOCK_RATIO else WARNING if fit.ratio < SHAPE_WARN_RATIO else OK
113
+ where = f"bench {fit.bench} ({fit.side}, RL {fit.rl:g})"
114
+ if status == OK:
115
+ message = f"the design tracks the shell within {fit.ratio:.0%} everywhere; worst at {where}"
116
+ else:
117
+ verb = "falls short of" if status == WARNING else "does not fit"
118
+ message = (f"at {where} the design covers {fit.design_area_m2:,.0f} m2 against {fit.shell_area_m2:,.0f} m2 "
119
+ f"the shell actually reaches there ({fit.ratio:.0%}); the offset construction {verb} the "
120
+ f"shell's true width at this elevation"
121
+ + ("; treat the reconciliation below with that in mind" if status == BLOCKED else ""))
122
+ # scope carries the same "bench N (side, RL x)" a UI needs to render this without re-parsing the English
123
+ # message, the same convention self_intersection's findings use for their own "bench N" scope.
124
+ return Finding("shape_fit", where, status, message, fit.ratio, SHAPE_BLOCK_RATIO if status == BLOCKED else SHAPE_WARN_RATIO)
125
+
126
+
127
+ def validate(stack: BenchStack, angles, osa: list[SectorOSA], ramp: Ramp | None, floor_width_m: float,
128
+ reconciliation: Reconciliation | None, limits: DesignLimitsConfig,
129
+ shape_fit: ShellFit | None = None) -> Validation:
130
+ findings: list[Finding] = []
131
+
132
+ if shape_fit is not None:
133
+ findings.append(_shape_fit_finding(shape_fit))
134
+
135
+ for a in angles:
136
+ findings.append(_angle("ira", a.name, a.ira_deg, a.ira_max_deg, a.status, "inter-ramp angle"))
137
+ for o in osa:
138
+ findings.append(_angle("osa", o.name, o.osa_deg, o.osa_max_deg, o.status, "overall angle with the ramp"))
139
+
140
+ if reconciliation is not None:
141
+ for metric, label in (("rock_tonnes", "rock"), ("ore_tonnes", "ore"), ("value", "value")):
142
+ change, status = reconciliation.change_pct(metric), reconciliation.status(metric)
143
+ if change != change: # nan: the shell holds none of it
144
+ continue
145
+ limit = reconciliation.block_pct if status == BLOCKED else reconciliation.warn_pct
146
+ findings.append(Finding("reconciliation", label, status,
147
+ f"{label} of the design is {change:+.1f}% against the shell (warning beyond "
148
+ f"{reconciliation.warn_pct:g}%, blocked beyond {reconciliation.block_pct:g}%)", change, limit))
149
+
150
+ if ramp is None:
151
+ findings.append(Finding("ramp", "", OK, "no ramp requested"))
152
+ else:
153
+ if ramp.broken:
154
+ findings.append(Finding("ramp", f"bench {ramp.broken.bench}", BLOCKED, f"the ramp is broken: {ramp.broken.reason}"))
155
+ else:
156
+ findings.append(Finding("ramp", "", OK, f"one continuous road from the floor to the crest, "
157
+ f"{ramp.horizontal_length_m:,.0f} m at {ramp.sizing.grade_pct:g}%"))
158
+ if ramp.secondary_lobes:
159
+ affected = sorted({int(e["bench"]) for e in ramp.secondary_lobes})
160
+ bench_label = ", ".join(str(b) for b in affected)
161
+ max_area = max(float(e["unserved_area_m2"]) for e in ramp.secondary_lobes)
162
+ max_parts = max(int(e["unserved_parts"]) for e in ramp.secondary_lobes)
163
+ findings.append(Finding(
164
+ "ramp",
165
+ f"bench {bench_label}",
166
+ WARNING,
167
+ f"ramp serves only the primary pit lobe; {max_parts} disconnected secondary lobe(s) on bench(es) "
168
+ f"{bench_label} remain unserved (up to {max_area:,.0f} m2)",
169
+ max_area,
170
+ 0.0,
171
+ ))
172
+ if not ramp.sizing.width_ok:
173
+ findings.append(Finding("ramp", "", WARNING, f"the road is {ramp.sizing.width_m:g} m wide, narrower than the "
174
+ f"{ramp.sizing.required_width_m:g} m the fleet needs",
175
+ ramp.sizing.width_m, ramp.sizing.required_width_m))
176
+
177
+ tolerance = limits.tolerance_m
178
+ invalid = [b for b in stack.benches if not (b.crest.is_valid and b.toe.is_valid)]
179
+ for b in invalid:
180
+ why = "; ".join(is_valid_reason(g) for g in (b.crest, b.toe) if not g.is_valid)
181
+ findings.append(Finding("self_intersection", f"bench {b.index}", BLOCKED, f"outline is not a valid polygon: {why}"))
182
+ overhangs = [f"bench {a.index}/{b.index}" for a, b in zip(stack.benches, stack.benches[1:])
183
+ if a.toe.is_valid and b.crest.is_valid and not a.toe.buffer(tolerance).contains(b.crest)]
184
+ for where in overhangs:
185
+ findings.append(Finding("self_intersection", where, BLOCKED, "the wall overhangs: a bench sits outside the one above it"))
186
+ if ramp is not None:
187
+ for bench, strip in ramp.strips.items():
188
+ if not strip.is_valid:
189
+ findings.append(Finding("self_intersection", f"bench {bench}", BLOCKED, "the road strip is not a valid polygon"))
190
+ if not invalid and not overhangs and all(s.is_valid for s in (ramp.strips.values() if ramp else [])):
191
+ findings.append(Finding("self_intersection", "", OK,
192
+ f"{len(stack.benches)} benches: every outline is valid and no wall overhangs"))
193
+
194
+ minimum = limits.min_mining_width_m
195
+ findings.append(Finding("min_width", "floor", OK if floor_width_m >= minimum else BLOCKED,
196
+ f"the floor is {floor_width_m:.1f} m wide against a {minimum:g} m minimum mining width",
197
+ floor_width_m, minimum))
198
+ return Validation(findings)