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
pitopt/config.py ADDED
@@ -0,0 +1,530 @@
1
+ """
2
+ Project configuration: typed parameter sets loaded from a YAML file.
3
+
4
+ Defaults are conventional first-pass values. They are deliberately
5
+ generic — replace every one of them with your own study's numbers before
6
+ the result means anything.
7
+
8
+ Economics is expressed as a list of *products*. A single-metal deposit is
9
+ one product; a mineral sands or polymetallic deposit is several, each
10
+ with its own price, recovery and processing cost. That matters whenever
11
+ products differ in value: combining zircon at 1,400/t and ilmenite at
12
+ 280/t into one "grade" would price five tonnes of ilmenite as if it were
13
+ a tonne of zircon.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from dataclasses import dataclass, field, fields, is_dataclass
19
+ from numbers import Real
20
+ from pathlib import Path
21
+
22
+ import yaml
23
+
24
+ # The detailed design's own parameters live with its engine; they are re-exported here so ProjectConfig stays the
25
+ # one place a project is described, and existing `from pitopt.config import RampConfig` keeps working.
26
+ from .core.design_detail.config import ( # noqa: F401 — re-exported
27
+ BermConfig,
28
+ DesignDetailConfig,
29
+ DesignLimitsConfig,
30
+ GradeClassConfig,
31
+ RampConfig,
32
+ SectorConfig,
33
+ SmoothingConfig,
34
+ _azimuth_coverage,
35
+ validate_detail,
36
+ )
37
+
38
+ # Divisor converting a reported grade into a fraction.
39
+ GRADE_DIVISOR = {"mass_percent": 100.0, "volume_percent": 100.0, "ppm": 1_000_000.0, "gpt": 1_000_000.0,
40
+ "kgm3": 1_000.0, "gm3": 1_000_000.0}
41
+
42
+ # Grade bases measured against block volume rather than block mass.
43
+ VOLUME_BASES = {"volume_percent"}
44
+
45
+ # Metal mass per in-situ cubic metre; these do not use rock or product density.
46
+ VOLUMETRIC_MASS_BASES = {"kgm3", "gm3"}
47
+
48
+ # Sales units per tonne of product, for products priced in ounces or pounds.
49
+ UNITS_PER_TONNE = {"t": 1.0, "kg": 1_000.0, "g": 1_000_000.0, "oz": 32_150.7466, "lb": 2_204.62262}
50
+
51
+
52
+ @dataclass
53
+ class BlockModelConfig:
54
+ path: str
55
+ x_col: str = "X"
56
+ y_col: str = "Y"
57
+ z_col: str = "Z"
58
+ grade_col: str | None = None # convenience for a single-product model
59
+ density_col: str | None = None
60
+ crs: str | None = None
61
+ vertical_datum: str | None = None
62
+ dx_col: str | None = None
63
+ dy_col: str | None = None
64
+ dz_col: str | None = None
65
+ domain_col: str | None = None
66
+ class_col: str | None = None
67
+ # Actual material volume per block, where a reblocked model carries
68
+ # partly-filled cells at the topographic and lateral edges. The grid
69
+ # stays regular for precedence; only the volume valued is reduced.
70
+ volume_col: str | None = None
71
+ dx: float = 10.0
72
+ dy: float = 10.0
73
+ dz: float = 10.0
74
+ density: float = 2.7
75
+ include_classes: list = field(default_factory=list) # empty = keep all
76
+ ore_domains: list = field(default_factory=list) # empty = any domain may be ore
77
+ unestimated_action: str = "reject" # "reject" | "drop" | "zero_waste"
78
+ downgrade_measured_to_probable: bool = False # CP option: report Measured as Probable when modifying factors warrant
79
+
80
+
81
+ @dataclass
82
+ class SurfaceConfig:
83
+ """Topography. DXF is the industry interchange format; CSV XYZ is
84
+ accepted as a fallback for DEM/point-cloud dumps."""
85
+ path: str | None = None
86
+ format: str = "dxf"
87
+ x_col: str = "X"
88
+ y_col: str = "Y"
89
+ z_col: str = "Z"
90
+
91
+
92
+ @dataclass
93
+ class ProductConfig:
94
+ """
95
+ One saleable product.
96
+
97
+ processing_cost_per_tonne is charged per tonne of *this* product, not
98
+ per tonne of ore — the right basis for a mineral separation plant, and
99
+ the way a by-product that costs nothing extra to recover is expressed
100
+ (leave it at zero).
101
+
102
+ `density` is only used when grades are volume-based: it converts the
103
+ product's volume fraction into tonnes.
104
+
105
+ `price_unit` is the unit the price and the per-unit costs are quoted in:
106
+ t, kg, g, oz (troy) or lb — gold at 2,300 per oz, copper at 4.1 per lb.
107
+ Quantities are still carried in tonnes internally.
108
+ """
109
+ name: str
110
+ grade_col: str
111
+ price: float
112
+ price_unit: str = "t"
113
+ plant_recovery: float = 1.0
114
+ washing_recovery: float = 1.0
115
+ grade_basis: str | None = None
116
+ domain_recovery: dict = field(default_factory=dict)
117
+ density: float = 1.0
118
+ processing_cost_per_tonne: float = 0.0
119
+ selling_cost_per_tonne: float = 0.0
120
+ selling_cost_per_volume: float = 0.0
121
+
122
+ @property
123
+ def per_tonne(self) -> float:
124
+ """Factor turning a per-price_unit figure into a per-tonne one."""
125
+ return UNITS_PER_TONNE[self.price_unit]
126
+
127
+
128
+ @dataclass
129
+ class EconomicsConfig:
130
+ """
131
+ Costs are split by what they are charged on.
132
+
133
+ Mining and rehabilitation apply to every block taken out of the pit,
134
+ ore or waste — they are the price of removing material at all, and
135
+ they are what a waste block's negative value is made of. Processing
136
+ costs apply only to material routed to the plant.
137
+
138
+ Both per-tonne and per-volume forms exist because the industry quotes
139
+ both: hard rock works in dollars per tonne, alluvial and dredging
140
+ operations in dollars per cubic metre. They are summed, so use
141
+ whichever your study uses and leave the other at zero.
142
+ """
143
+ currency: str = "USD"
144
+ capex: float = 0.0
145
+ mining_mode: str = "selective" # "selective" | "total_mining"
146
+ grade_basis: str = "mass_percent"
147
+ mining_recovery: float = 1.0
148
+ dilution: float = 0.0
149
+ royalty_rate: float = 0.0
150
+
151
+ mining_cost_per_tonne: float = 0.0
152
+ mining_cost_per_volume: float = 0.0
153
+ # Haulage grows with depth: extra mining cost per tonne for every metre
154
+ # below the reference RL (default: top of the model). The usual
155
+ # depth-based mining cost adjustment for deep pits.
156
+ mining_cost_increment_per_m: float = 0.0
157
+ mining_cost_reference_rl: float | None = None
158
+ rehabilitation_cost_per_tonne: float = 0.0
159
+ rehabilitation_cost_per_volume: float = 0.0
160
+
161
+ processing_cost_per_tonne: float = 0.0
162
+ processing_cost_per_volume: float = 0.0
163
+ domain_processing_cost_per_tonne: dict = field(default_factory=dict)
164
+
165
+ products: list = field(default_factory=list)
166
+
167
+ def __post_init__(self) -> None:
168
+ self.products = [ProductConfig(**p) if isinstance(p, dict) else p for p in self.products]
169
+
170
+
171
+ @dataclass
172
+ class SlopeConfig:
173
+ """
174
+ Overall slope angle driving the precedence cone. `max_bench_levels`
175
+ caps how many benches up the cone template reaches. Leave it unset:
176
+ it is then sized from the block shape so the cone reaches three blocks
177
+ out, which keeps diagonal walls within a few degrees of the design
178
+ angle. A fixed small value is only safe for roughly cubic blocks — on
179
+ 10 x 10 x 1 m blocks, 8 levels let diagonal walls stand at 40 degrees
180
+ against a 30 degree design. `pitopt validate` prints the effective
181
+ angle in both directions.
182
+
183
+ `domain_angles` maps a value in the block model's domain column to
184
+ its own angle, for models with distinct geotechnical domains.
185
+ """
186
+ overall_angle_deg: float = 45.0
187
+ max_bench_levels: int | None = None
188
+ domain_angles: dict = field(default_factory=dict)
189
+ sector_angles: list = field(default_factory=list)
190
+
191
+
192
+ @dataclass
193
+ class DesignConfig:
194
+ """
195
+ Geotechnical bench geometry for the pit design surfaces.
196
+
197
+ bench_height, bench_face_angle_deg and berm_width define the wall;
198
+ together they give the overall slope. Leave berm_width unset and it is
199
+ sized so the benches honour slope.overall_angle_deg — the optimiser and
200
+ the design then agree on the slope. `cell` is the design grid spacing:
201
+ it must be finer than the berm for benches to show.
202
+
203
+ `detail` adds bench polygons, azimuth sectors and a ramp on top of
204
+ this geometry. It is off by default and inherits the bench height and
205
+ face angle from here, so the two never disagree about the wall.
206
+ """
207
+ enabled: bool = True
208
+ bench_height: float = 10.0
209
+ bench_face_angle_deg: float = 65.0
210
+ berm_width: float | None = None
211
+ cell: float = 2.5
212
+ detail: DesignDetailConfig = field(default_factory=DesignDetailConfig)
213
+
214
+ def __post_init__(self) -> None:
215
+ if isinstance(self.detail, dict):
216
+ self.detail = DesignDetailConfig(**self.detail)
217
+
218
+
219
+ @dataclass
220
+ class ShellsConfig:
221
+ """Revenue factors for the nested pit shells (Whittle
222
+ parameterisation, also written RAF — revenue adjustment factor): the
223
+ price is scaled by each factor and the pit re-solved, giving the
224
+ family of shells used for pushback choice and price sensitivity.
225
+ RF 1.0 is the ultimate pit."""
226
+ revenue_factors: list = field(
227
+ default_factory=lambda: [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2]
228
+ )
229
+
230
+
231
+ @dataclass
232
+ class ScheduleConfig:
233
+ """
234
+ Production scheduling over the shells.
235
+
236
+ `ore_capacity` is throughput per period on plant feed; `total_capacity`
237
+ optionally caps all material moved, which is what binds when stripping
238
+ rather than milling is the constraint. `basis` picks whether those
239
+ limits are read as tonnes or cubic metres — alluvial operations are
240
+ normally planned by volume.
241
+
242
+ Set either `ore_capacity` (the plant rate is given, mine life follows)
243
+ or `periods` (mine life is given, plant rate follows).
244
+ """
245
+ enabled: bool = False
246
+ ore_capacity: float = 0.0
247
+ # Alternative to ore_capacity: the number of periods the final pit
248
+ # should be mined over. The plant rate then follows from the pit
249
+ # (final pit feed / periods) — the "size the plant for an N-year life"
250
+ # case. When both are set, periods wins.
251
+ periods: int | None = None
252
+ period_years: float = 1.0 # length of one period, for discounting
253
+ total_capacity: float | None = None
254
+ basis: str = "tonnes" # tonnes | volume
255
+ discount_rate: float = 0.10
256
+ max_periods: int = 100
257
+ lom_limit_periods: int | None = None # optional permit / IUP horizon cap: stops scheduling cleanly after N periods
258
+ include_worst_case: bool = True
259
+
260
+
261
+ @dataclass
262
+ class FinalPitConfig:
263
+ """
264
+ How the final pit is chosen from the shells, once they have been
265
+ scheduled and discounted (the pit-by-pit analysis).
266
+
267
+ criterion NPV to maximise: best | worst | average (of best and
268
+ worst — the usual proxy for a schedule not yet built)
269
+ tolerance take the smallest shell within this fraction of the
270
+ maximum; the NPV curve is flat at the top, and the
271
+ smaller pit carries less capital and price risk
272
+ revenue_factor fix the final pit to one shell instead
273
+ """
274
+ criterion: str = "average"
275
+ tolerance: float = 0.01
276
+ revenue_factor: float | None = None
277
+
278
+
279
+ @dataclass
280
+ class PushbackConfig:
281
+ """
282
+ How the final pit is split into mining stages.
283
+
284
+ Pushbacks are stages, not periods: one pushback is usually mined over
285
+ one to two years and consecutive pushbacks overlap in time. Setting the
286
+ duration to one period gives one pushback per period if that is wanted.
287
+
288
+ shells a few of the nested shells become pushback boundaries, chosen
289
+ for the best specified-case NPV among the splits that are
290
+ practical: every pushback at least `min_tonnes` of material
291
+ (default: one period of plant feed) and no more than
292
+ `max_narrow` of its area narrower than `min_width`. Mined in
293
+ order with a lag of `bench_lag_m` between pushbacks.
294
+ strips panels `strip_width` wide advancing along the deposit with a
295
+ face sloping back at the wall angle — the practice for shallow
296
+ elongated deposits (mineral sands, alluvials). `strip_axis`
297
+ auto takes the long axis; `strip_direction` auto keeps the
298
+ direction with the higher NPV. The strips are the working
299
+ panels; consecutive strips are grouped into the pushbacks, cut
300
+ where each pushback carries an equal share of the plant feed.
301
+ """
302
+ method: str = "shells" # shells | strips
303
+ # How many pushbacks — three ways, first one set wins:
304
+ # count fixed number (manual)
305
+ # duration_years fixed duration per pushback (manual); count = life / duration
306
+ # "auto" duration from practice: target_duration_years
307
+ # (1-2 years is normal), lengthened if the pit is too
308
+ # deep to sink through in that time at
309
+ # max_vertical_advance_m per year
310
+ count: int | None = None
311
+ duration_years: object = "auto"
312
+ target_duration_years: float = 1.5
313
+ max_vertical_advance_m: float = 80.0
314
+ max_pushbacks: int = 6
315
+ min_tonnes: float | None = None
316
+ min_width: float = 50.0
317
+ max_narrow: float = 0.30
318
+ bench_lag_m: float = 10.0
319
+ strip_width: float = 50.0
320
+ strip_axis: str = "auto" # auto | x | y
321
+ strip_direction: str = "auto" # auto | forward | reverse
322
+
323
+
324
+ @dataclass
325
+ class SensitivityConfig:
326
+ """Price factors applied to a FIXED pit — distinct from the revenue
327
+ factors, which re-optimise the pit outline at each price."""
328
+ enabled: bool = False
329
+ price_factors: list = field(
330
+ default_factory=lambda: [0.7, 0.8, 0.9, 0.95, 1.0, 1.05, 1.1, 1.2, 1.3]
331
+ )
332
+ per_product: bool = True # also flex each product on its own
333
+
334
+
335
+ @dataclass
336
+ class OutputConfig:
337
+ directory: str = "outputs"
338
+ write_dxf: bool = True
339
+ dxf_cell: float | None = None # DXF facet size, m; None = the bench face run (max 5 m), never coarser than the design grid
340
+ write_results: bool = True # results.json + surfaces.npz, read by the UI
341
+ verify: bool = True # independent geometric checks on every run
342
+ write_plot: bool = True
343
+ write_excel: bool = True
344
+ write_pdf: bool = True
345
+ write_3d: bool = True # interactive HTML viewer (plotly)
346
+ dxf_surface_all_shells: bool = False
347
+ dxf_surface_periods: bool = True # end-of-period pit surfaces: the period mine plan
348
+ dxf_surface_pushbacks: bool = True # end-of-pushback surfaces
349
+ # Detailed design (design.detail): bench, ramp and sector DXF, session JSON, reconciliation CSV/XLSX.
350
+ write_design_detail: bool = True
351
+ design_shell_reference: bool = False # also draw the optimiser shell outline beside the design, for overlay in CAD
352
+
353
+
354
+ @dataclass
355
+ class ProjectConfig:
356
+ name: str
357
+ block_model: BlockModelConfig
358
+ surface: SurfaceConfig
359
+ economics: EconomicsConfig
360
+ slope: SlopeConfig
361
+ design: DesignConfig
362
+ shells: ShellsConfig
363
+ final_pit: FinalPitConfig
364
+ pushbacks: PushbackConfig
365
+ schedule: ScheduleConfig
366
+ sensitivity: SensitivityConfig
367
+ output: OutputConfig
368
+ # Where each parameter came from: {"economics.mining_cost_per_volume":
369
+ # {"source": "dokumen", "ref": "Parameter!C21"}, ...}. source is one of
370
+ # dokumen | asumsi | default; asumsi entries carry a mandatory note.
371
+ provenance: dict = field(default_factory=dict)
372
+ source: str | None = None
373
+
374
+ @classmethod
375
+ def from_yaml(cls, path: str) -> ProjectConfig:
376
+ with open(path) as f:
377
+ raw = yaml.safe_load(f)
378
+
379
+ base = Path(path).resolve().parent
380
+
381
+ def resolve(p: str | None) -> str | None:
382
+ if not p:
383
+ return p
384
+ return str((base / p).resolve()) if not Path(p).is_absolute() else p
385
+
386
+ bm = BlockModelConfig(**raw["block_model"])
387
+ bm.path = resolve(bm.path)
388
+
389
+ surf = SurfaceConfig(**raw.get("surface", {}))
390
+ surf.path = resolve(surf.path)
391
+
392
+ out = OutputConfig(**raw.get("output", {}))
393
+ out.directory = resolve(out.directory)
394
+
395
+ cfg = cls(
396
+ name=raw.get("project", {}).get("name", "pit"),
397
+ block_model=bm,
398
+ surface=surf,
399
+ economics=EconomicsConfig(**raw.get("economics", {})),
400
+ slope=SlopeConfig(**raw.get("slope", {})),
401
+ design=DesignConfig(**raw.get("design", {})),
402
+ shells=ShellsConfig(**raw.get("shells", {})),
403
+ final_pit=FinalPitConfig(**raw.get("final_pit", {})),
404
+ pushbacks=PushbackConfig(**raw.get("pushbacks", {})),
405
+ schedule=ScheduleConfig(**raw.get("schedule", {})),
406
+ sensitivity=SensitivityConfig(**raw.get("sensitivity", {})),
407
+ output=out,
408
+ provenance=raw.get("provenance", {}) or {},
409
+ source=str(Path(path).resolve()),
410
+ )
411
+ cfg.validate()
412
+ return cfg
413
+
414
+ def validate(self) -> None:
415
+ def finite(value, path):
416
+ if is_dataclass(value):
417
+ for item in fields(value):
418
+ finite(getattr(value, item.name), f"{path}.{item.name}")
419
+ elif isinstance(value, dict):
420
+ for key, item in value.items():
421
+ finite(item, f"{path}.{key}")
422
+ elif isinstance(value, (list, tuple)):
423
+ for index, item in enumerate(value):
424
+ finite(item, f"{path}[{index}]")
425
+ elif isinstance(value, Real) and not math.isfinite(value):
426
+ raise ValueError(f"{path} must be finite")
427
+
428
+ finite(self, "project")
429
+ e = self.economics
430
+ if e.grade_basis not in GRADE_DIVISOR:
431
+ raise ValueError(f"economics.grade_basis must be one of {list(GRADE_DIVISOR)}, got {e.grade_basis!r}")
432
+ if not e.products:
433
+ raise ValueError("economics.products must list at least one product")
434
+ if not 0 < e.mining_recovery <= 1:
435
+ raise ValueError("economics.mining_recovery must be in (0, 1]")
436
+ if not 0 <= e.dilution < 1:
437
+ raise ValueError("economics.dilution must be in [0, 1)")
438
+ if not 0 <= e.royalty_rate < 1:
439
+ raise ValueError("economics.royalty_rate must be in [0, 1)")
440
+
441
+ if not str(e.currency).strip():
442
+ raise ValueError("economics.currency must be a non-empty currency code")
443
+ if e.capex < 0:
444
+ raise ValueError("economics.capex must be >= 0")
445
+ if e.mining_mode not in ("selective", "total_mining"):
446
+ raise ValueError("economics.mining_mode must be 'selective' or 'total_mining'")
447
+ for dom, cost in (e.domain_processing_cost_per_tonne or {}).items():
448
+ if float(cost) < 0:
449
+ raise ValueError(f"economics.domain_processing_cost_per_tonne[{dom!r}] must be >= 0")
450
+
451
+ for p in e.products:
452
+ p_basis = p.grade_basis or e.grade_basis
453
+ if p_basis not in GRADE_DIVISOR:
454
+ raise ValueError(f"product {p.name}: grade_basis must be one of {list(GRADE_DIVISOR)}, got {p_basis!r}")
455
+ if p.price_unit not in UNITS_PER_TONNE:
456
+ raise ValueError(f"product {p.name}: price_unit must be one of {list(UNITS_PER_TONNE)}")
457
+ if not 0 < p.plant_recovery <= 1:
458
+ raise ValueError(f"product {p.name}: plant_recovery must be in (0, 1]")
459
+ if not 0 < p.washing_recovery <= 1:
460
+ raise ValueError(f"product {p.name}: washing_recovery must be in (0, 1]")
461
+ for dom, rec in (p.domain_recovery or {}).items():
462
+ if not 0 < float(rec) <= 1:
463
+ raise ValueError(f"product {p.name}: domain_recovery[{dom!r}] must be in (0, 1]")
464
+ if p.price <= 0:
465
+ raise ValueError(f"product {p.name}: price must be > 0")
466
+ if p_basis in VOLUME_BASES and p.density <= 0:
467
+ raise ValueError(f"product {p.name}: density must be > 0 for a volume-basis grade")
468
+
469
+ if not 0 < self.slope.overall_angle_deg < 90:
470
+ raise ValueError("slope.overall_angle_deg must be in (0, 90)")
471
+ for dom, ang in (self.slope.domain_angles or {}).items():
472
+ if not 0 < float(ang) < 90:
473
+ raise ValueError(f"slope.domain_angles[{dom!r}] must be in (0, 90)")
474
+ for sec in self.slope.sector_angles or []:
475
+ if not isinstance(sec, dict):
476
+ raise ValueError("slope.sector_angles entries must be mappings with azimuth_from, azimuth_to, angle_deg")
477
+ az_f = float(sec.get("azimuth_from", -1))
478
+ az_t = float(sec.get("azimuth_to", -1))
479
+ ang = float(sec.get("angle_deg", -1))
480
+ if not (0.0 <= az_f < 360.0 and 0.0 < az_t <= 360.0 and 0.0 < ang < 90.0):
481
+ raise ValueError("slope.sector_angles requires 0 <= azimuth_from < 360, 0 < azimuth_to <= 360, and 0 < angle_deg < 90")
482
+ if self.slope.max_bench_levels is not None and self.slope.max_bench_levels < 1:
483
+ raise ValueError("slope.max_bench_levels must be >= 1")
484
+ if not self.shells.revenue_factors:
485
+ raise ValueError("shells.revenue_factors must not be empty")
486
+ if any(rf <= 0 for rf in self.shells.revenue_factors):
487
+ raise ValueError("shells.revenue_factors must all be > 0")
488
+
489
+ if self.schedule.enabled:
490
+ if self.schedule.ore_capacity <= 0 and not self.schedule.periods:
491
+ raise ValueError("schedule needs ore_capacity > 0 or periods >= 1")
492
+ if self.schedule.periods is not None and self.schedule.periods < 1:
493
+ raise ValueError("schedule.periods must be >= 1")
494
+ if self.schedule.period_years <= 0:
495
+ raise ValueError("schedule.period_years must be > 0")
496
+ if self.schedule.basis not in ("tonnes", "volume"):
497
+ raise ValueError("schedule.basis must be 'tonnes' or 'volume'")
498
+ if not 0 <= self.schedule.discount_rate < 1:
499
+ raise ValueError("schedule.discount_rate must be in [0, 1)")
500
+ if self.schedule.lom_limit_periods is not None and self.schedule.lom_limit_periods < 1:
501
+ raise ValueError("schedule.lom_limit_periods must be >= 1")
502
+ d = self.design
503
+ if d.enabled:
504
+ if d.bench_height <= 0 or d.cell <= 0 or not 0 < d.bench_face_angle_deg < 90:
505
+ raise ValueError("design: bench_height and cell must be > 0, bench_face_angle_deg in (0, 90)")
506
+ if d.bench_face_angle_deg < self.slope.overall_angle_deg:
507
+ raise ValueError("design.bench_face_angle_deg cannot be flatter than slope.overall_angle_deg")
508
+ if d.berm_width is not None and d.berm_width < 0:
509
+ raise ValueError("design.berm_width must be >= 0")
510
+ if d.detail.enabled:
511
+ validate_detail(d.detail, d.bench_height)
512
+ if self.final_pit.criterion not in ("best", "worst", "average"):
513
+ raise ValueError("final_pit.criterion must be best, worst or average")
514
+ if not 0 <= self.final_pit.tolerance < 0.5:
515
+ raise ValueError("final_pit.tolerance must be in [0, 0.5)")
516
+ pb = self.pushbacks
517
+ if pb.method not in ("shells", "strips"):
518
+ raise ValueError("pushbacks.method must be 'shells' or 'strips'")
519
+ if pb.count is not None and pb.count < 1:
520
+ raise ValueError("pushbacks.count must be >= 1")
521
+ if pb.duration_years != "auto" and (pb.duration_years is None or float(pb.duration_years) <= 0):
522
+ raise ValueError("pushbacks.duration_years must be 'auto' or a number > 0")
523
+ if pb.target_duration_years <= 0 or pb.max_vertical_advance_m <= 0:
524
+ raise ValueError("pushbacks.target_duration_years and max_vertical_advance_m must be > 0")
525
+ if pb.max_pushbacks < 1 or pb.strip_width <= 0 or pb.min_width < 0 or pb.bench_lag_m < 0:
526
+ raise ValueError("pushbacks: max_pushbacks >= 1, strip_width > 0, min_width and bench_lag_m >= 0")
527
+ if pb.strip_axis not in ("auto", "x", "y") or pb.strip_direction not in ("auto", "forward", "reverse"):
528
+ raise ValueError("pushbacks.strip_axis must be auto|x|y and strip_direction auto|forward|reverse")
529
+ if self.sensitivity.enabled and not self.sensitivity.price_factors:
530
+ raise ValueError("sensitivity.price_factors must not be empty when sensitivity is enabled")
@@ -0,0 +1 @@
1
+ """Core optimisation: valuation, slope precedence, solve, shells, pit surface."""
pitopt/core/cancel.py ADDED
@@ -0,0 +1,32 @@
1
+ """
2
+ Cooperative cancellation (PRD F-RUN-4).
3
+
4
+ A long computation checks a token at points where stopping is safe and
5
+ raises `Cancelled` there; nothing is killed from outside, so no thread dies
6
+ holding a half-written file. The caller decides what to do with the partial
7
+ work — the UI discards it and leaves the previous result untouched.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import threading
12
+
13
+
14
+ class Cancelled(Exception):
15
+ """The user stopped the computation."""
16
+
17
+
18
+ class CancelToken:
19
+ def __init__(self) -> None:
20
+ self._stop = threading.Event()
21
+
22
+ def cancel(self) -> None:
23
+ self._stop.set()
24
+
25
+ @property
26
+ def cancelled(self) -> bool:
27
+ return self._stop.is_set()
28
+
29
+ def check(self) -> None:
30
+ """Raise `Cancelled` if a stop was requested. Call it where the state is consistent."""
31
+ if self._stop.is_set():
32
+ raise Cancelled()