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,199 @@
1
+ """
2
+ The optimiser shell as an outline, and the simplification that makes it
3
+ diggable.
4
+
5
+ A maximum_closure shell is a set of whole blocks. Its outline at one level is
6
+ the union of those blocks' squares — a staircase that steps by a block at
7
+ a time. Offsetting the staircase as it is would reproduce every step as a
8
+ notch in every bench, so the outline is simplified first. That is a
9
+ judgement, not a standard, and it is the stage that most decides how the
10
+ result looks; so what it did — how far it allowed a point to move, how much
11
+ area it gained or lost, what it dropped — comes back as a record beside
12
+ the geometry rather than being folded into it.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from dataclasses import dataclass, field
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import shapely
22
+ from shapely.geometry import Polygon
23
+ from shapely.geometry.base import BaseGeometry
24
+
25
+ from .config import SmoothingConfig
26
+
27
+
28
+ @dataclass
29
+ class SmoothingRecord:
30
+ """What the smoothing did to the outline. Reported in the design so
31
+ that a tonnage difference can be traced to it."""
32
+
33
+ applied: bool
34
+ tolerance_m: float
35
+ closing_m: float
36
+ area_before_m2: float
37
+ area_after_m2: float
38
+ dropped_parts: int = 0
39
+ dropped_area_m2: float = 0.0
40
+ notes: list[str] = field(default_factory=list)
41
+
42
+ @property
43
+ def area_change_m2(self) -> float:
44
+ return self.area_after_m2 - self.area_before_m2
45
+
46
+
47
+ def shell_level_areas(blocks: pd.DataFrame, mask: np.ndarray) -> dict[float, float]:
48
+ """Footprint area (block count times block area) at every elevation the shell occupies.
49
+
50
+ Cheap on purpose — a block count per level, not a union of squares — because this is read to characterise
51
+ the shell's overall shape (is it a single cone that narrows to one floor, or something else) before any
52
+ geometry is built from it, not to draw anything."""
53
+ dx, dy = float(blocks["dx"].iloc[0]), float(blocks["dy"].iloc[0])
54
+ z = np.round(blocks["z"].to_numpy()[mask], 6)
55
+ levels, counts = np.unique(z, return_counts=True)
56
+ return dict(zip(levels.tolist(), (counts * dx * dy).tolist()))
57
+
58
+
59
+ @dataclass
60
+ class ShellFit:
61
+ """How closely the built design tracks the true shell, at the bench and side (toe or crest) where they
62
+ agree the least."""
63
+
64
+ ratio: float # design polygon area / true shell area at the matching elevation, worst over the stack
65
+ bench: int
66
+ side: str # "toe" | "crest"
67
+ rl: float
68
+ design_area_m2: float
69
+ shell_area_m2: float
70
+
71
+
72
+ def worst_shell_fit(stack, shell_areas: dict[float, float], dz: float) -> ShellFit | None:
73
+ """The offset construction (build_bench_stack) grows every bench's wall outward from the last by a fixed,
74
+ formula-derived distance; nothing about it looks at the shell again once the anchor outline is taken. That
75
+ is exactly right for a shell that is one cone widening steadily from its floor to its crest, and it can be
76
+ badly wrong otherwise: a shell whose footprint balloons at a middle elevation and pinches at both ends (a
77
+ wide, shallow, undulating deposit — mineral sands, a stratiform seam) leaves the design far short of the
78
+ true width partway up the wall, with no parameter that fixes it, because the fault is the shape and not a
79
+ number. Comparing each bench's own crest and toe area against the shell's true footprint at that elevation
80
+ catches this directly, at the bench and side where it is worst, rather than inferring it indirectly from
81
+ how far off the final reconciliation ends up.
82
+
83
+ None when the shell has no measurable area at any bench elevation (nothing to compare against)."""
84
+ if not shell_areas:
85
+ return None
86
+ levels = np.array(sorted(shell_areas))
87
+ worst: ShellFit | None = None
88
+ for bench in stack.benches:
89
+ for side, rl, polygon in (("toe", bench.toe_rl, bench.toe), ("crest", bench.crest_rl, bench.crest)):
90
+ shell_area = shell_areas[float(levels[np.argmin(np.abs(levels - (rl - dz / 2.0)))])]
91
+ if shell_area <= 0:
92
+ continue
93
+ ratio = polygon.area / shell_area
94
+ if worst is None or ratio < worst.ratio:
95
+ worst = ShellFit(ratio, bench.index, side, rl, polygon.area, shell_area)
96
+ return worst
97
+
98
+
99
+ def _boxes_union(blocks: pd.DataFrame, at_level: np.ndarray) -> BaseGeometry:
100
+ if not at_level.any():
101
+ return Polygon()
102
+ x, y = blocks["x"].to_numpy()[at_level], blocks["y"].to_numpy()[at_level]
103
+ hx, hy = blocks["dx"].to_numpy()[at_level] / 2.0, blocks["dy"].to_numpy()[at_level] / 2.0
104
+ return shapely.union_all(shapely.box(x - hx, y - hy, x + hx, y + hy))
105
+
106
+
107
+ def level_footprint(blocks: pd.DataFrame, mask: np.ndarray, z: float) -> BaseGeometry:
108
+ """Outline of the masked blocks whose centre is at elevation z.
109
+
110
+ Boxes are built in one vectorised call and merged in one union, which
111
+ stays fast at the block counts a real model has."""
112
+ return _boxes_union(blocks, mask & np.isclose(blocks["z"].to_numpy(), z))
113
+
114
+
115
+ def band_footprint(blocks: pd.DataFrame, mask: np.ndarray, z_lo: float, z_hi: float) -> BaseGeometry:
116
+ """Outline of all masked blocks whose centre lies inside [z_lo, z_hi)."""
117
+ z = blocks["z"].to_numpy()
118
+ return _boxes_union(blocks, mask & (z >= z_lo - 1e-6) & (z < z_hi - 1e-6))
119
+
120
+
121
+ def smooth_outline(outline: BaseGeometry, config: SmoothingConfig, block_diagonal_m: float) -> tuple[BaseGeometry, SmoothingRecord]:
122
+ """Close single-block notches, simplify, drop unmineable fragments.
123
+
124
+ The simplification band defaults to one block diagonal — the finest
125
+ detail the shell actually carries, so nothing real is smoothed away and
126
+ only the staircase is. Topology is preserved: a hole stays a hole and
127
+ two parts never merge."""
128
+ before = float(outline.area)
129
+ tolerance = config.tolerance_m if config.tolerance_m is not None else block_diagonal_m
130
+ closing = config.closing_m or 0.0
131
+ if not config.enabled or outline.is_empty:
132
+ return outline, SmoothingRecord(False, 0.0, 0.0, before, before)
133
+
134
+ result = outline
135
+ if closing > 0:
136
+ result = result.buffer(closing, quad_segs=8).buffer(-closing, quad_segs=8)
137
+ if tolerance > 0:
138
+ result = result.simplify(tolerance, preserve_topology=True)
139
+
140
+ dropped, dropped_area, notes = 0, 0.0, []
141
+ if config.min_area_m2:
142
+ parts = list(result.geoms) if hasattr(result, "geoms") else [result]
143
+ kept = [p for p in parts if p.area >= config.min_area_m2]
144
+ dropped = len(parts) - len(kept)
145
+ dropped_area = float(sum(p.area for p in parts if p.area < config.min_area_m2))
146
+ result = shapely.union_all(kept) if kept else Polygon()
147
+ if dropped:
148
+ notes.append(f"{dropped} fragment(s) under {config.min_area_m2:g} m2 dropped ({dropped_area:,.0f} m2)")
149
+
150
+ return result, SmoothingRecord(True, tolerance, closing, before, float(result.area), dropped, dropped_area, notes)
151
+
152
+
153
+ def block_diagonal(blocks: pd.DataFrame) -> float:
154
+ return math.hypot(float(blocks["dx"].iloc[0]), float(blocks["dy"].iloc[0]))
155
+
156
+
157
+ def working_width(outline: BaseGeometry, tolerance: float = 0.01) -> float:
158
+ """How wide the floor is where it is widest: the diameter of the largest circle that fits inside, which is
159
+ what an excavator turning on it needs. Zero for an empty outline."""
160
+ if outline.is_empty:
161
+ return 0.0
162
+ return float(2.0 * shapely.maximum_inscribed_circle(outline, tolerance=tolerance).length)
163
+
164
+
165
+ def widen_to_min_width(outline: BaseGeometry, min_width: float) -> tuple[BaseGeometry, bool]:
166
+ """Widen every part of a floor that is narrower than the minimum mining width, evenly all round, until its
167
+ largest inscribed circle is exactly that wide. A part already wide enough is untouched. Returns the outline
168
+ and whether anything was widened.
169
+
170
+ Even widening is the smallest change that makes the part workable and the one that adds the least waste; the
171
+ material it adds is what the reconciliation reports as minimum-width dilution."""
172
+ parts = list(outline.geoms) if hasattr(outline, "geoms") else [outline]
173
+ widened, changed = [], False
174
+ for part in parts:
175
+ width = working_width(part)
176
+ if 0.0 < width < min_width:
177
+ radius = (min_width - width) / 2.0
178
+ # Round-buffer arcs and the maximum-inscribed-circle solver are both
179
+ # approximations. Solve against the same width oracle used by the
180
+ # validator; one analytic radius can otherwise miss the limit by a
181
+ # fraction of a millimetre (notably for triangular smoothed floors).
182
+ # Each shortfall step adds the whole width gap to the radius (about twice what an exact buffer
183
+ # would need) plus half the oracle tolerance: a half-gap step only closes ~70% of the gap per pass
184
+ # on a sharp triangle and could still be 1e-6 m short after 8 passes, and a gap below the
185
+ # inscribed-circle tolerance would otherwise stall. Worst overshoot is about 1-2 cm.
186
+ for _ in range(16):
187
+ candidate = part.buffer(radius, quad_segs=16)
188
+ measured = working_width(candidate)
189
+ if measured >= min_width:
190
+ part = candidate
191
+ break
192
+ radius += max(min_width - measured, 0.0) + 0.005
193
+ else:
194
+ raise RuntimeError(
195
+ f"could not widen floor to the {min_width:g} m minimum; measured {measured:g} m"
196
+ )
197
+ changed = True
198
+ widened.append(part)
199
+ return (shapely.union_all(widened) if changed else outline), changed
@@ -0,0 +1,114 @@
1
+ """
2
+ Moving a pit outline sideways by a distance that depends on which way the
3
+ wall faces.
4
+
5
+ The polygon problem the design engine rests on. A wall that varies by
6
+ sector needs a *variable-distance* offset, and the textbook trick of
7
+ shifting every vertex along its normal is exactly the naive version that
8
+ fails: at a convex corner the shifted edges cross and leave a loop, at a
9
+ concave one they pull apart, and a narrow neck can pinch the outline in
10
+ two. All of that is a property of the offset, not a bug to patch.
11
+
12
+ So the offset is defined by what it means instead of by vertex surgery.
13
+ Growing an outline by d(direction) is the union of the outline with a disk
14
+ swept along each edge, radius d at that edge's own facing; shrinking it is
15
+ removing those sweeps. Both are set operations, so the geometry engine —
16
+ not this module — decides what happens at corners, pinches and vanishing
17
+ islands, and the result is valid by construction. Round joins fall out of
18
+ the disks; a uniform distance reduces to shapely's own buffer and matches
19
+ it.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ from collections.abc import Callable
25
+
26
+ import numpy as np
27
+ import shapely
28
+ from shapely.geometry import LineString, Polygon
29
+ from shapely.geometry.base import BaseGeometry
30
+ from shapely.geometry.polygon import orient
31
+
32
+ from .parameters import SectorGeometry
33
+
34
+ # Segments per quarter circle when a disk is approximated. 16 keeps the
35
+ # rim within 0.5% of the true radius; the exported geometry is checked
36
+ # against exact circles in the tests.
37
+ QUAD_SEGS = 16
38
+ # No single sweep is longer than this, so the facing it samples is local.
39
+ MAX_SEGMENT_M = 10.0
40
+
41
+
42
+ def azimuth_profile(sectors: list[SectorGeometry], values: list[float], blend_deg: float) -> Callable[[np.ndarray], np.ndarray]:
43
+ """value(azimuth): each sector's own value across its arc, mixed
44
+ linearly through +/- blend_deg either side of a boundary so a change of
45
+ geotechnical domain is a ramp in the wall and not a step.
46
+
47
+ Azimuths are compass bearings, clockwise from north, and periodic."""
48
+ nodes_x, nodes_y = [], []
49
+ for sector, value in zip(sectors, values):
50
+ start = sector.azimuth_from % 360.0
51
+ length = (sector.azimuth_to - sector.azimuth_from) % 360.0 or 360.0
52
+ # A hair of inset even with no blend: two nodes at the same azimuth make the interpolation ambiguous.
53
+ inset = max(min(blend_deg, length / 2.0), 1e-6)
54
+ nodes_x += [(start + inset) % 360.0, (start + length - inset) % 360.0]
55
+ nodes_y += [value, value]
56
+ if len(sectors) == 1: # one sector all the way round is a constant
57
+ return lambda azimuth: np.full_like(np.asarray(azimuth, dtype=float), values[0])
58
+ order = np.argsort(nodes_x)
59
+ xs, ys = np.asarray(nodes_x)[order], np.asarray(nodes_y)[order]
60
+ return lambda azimuth: np.interp(np.asarray(azimuth, dtype=float) % 360.0, xs, ys, period=360.0)
61
+
62
+
63
+ def _segments(polygon: Polygon) -> tuple[list[LineString], np.ndarray]:
64
+ """The outline cut into short edges, each with the compass bearing of
65
+ its outward normal (away from the material, into a hole for an island)."""
66
+ lines: list[LineString] = []
67
+ bearings: list[float] = []
68
+ oriented = orient(polygon, sign=1.0) # material always on the left of travel, holes included
69
+ for ring in [oriented.exterior, *oriented.interiors]:
70
+ ring = shapely.segmentize(ring, MAX_SEGMENT_M)
71
+ xy = np.asarray(ring.coords)
72
+ for a, b in zip(xy[:-1], xy[1:]):
73
+ dx, dy = b[0] - a[0], b[1] - a[1]
74
+ if math.hypot(dx, dy) < 1e-9:
75
+ continue
76
+ lines.append(LineString([a, b]))
77
+ bearings.append(math.degrees(math.atan2(dy, -dx)) % 360.0) # normal (dy, -dx): east = 90, north = 0
78
+ return lines, np.asarray(bearings)
79
+
80
+
81
+ def offset(geometry: BaseGeometry, distance: float | Callable[[np.ndarray], np.ndarray], *, grow: bool,
82
+ join_style: str = "round", miter_limit: float = 2.0) -> BaseGeometry:
83
+ """Grow (or shrink) a polygon or multipolygon.
84
+
85
+ `distance` is a number, or a function of the outward-normal bearing.
86
+ Anything that is not a Polygon (an emptied result, a lone line left by a
87
+ pinch) is dropped: only area is a pit."""
88
+ if geometry.is_empty:
89
+ return geometry
90
+ if not callable(distance):
91
+ style = {"round": "round", "mitre": "mitre"}[join_style]
92
+ return _areal(geometry.buffer(distance if grow else -distance, quad_segs=QUAD_SEGS, join_style=style,
93
+ mitre_limit=miter_limit))
94
+
95
+ polygons = list(geometry.geoms) if hasattr(geometry, "geoms") else [geometry]
96
+ sweeps: list[BaseGeometry] = []
97
+ for polygon in polygons:
98
+ lines, bearings = _segments(polygon)
99
+ if not lines:
100
+ continue
101
+ radii = np.asarray(distance(bearings), dtype=float)
102
+ keep = radii > 0
103
+ sweeps.append(shapely.union_all(shapely.buffer(np.asarray(lines, dtype=object)[keep], radii[keep],
104
+ quad_segs=QUAD_SEGS)))
105
+ swept = shapely.union_all(sweeps) if sweeps else Polygon()
106
+ return _areal(geometry.union(swept) if grow else geometry.difference(swept))
107
+
108
+
109
+ def _areal(geometry: BaseGeometry) -> BaseGeometry:
110
+ """Keep only the area: polygons and multipolygons, nothing degenerate."""
111
+ if geometry.is_empty or geometry.geom_type in ("Polygon", "MultiPolygon"):
112
+ return geometry
113
+ parts = [g for g in getattr(geometry, "geoms", []) if g.geom_type in ("Polygon", "MultiPolygon") and not g.is_empty]
114
+ return shapely.union_all(parts) if parts else Polygon()
@@ -0,0 +1,336 @@
1
+ """
2
+ The numbers that describe one stretch of wall, and the angles they imply.
3
+
4
+ Everything here is closed-form and checked against a hand calculation in
5
+ the tests. Nothing touches a polygon: this module answers "what should the
6
+ wall be" so that the geometry modules only have to answer "where is it".
7
+
8
+ run = H / tan(face) horizontal width of one face
9
+ berm = criterion(H, face) catch bench, see BermConfig
10
+ IRA = atan( N H / (N run + berm) ) inter-ramp angle, N benches
11
+ between berms
12
+
13
+ The inter-ramp angle is the wall angle of a whole stack of benches with the
14
+ berms counted in and no ramp: it is what a geotechnical study gives an
15
+ allowable value for. The overall angle, which also counts the haul road,
16
+ needs a ramp and is computed where the ramp is built.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ from collections import Counter
22
+ from dataclasses import dataclass
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+ from ...config import DesignConfig
28
+ from .config import BermConfig, SectorConfig
29
+
30
+ # Modified Ritchie catch-bench width, W = 0.2 H + 4.5 m. The relation was
31
+ # fitted to benches of roughly 15-30 m; above that the width is an
32
+ # extrapolation of the fit and the design says so.
33
+ RITCHIE_A, RITCHIE_B = 0.2, 4.5
34
+ RITCHIE_H_MAX = 30.0
35
+
36
+ OK, WARNING, BLOCKED = "OK", "PERINGATAN", "BLOKIR"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class SectorGeometry:
41
+ """One sector's fully resolved wall geometry — no field left unset."""
42
+
43
+ name: str
44
+ azimuth_from: float
45
+ azimuth_to: float
46
+ bench_height: float
47
+ face_angle_deg: float
48
+ berm_every_n: int
49
+ berm_width: float
50
+ berm_method: str
51
+ ira_max_deg: float | None
52
+ osa_max_deg: float | None
53
+ bench_berms: tuple[float, ...] = ()
54
+ bench_ira_limits: tuple[float, ...] = ()
55
+
56
+ @property
57
+ def face_run(self) -> float:
58
+ return self.bench_height / math.tan(math.radians(self.face_angle_deg))
59
+
60
+ @property
61
+ def ira_deg(self) -> float:
62
+ return inter_ramp_angle_deg(self.bench_height, self.face_angle_deg, self.berm_width, self.berm_every_n)
63
+
64
+ def crest_offset(self, k: int) -> float:
65
+ """Horizontal distance of the crest of the k-th bench from the
66
+ anchor, k = 0 being the anchor bench itself:
67
+ k run + sum of catch berms up to step k."""
68
+ if self.bench_berms:
69
+ berm_sum = sum(
70
+ self.bench_berms[j]
71
+ for j in range(1, min(k + 1, len(self.bench_berms)))
72
+ if j % self.berm_every_n == 0
73
+ )
74
+ return k * self.face_run + berm_sum
75
+ return k * self.face_run + (k // self.berm_every_n) * self.berm_width
76
+
77
+ def toe_offset(self, k: int) -> float:
78
+ """Horizontal distance of that bench's toe: one face further in."""
79
+ return self.crest_offset(k) + self.face_run
80
+
81
+
82
+ def berm_width(berm: BermConfig, bench_height: float, face_angle_deg: float, berm_every_n: int,
83
+ overall_angle_deg: float) -> tuple[float, str | None]:
84
+ """Berm width by the configured criterion, and a note when the criterion
85
+ is being used outside the range it was derived for."""
86
+ if berm.method == "manual":
87
+ return float(berm.width), None
88
+ if berm.method == "ritchie":
89
+ note = None
90
+ if bench_height > RITCHIE_H_MAX:
91
+ note = (f"Ritchie berm criterion is fitted to benches up to about {RITCHIE_H_MAX:g} m; "
92
+ f"{bench_height:g} m is an extrapolation")
93
+ return RITCHIE_A * bench_height + RITCHIE_B, note
94
+ if berm.method == "ryan":
95
+ return berm.ryan_a * bench_height + berm.ryan_b, None
96
+ # slope: the berm that makes the inter-ramp angle equal the optimiser's
97
+ # overall angle, so design and optimiser agree on the wall.
98
+ run = bench_height / math.tan(math.radians(face_angle_deg))
99
+ stack_run = berm_every_n * bench_height / math.tan(math.radians(overall_angle_deg))
100
+ width = stack_run - berm_every_n * run
101
+ if width < 0:
102
+ raise ValueError(
103
+ f"face angle {face_angle_deg:g} deg is flatter than the overall slope {overall_angle_deg:g} deg: "
104
+ "no berm can make the benches honour it"
105
+ )
106
+ return width, None
107
+
108
+
109
+ def inter_ramp_angle_deg(bench_height: float, face_angle_deg: float, berm: float, berm_every_n: int) -> float:
110
+ run = bench_height / math.tan(math.radians(face_angle_deg))
111
+ return math.degrees(math.atan2(berm_every_n * bench_height, berm_every_n * run + berm))
112
+
113
+
114
+ def _domain_sectors_from_blocks(
115
+ blocks: pd.DataFrame,
116
+ in_pit: np.ndarray | None,
117
+ domain_angles: dict,
118
+ overall_angle_deg: float,
119
+ n_bins: int = 36,
120
+ ) -> list[tuple[SectorConfig, float]]:
121
+ """Map spatial block domains around the pit centre to contiguous azimuth sectors."""
122
+ sub = blocks.loc[in_pit] if in_pit is not None else blocks
123
+ if sub.empty:
124
+ return [(SectorConfig(name="Semua", azimuth_from=0.0, azimuth_to=360.0), overall_angle_deg)]
125
+
126
+ cx, cy = float(sub["x"].mean()), float(sub["y"].mean())
127
+ dx = sub["x"].to_numpy(dtype=float) - cx
128
+ dy = sub["y"].to_numpy(dtype=float) - cy
129
+ bearings = np.degrees(np.arctan2(dx, dy)) % 360.0
130
+ bin_step = 360.0 / n_bins
131
+ bin_ids = (bearings // bin_step).astype(int) % n_bins
132
+ domains = sub["domain"].to_numpy()
133
+
134
+ bin_labels: list[tuple[str, float] | None] = [None] * n_bins
135
+ for b in range(n_bins):
136
+ mask = bin_ids == b
137
+ if not mask.any():
138
+ continue
139
+ dom = Counter(domains[mask]).most_common(1)[0][0]
140
+ if dom in domain_angles:
141
+ bin_labels[b] = (str(dom), float(domain_angles[dom]))
142
+ else:
143
+ bin_labels[b] = ("Semua", overall_angle_deg)
144
+
145
+ populated = [i for i, v in enumerate(bin_labels) if v is not None]
146
+ if not populated:
147
+ return [(SectorConfig(name="Semua", azimuth_from=0.0, azimuth_to=360.0), overall_angle_deg)]
148
+ for b in range(n_bins):
149
+ if bin_labels[b] is None:
150
+ nearest = min(populated, key=lambda p: min((p - b) % n_bins, (b - p) % n_bins))
151
+ bin_labels[b] = bin_labels[nearest]
152
+
153
+ runs: list[list] = []
154
+ for b, label in enumerate(bin_labels):
155
+ assert label is not None
156
+ if runs and runs[-1][0] == label:
157
+ runs[-1][2] = (b + 1) * bin_step
158
+ else:
159
+ runs.append([label, b * bin_step, (b + 1) * bin_step])
160
+
161
+ if len(runs) > 1 and runs[0][0] == runs[-1][0]:
162
+ runs[0][1] = runs[-1][1]
163
+ runs.pop()
164
+
165
+ if len(runs) == 1:
166
+ label, _, _ = runs[0]
167
+ return [(SectorConfig(name=label[0], azimuth_from=0.0, azimuth_to=360.0), label[1])]
168
+
169
+ return [
170
+ (SectorConfig(name=label[0], azimuth_from=az_from % 360.0, azimuth_to=az_to % 360.0 or 360.0), label[1])
171
+ for label, az_from, az_to in runs
172
+ ]
173
+
174
+
175
+ def resolve_sectors(
176
+ design: DesignConfig,
177
+ overall_angle_deg: float,
178
+ domain_angles: dict | None = None,
179
+ blocks: pd.DataFrame | None = None,
180
+ in_pit: np.ndarray | None = None,
181
+ ) -> tuple[list[SectorGeometry], list[str]]:
182
+ """Every sector with each unset field filled from the design block.
183
+
184
+ A project with no sectors is one sector all the way round, so the
185
+ uniform pit is the same code path as the sectored one rather than a
186
+ second implementation that could drift from it. When no manual sectors
187
+ are configured and `domain_angles` is supplied, domains are mapped to
188
+ sectors with their respective overall slope angles."""
189
+ detail = design.detail
190
+ limits = detail.limits
191
+ if detail.sectors:
192
+ configured = [(s, overall_angle_deg) for s in detail.sectors]
193
+ elif domain_angles:
194
+ if blocks is not None and "domain" in blocks.columns:
195
+ configured = _domain_sectors_from_blocks(blocks, in_pit, domain_angles, overall_angle_deg)
196
+ else:
197
+ step = 360.0 / len(domain_angles)
198
+ configured = [
199
+ (SectorConfig(name=str(dom), azimuth_from=i * step, azimuth_to=(i + 1) * step), float(angle))
200
+ for i, (dom, angle) in enumerate(domain_angles.items())
201
+ ]
202
+ else:
203
+ configured = [(SectorConfig(name="Semua", azimuth_from=0.0, azimuth_to=360.0), overall_angle_deg)]
204
+
205
+ sectors, notes = [], []
206
+ for s, sector_overall in configured:
207
+ height = s.bench_height if s.bench_height is not None else design.bench_height
208
+ face = s.face_angle_deg if s.face_angle_deg is not None else design.bench_face_angle_deg
209
+ n = s.berm_every_n_benches if s.berm_every_n_benches is not None else detail.berm_every_n_benches
210
+ criterion = s.berm or detail.berm
211
+ width, note = berm_width(criterion, height, face, n, sector_overall)
212
+ if note:
213
+ notes.append(f"{s.name or 'sector'}: {note}")
214
+ sectors.append(SectorGeometry(
215
+ name=s.name or f"S{len(sectors) + 1}", azimuth_from=s.azimuth_from, azimuth_to=s.azimuth_to,
216
+ bench_height=height, face_angle_deg=face, berm_every_n=n, berm_width=width, berm_method=criterion.method,
217
+ ira_max_deg=s.ira_max_deg if s.ira_max_deg is not None else limits.ira_max_deg,
218
+ osa_max_deg=s.osa_max_deg if s.osa_max_deg is not None else limits.osa_max_deg,
219
+ ))
220
+ return sectors, notes
221
+
222
+
223
+ def stratify_sectors_by_elevation(
224
+ sectors: list[SectorGeometry],
225
+ blocks: pd.DataFrame,
226
+ in_pit: np.ndarray,
227
+ anchor: str,
228
+ anchor_rl: float,
229
+ floor_rl: float,
230
+ n_benches: int,
231
+ design: DesignConfig,
232
+ overall_angle_deg: float,
233
+ domain_angles: dict,
234
+ ) -> tuple[list[SectorGeometry], list[str]]:
235
+ """Populate elevation-stratified per-bench berms and domain limits on each sector when `domain_angles` is active."""
236
+ if not domain_angles or "domain" not in blocks.columns or n_benches < 1:
237
+ return sectors, []
238
+
239
+ detail = design.detail
240
+ sub_pit = blocks.loc[in_pit] if in_pit.any() else blocks
241
+ cx, cy = float(sub_pit["x"].mean()), float(sub_pit["y"].mean())
242
+ bx = sub_pit["x"].to_numpy(float) - cx
243
+ by = sub_pit["y"].to_numpy(float) - cy
244
+ radii = np.hypot(bx, by)
245
+ bearings = np.degrees(np.arctan2(bx, by)) % 360.0
246
+ dz = sub_pit["dz"].to_numpy(float)
247
+ z_mid = sub_pit["z"].to_numpy(float)
248
+ z_bot = z_mid - 0.5 * dz
249
+ z_top = z_mid + 0.5 * dz
250
+ doms = sub_pit["domain"].astype(str).to_numpy()
251
+
252
+ def _dominant_angle(mask: np.ndarray) -> float:
253
+ idx = np.flatnonzero(mask)
254
+ if len(idx) > 4:
255
+ # Pit wall sits at the outer rim of the level footprint in this azimuth sector
256
+ r_cut = float(np.quantile(radii[idx], 0.6))
257
+ rim = idx[radii[idx] >= r_cut]
258
+ if len(rim):
259
+ idx = rim
260
+ dom = Counter(doms[idx]).most_common(1)[0][0]
261
+ return float(domain_angles.get(dom, overall_angle_deg))
262
+
263
+ # Map sector name back to explicit SectorConfig berm override if supplied
264
+ cfg_by_name = {s.name: s for s in (detail.sectors or []) if s.name}
265
+ out_sectors: list[SectorGeometry] = []
266
+ notes: list[str] = []
267
+
268
+ for s in sectors:
269
+ span = (s.azimuth_to - s.azimuth_from) % 360.0 or 360.0
270
+ in_az = ((bearings - s.azimuth_from) % 360.0) < span
271
+ scfg = cfg_by_name.get(s.name)
272
+ criterion = (scfg.berm if scfg and scfg.berm is not None else detail.berm)
273
+
274
+ band_limits: list[float] = []
275
+ for j in range(n_benches):
276
+ if anchor == "crest":
277
+ z1 = anchor_rl - j * s.bench_height
278
+ z0 = z1 - s.bench_height
279
+ else:
280
+ z0 = floor_rl + j * s.bench_height
281
+ z1 = z0 + s.bench_height
282
+ in_z = (z_bot < z1 - 1e-9) & (z_top > z0 + 1e-9)
283
+ in_band_az = in_z & in_az
284
+ if in_band_az.any():
285
+ band_limits.append(_dominant_angle(in_band_az))
286
+ elif in_z.any():
287
+ band_limits.append(_dominant_angle(in_z))
288
+ else:
289
+ band_limits.append(float(overall_angle_deg))
290
+
291
+ berms = [0.0]
292
+ ira_limits = [band_limits[0]]
293
+ for j in range(1, n_benches):
294
+ gov_ang = min(band_limits[j - 1], band_limits[j])
295
+ w_j, note = berm_width(criterion, s.bench_height, s.face_angle_deg, s.berm_every_n, gov_ang)
296
+ if note and note not in notes:
297
+ notes.append(f"{s.name}: {note}")
298
+ berms.append(float(w_j))
299
+ ira_limits.append(gov_ang)
300
+
301
+ active_berms = [berms[j] for j in range(1, n_benches) if j % s.berm_every_n == 0]
302
+ rep_berm = float(np.mean(active_berms)) if active_berms else s.berm_width
303
+
304
+ out_sectors.append(
305
+ SectorGeometry(
306
+ name=s.name,
307
+ azimuth_from=s.azimuth_from,
308
+ azimuth_to=s.azimuth_to,
309
+ bench_height=s.bench_height,
310
+ face_angle_deg=s.face_angle_deg,
311
+ berm_every_n=s.berm_every_n,
312
+ berm_width=rep_berm,
313
+ berm_method=s.berm_method,
314
+ ira_max_deg=s.ira_max_deg,
315
+ osa_max_deg=s.osa_max_deg,
316
+ bench_berms=tuple(berms),
317
+ bench_ira_limits=tuple(ira_limits),
318
+ )
319
+ )
320
+ return out_sectors, notes
321
+
322
+
323
+ def angle_status(value_deg: float, limit_deg: float | None, warn_margin_deg: float) -> str:
324
+ """OK / warning / blocked for a wall angle against its allowable value.
325
+
326
+ A wall designed 0.1 degree inside its limit has no tolerance left for
327
+ the survey and the excavator, so the margin counts as a warning; a
328
+ wall over the limit is blocked. With no limit given there is nothing
329
+ to fail and the answer is OK."""
330
+ if limit_deg is None:
331
+ return OK
332
+ if value_deg > limit_deg:
333
+ return BLOCKED
334
+ if limit_deg - value_deg < warn_margin_deg:
335
+ return WARNING
336
+ return OK