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.
- pitopt/__init__.py +15 -0
- pitopt/__main__.py +7 -0
- pitopt/cli.py +207 -0
- pitopt/config.py +530 -0
- pitopt/core/__init__.py +1 -0
- pitopt/core/cancel.py +32 -0
- pitopt/core/design.py +475 -0
- pitopt/core/design_detail/__init__.py +5 -0
- pitopt/core/design_detail/angles.py +100 -0
- pitopt/core/design_detail/builder.py +230 -0
- pitopt/core/design_detail/config.py +416 -0
- pitopt/core/design_detail/footprint.py +199 -0
- pitopt/core/design_detail/offset.py +114 -0
- pitopt/core/design_detail/parameters.py +336 -0
- pitopt/core/design_detail/ramp.py +533 -0
- pitopt/core/design_detail/reconcile.py +210 -0
- pitopt/core/design_detail/stack.py +245 -0
- pitopt/core/design_detail/validate.py +198 -0
- pitopt/core/economics.py +245 -0
- pitopt/core/limits.py +136 -0
- pitopt/core/pitsurface.py +108 -0
- pitopt/core/planning.py +223 -0
- pitopt/core/precedence.py +486 -0
- pitopt/core/reblock.py +272 -0
- pitopt/core/reserves.py +339 -0
- pitopt/core/schedule.py +360 -0
- pitopt/core/sensitivity.py +100 -0
- pitopt/core/shells.py +100 -0
- pitopt/core/solver.py +182 -0
- pitopt/core/verify.py +310 -0
- pitopt/io/__init__.py +3 -0
- pitopt/io/blockmodel.py +210 -0
- pitopt/io/console.py +75 -0
- pitopt/io/datasets.py +204 -0
- pitopt/io/datfile.py +93 -0
- pitopt/io/design_export.py +360 -0
- pitopt/io/dxf.py +259 -0
- pitopt/io/excel.py +231 -0
- pitopt/io/pdf.py +376 -0
- pitopt/io/plot.py +66 -0
- pitopt/io/results.py +594 -0
- pitopt/io/viz.py +371 -0
- pitopt/mcp_server.py +632 -0
- pitopt/pipeline.py +1022 -0
- pitopt/provenance.py +62 -0
- pitopt/ui/__init__.py +3 -0
- pitopt/ui/design_service.py +412 -0
- pitopt/ui/mcp_controller.py +509 -0
- pitopt/ui/onboard.py +403 -0
- pitopt/ui/server.py +1145 -0
- pitopt/ui/staging.py +49 -0
- pitopt/ui/static/css/app.css +301 -0
- pitopt/ui/static/css/chat.css +657 -0
- pitopt/ui/static/css/design.css +62 -0
- pitopt/ui/static/fonts/IBMPlexMono-400.woff2 +0 -0
- pitopt/ui/static/fonts/IBMPlexMono-500.woff2 +0 -0
- pitopt/ui/static/fonts/IBMPlexMono-600.woff2 +0 -0
- pitopt/ui/static/fonts/IBMPlexSans-var.woff2 +0 -0
- pitopt/ui/static/fonts/OFL.txt +93 -0
- pitopt/ui/static/i18n/en.json +1229 -0
- pitopt/ui/static/img/design.webp +0 -0
- pitopt/ui/static/img/og-pitopt-2026-11.png +0 -0
- pitopt/ui/static/img/pitbypit.webp +0 -0
- pitopt/ui/static/img/pushback.webp +0 -0
- pitopt/ui/static/img/summary.webp +0 -0
- pitopt/ui/static/img/tutorial-marvin.webp +0 -0
- pitopt/ui/static/index.html +24 -0
- pitopt/ui/static/js/actions.js +4 -0
- pitopt/ui/static/js/app.js +223 -0
- pitopt/ui/static/js/charts.js +279 -0
- pitopt/ui/static/js/chat-panel.js +1210 -0
- pitopt/ui/static/js/commands.js +1025 -0
- pitopt/ui/static/js/csp-boot.js +48 -0
- pitopt/ui/static/js/design/core.js +194 -0
- pitopt/ui/static/js/design/plan.js +105 -0
- pitopt/ui/static/js/design/planview.js +49 -0
- pitopt/ui/static/js/design/section.js +80 -0
- pitopt/ui/static/js/design/three.js +45 -0
- pitopt/ui/static/js/design/ui.js +175 -0
- pitopt/ui/static/js/i18n.js +205 -0
- pitopt/ui/static/js/manage.js +119 -0
- pitopt/ui/static/js/modal.js +16 -0
- pitopt/ui/static/js/run.js +81 -0
- pitopt/ui/static/js/store.js +103 -0
- pitopt/ui/static/js/tutorial-guide.js +140 -0
- pitopt/ui/static/js/util.js +98 -0
- pitopt/ui/static/js/views/blocks.js +106 -0
- pitopt/ui/static/js/views/common.js +37 -0
- pitopt/ui/static/js/views/design_ekspor.js +69 -0
- pitopt/ui/static/js/views/design_generate.js +76 -0
- pitopt/ui/static/js/views/design_penampang.js +72 -0
- pitopt/ui/static/js/views/design_ramp.js +109 -0
- pitopt/ui/static/js/views/design_sektor.js +117 -0
- pitopt/ui/static/js/views/design_sumber.js +75 -0
- pitopt/ui/static/js/views/design_validasi.js +88 -0
- pitopt/ui/static/js/views/misc.js +128 -0
- pitopt/ui/static/js/views/params.js +189 -0
- pitopt/ui/static/js/views/pitbypit.js +65 -0
- pitopt/ui/static/js/views/plan.js +140 -0
- pitopt/ui/static/js/views/summary.js +94 -0
- pitopt/ui/static/js/views/upload.js +503 -0
- pitopt/ui/static/js/views/view3d.js +85 -0
- pitopt/ui/static/js/views/workspace.js +103 -0
- pitopt/ui/static/landing.html +487 -0
- pitopt-1.1.0.dist-info/METADATA +180 -0
- pitopt-1.1.0.dist-info/RECORD +112 -0
- pitopt-1.1.0.dist-info/WHEEL +5 -0
- pitopt-1.1.0.dist-info/entry_points.txt +3 -0
- pitopt-1.1.0.dist-info/licenses/LICENSE +661 -0
- pitopt-1.1.0.dist-info/licenses/NOTICE +19 -0
- pitopt-1.1.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +52 -0
- pitopt-1.1.0.dist-info/top_level.txt +1 -0
pitopt/core/economics.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Block valuation with destination selection, over one or many products.
|
|
3
|
+
|
|
4
|
+
Each block is valued twice — as plant feed and as waste — and takes the
|
|
5
|
+
better of the two. That `max(ore, waste)` step is what puts a marginal
|
|
6
|
+
cutoff into the pit optimisation: a block only carries plant cost if
|
|
7
|
+
processing it actually pays, so barren material inside the shell is
|
|
8
|
+
valued as waste. Valuing every block as ore instead charges processing on
|
|
9
|
+
material that would never see the plant, which understates the deposit
|
|
10
|
+
and shrinks the pit.
|
|
11
|
+
|
|
12
|
+
Mining and rehabilitation are charged on every block that comes out,
|
|
13
|
+
ore or waste. They are therefore *not* part of the ore-versus-waste
|
|
14
|
+
comparison — they cancel — which is why the cutoff below depends only on
|
|
15
|
+
processing, selling and revenue.
|
|
16
|
+
|
|
17
|
+
Revenue is scaled by `revenue_factor` (the Whittle / RAF parameterisation)
|
|
18
|
+
so the same routine drives every nested shell. The destination decision is
|
|
19
|
+
re-made at each factor, which is correct: a block that is marginal ore at
|
|
20
|
+
RF 1.0 is waste at RF 0.6.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
|
|
27
|
+
from ..config import GRADE_DIVISOR, VOLUME_BASES, VOLUMETRIC_MASS_BASES, EconomicsConfig, ProductConfig
|
|
28
|
+
|
|
29
|
+
ORE, WASTE = 1, 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _basis_of(product: ProductConfig, econ: EconomicsConfig) -> str:
|
|
33
|
+
return product.grade_basis or econ.grade_basis
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _plant_recovery_array(df: pd.DataFrame, product: ProductConfig) -> float | np.ndarray:
|
|
37
|
+
if product.domain_recovery and "domain" in df.columns:
|
|
38
|
+
mapping = {str(k): float(v) for k, v in product.domain_recovery.items()}
|
|
39
|
+
rec = df["domain"].astype(str).map(mapping).fillna(product.plant_recovery).to_numpy(dtype=float)
|
|
40
|
+
return rec * product.washing_recovery
|
|
41
|
+
return float(product.plant_recovery * product.washing_recovery)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _recovered_tonnes(
|
|
45
|
+
df: pd.DataFrame, product: ProductConfig, econ: EconomicsConfig, recovered_volume: np.ndarray, recovered_mass: np.ndarray
|
|
46
|
+
) -> np.ndarray:
|
|
47
|
+
"""Saleable tonnes of one product, after mining, washing, and domain/plant recovery."""
|
|
48
|
+
basis = _basis_of(product, econ)
|
|
49
|
+
grade_fraction = df[product.grade_col].to_numpy() / GRADE_DIVISOR[basis]
|
|
50
|
+
if basis in VOLUMETRIC_MASS_BASES:
|
|
51
|
+
in_situ = recovered_volume * grade_fraction
|
|
52
|
+
elif basis in VOLUME_BASES:
|
|
53
|
+
in_situ = recovered_volume * grade_fraction * product.density
|
|
54
|
+
else:
|
|
55
|
+
in_situ = recovered_mass * grade_fraction
|
|
56
|
+
return in_situ * _plant_recovery_array(df, product)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def product_margin(econ: EconomicsConfig, product: ProductConfig, revenue_factor: float = 1.0) -> float:
|
|
60
|
+
"""
|
|
61
|
+
Net margin per saleable tonne of one product: price less selling and
|
|
62
|
+
less that product's own processing cost.
|
|
63
|
+
|
|
64
|
+
A product's processing cost is netted off its price rather than
|
|
65
|
+
treated as a cost the grade has to cover, because it is charged per
|
|
66
|
+
tonne of product, not per tonne of ore. A product with a positive
|
|
67
|
+
margin adds value at any grade; one with a negative margin destroys
|
|
68
|
+
value however rich the block is.
|
|
69
|
+
"""
|
|
70
|
+
unit = product.per_tonne
|
|
71
|
+
net = (revenue_factor * product.price - product.selling_cost_per_tonne) * unit
|
|
72
|
+
if product.density > 0:
|
|
73
|
+
net -= product.selling_cost_per_volume / product.density
|
|
74
|
+
return net * (1.0 - econ.royalty_rate) - product.processing_cost_per_tonne * unit
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def marginal_cutoff_grades(econ: EconomicsConfig, revenue_factor: float = 1.0, rock_density: float = 1.0) -> dict:
|
|
78
|
+
"""
|
|
79
|
+
Grade at which each product alone would cover the *ore-level*
|
|
80
|
+
processing cost — the cost charged per tonne or cubic metre of plant
|
|
81
|
+
feed, irrespective of what is recovered from it.
|
|
82
|
+
|
|
83
|
+
Where there is no such ore-level cost, the cutoff is zero: any block
|
|
84
|
+
with a positive-margin product in it is worth processing, and the pit
|
|
85
|
+
limit is then set by whether revenue covers mining and rehabilitation,
|
|
86
|
+
not by grade. Mining and rehabilitation never enter the cutoff — they
|
|
87
|
+
are paid on ore and waste alike, so they cancel from the comparison.
|
|
88
|
+
|
|
89
|
+
With several products these are indicative only. The destination
|
|
90
|
+
decision is made on total block value, so a block below every single
|
|
91
|
+
product cutoff can still pay once the products are combined.
|
|
92
|
+
"""
|
|
93
|
+
feed_cost = econ.processing_cost_per_volume + rock_density * econ.processing_cost_per_tonne
|
|
94
|
+
feed_cost *= 1.0 + econ.dilution
|
|
95
|
+
|
|
96
|
+
cutoffs = {}
|
|
97
|
+
for product in econ.products:
|
|
98
|
+
basis = _basis_of(product, econ)
|
|
99
|
+
margin = product_margin(econ, product, revenue_factor)
|
|
100
|
+
if margin <= 0:
|
|
101
|
+
cutoffs[product.name] = float("inf")
|
|
102
|
+
continue
|
|
103
|
+
if feed_cost <= 0:
|
|
104
|
+
cutoffs[product.name] = 0.0
|
|
105
|
+
continue
|
|
106
|
+
|
|
107
|
+
payable_per_unit = (product.washing_recovery * product.plant_recovery) * margin
|
|
108
|
+
if basis in VOLUME_BASES:
|
|
109
|
+
payable_per_unit *= product.density
|
|
110
|
+
elif basis not in VOLUMETRIC_MASS_BASES:
|
|
111
|
+
payable_per_unit *= rock_density
|
|
112
|
+
|
|
113
|
+
cutoffs[product.name] = (feed_cost / payable_per_unit) * GRADE_DIVISOR[basis]
|
|
114
|
+
return cutoffs
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def breakeven_cutoff_grades(
|
|
118
|
+
econ: EconomicsConfig,
|
|
119
|
+
revenue_factor: float = 1.0,
|
|
120
|
+
rock_density: float = 1.0,
|
|
121
|
+
include_rehab: bool = True,
|
|
122
|
+
) -> dict:
|
|
123
|
+
"""Full break-even grade where one product covers mining + processing (+ rehabilitation if `include_rehab=True`).
|
|
124
|
+
|
|
125
|
+
Used in Competent Person reserve audits (e.g., total-mining / alluvial / mineral-sands reviews) to check
|
|
126
|
+
the full economic pit boundary grade with and without rehabilitation cost.
|
|
127
|
+
"""
|
|
128
|
+
c_vol = econ.mining_cost_per_volume + (econ.rehabilitation_cost_per_volume if include_rehab else 0.0)
|
|
129
|
+
c_t = econ.mining_cost_per_tonne + (econ.rehabilitation_cost_per_tonne if include_rehab else 0.0)
|
|
130
|
+
plant_per_insitu_m3 = econ.mining_recovery * (1.0 + econ.dilution) * (
|
|
131
|
+
econ.processing_cost_per_volume + rock_density * econ.processing_cost_per_tonne
|
|
132
|
+
)
|
|
133
|
+
total_cost_per_m3 = c_vol + rock_density * c_t + plant_per_insitu_m3
|
|
134
|
+
|
|
135
|
+
cutoffs = {}
|
|
136
|
+
for product in econ.products:
|
|
137
|
+
basis = _basis_of(product, econ)
|
|
138
|
+
margin = product_margin(econ, product, revenue_factor)
|
|
139
|
+
if margin <= 0:
|
|
140
|
+
cutoffs[product.name] = float("inf")
|
|
141
|
+
continue
|
|
142
|
+
if total_cost_per_m3 <= 0:
|
|
143
|
+
cutoffs[product.name] = 0.0
|
|
144
|
+
continue
|
|
145
|
+
eff_rec = econ.mining_recovery * product.washing_recovery * product.plant_recovery
|
|
146
|
+
payable_per_m3_unit = eff_rec * margin
|
|
147
|
+
if basis in VOLUME_BASES:
|
|
148
|
+
payable_per_m3_unit *= product.density
|
|
149
|
+
elif basis not in VOLUMETRIC_MASS_BASES:
|
|
150
|
+
payable_per_m3_unit *= rock_density
|
|
151
|
+
cutoffs[product.name] = (total_cost_per_m3 / payable_per_m3_unit) * GRADE_DIVISOR[basis]
|
|
152
|
+
return cutoffs
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def value_blocks(df: pd.DataFrame, econ: EconomicsConfig, revenue_factor: float = 1.0) -> pd.DataFrame:
|
|
156
|
+
"""
|
|
157
|
+
Adds tonnage/value columns to a standardised block model.
|
|
158
|
+
|
|
159
|
+
Columns added:
|
|
160
|
+
volume in-situ block volume
|
|
161
|
+
rock_tonnes in-situ tonnes (everything mined)
|
|
162
|
+
ore_tonnes diluted tonnes to the plant if the block is sent there
|
|
163
|
+
<NAME>_tonnes saleable tonnes of each product
|
|
164
|
+
revenue gross revenue if processed
|
|
165
|
+
value_ore block value if processed
|
|
166
|
+
value_waste block value if dumped (mining + rehabilitation only)
|
|
167
|
+
value max of the two — what the optimiser maximises
|
|
168
|
+
destination 1 = ore, 0 = waste
|
|
169
|
+
"""
|
|
170
|
+
out = df.copy()
|
|
171
|
+
|
|
172
|
+
# A reblocked model may carry partly-filled cells at the model edge;
|
|
173
|
+
# its own volume column is the material actually there, and the
|
|
174
|
+
# nominal cell size would overstate both tonnes and volumetric costs.
|
|
175
|
+
if "volume" in out.columns:
|
|
176
|
+
volume = out["volume"].to_numpy()
|
|
177
|
+
else:
|
|
178
|
+
volume = (out["dx"] * out["dy"] * out["dz"]).to_numpy()
|
|
179
|
+
rock_tonnes = volume * out["density"].to_numpy()
|
|
180
|
+
|
|
181
|
+
recovered_volume = volume * econ.mining_recovery
|
|
182
|
+
recovered_mass = rock_tonnes * econ.mining_recovery
|
|
183
|
+
ore_tonnes = recovered_mass * (1.0 + econ.dilution)
|
|
184
|
+
ore_volume = recovered_volume * (1.0 + econ.dilution)
|
|
185
|
+
|
|
186
|
+
revenue = np.zeros(len(out))
|
|
187
|
+
product_cost = np.zeros(len(out))
|
|
188
|
+
for product in econ.products:
|
|
189
|
+
tonnes = _recovered_tonnes(out, product, econ, recovered_volume, recovered_mass)
|
|
190
|
+
out[f"{product.name}_tonnes"] = tonnes
|
|
191
|
+
|
|
192
|
+
unit = product.per_tonne
|
|
193
|
+
gross = tonnes * revenue_factor * product.price * unit
|
|
194
|
+
selling = tonnes * product.selling_cost_per_tonne * unit
|
|
195
|
+
if product.density > 0:
|
|
196
|
+
selling += (tonnes / product.density) * product.selling_cost_per_volume
|
|
197
|
+
|
|
198
|
+
revenue += (gross - selling) * (1.0 - econ.royalty_rate)
|
|
199
|
+
product_cost += tonnes * product.processing_cost_per_tonne * unit
|
|
200
|
+
|
|
201
|
+
if econ.domain_processing_cost_per_tonne and "domain" in out.columns:
|
|
202
|
+
dom_proc = (
|
|
203
|
+
out["domain"]
|
|
204
|
+
.astype(str)
|
|
205
|
+
.map({str(k): float(v) for k, v in econ.domain_processing_cost_per_tonne.items()})
|
|
206
|
+
.fillna(econ.processing_cost_per_tonne)
|
|
207
|
+
.to_numpy(dtype=float)
|
|
208
|
+
)
|
|
209
|
+
else:
|
|
210
|
+
dom_proc = econ.processing_cost_per_tonne
|
|
211
|
+
plant_cost = ore_tonnes * dom_proc + ore_volume * econ.processing_cost_per_volume
|
|
212
|
+
mining_cost = rock_tonnes * econ.mining_cost_per_tonne + volume * econ.mining_cost_per_volume
|
|
213
|
+
if econ.mining_cost_increment_per_m:
|
|
214
|
+
reference = econ.mining_cost_reference_rl
|
|
215
|
+
if reference is None:
|
|
216
|
+
reference = float((out["z"] + out["dz"] / 2).max())
|
|
217
|
+
depth = np.clip(reference - out["z"].to_numpy(), 0.0, None)
|
|
218
|
+
mining_cost = mining_cost + rock_tonnes * econ.mining_cost_increment_per_m * depth
|
|
219
|
+
rehab_cost = rock_tonnes * econ.rehabilitation_cost_per_tonne + volume * econ.rehabilitation_cost_per_volume
|
|
220
|
+
fixed_cost = mining_cost + rehab_cost
|
|
221
|
+
|
|
222
|
+
value_ore = revenue - product_cost - plant_cost - fixed_cost
|
|
223
|
+
value_waste = -fixed_cost
|
|
224
|
+
|
|
225
|
+
# Material outside the ore domains cannot be routed to the plant at
|
|
226
|
+
# all, whatever it assays — overburden and bedrock are not feed.
|
|
227
|
+
if "is_ore_domain" in out.columns:
|
|
228
|
+
eligible = out["is_ore_domain"].to_numpy(dtype=bool)
|
|
229
|
+
value_ore = np.where(~eligible, value_waste, value_ore)
|
|
230
|
+
else:
|
|
231
|
+
eligible = np.ones(len(out), dtype=bool)
|
|
232
|
+
|
|
233
|
+
out["volume"] = volume
|
|
234
|
+
out["rock_tonnes"] = rock_tonnes
|
|
235
|
+
out["ore_tonnes"] = ore_tonnes
|
|
236
|
+
out["revenue"] = revenue
|
|
237
|
+
out["value_ore"] = value_ore
|
|
238
|
+
out["value_waste"] = value_waste
|
|
239
|
+
if econ.mining_mode == "total_mining":
|
|
240
|
+
out["value"] = np.where(eligible, value_ore, value_waste)
|
|
241
|
+
out["destination"] = np.where(eligible, ORE, WASTE)
|
|
242
|
+
else:
|
|
243
|
+
out["value"] = np.maximum(value_ore, value_waste)
|
|
244
|
+
out["destination"] = np.where(value_ore > value_waste, ORE, WASTE)
|
|
245
|
+
return out
|
pitopt/core/limits.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Refuse a run that cannot fit in memory, before it starts, with a message that says what to change.
|
|
3
|
+
|
|
4
|
+
The maximum-closure solve holds one graph edge per precedence arc. Measured on a 230,164-block porphyry model
|
|
5
|
+
(10.3 million arcs at 35-45 degrees) the process peaked at 9.5 GB (26 minutes for the whole run, about two
|
|
6
|
+
minutes per shell solve). Without this check a model that is too big for the machine ends in the kernel
|
|
7
|
+
killing the process — no message, no results — so the estimate is made from the block count and the slope
|
|
8
|
+
template alone, before any large array exists.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import ctypes
|
|
13
|
+
import os
|
|
14
|
+
import platform
|
|
15
|
+
import re
|
|
16
|
+
import subprocess
|
|
17
|
+
|
|
18
|
+
BYTES_PER_ARC = 620 # NetworkX DiGraph edge tuples: 9.5 GB / 15.1 M measured on 230,164-block model
|
|
19
|
+
# SciPy CSR + csgraph.maximum_flow: arcs int64 (16 B) + COO rows/cols/caps (24 B) + CSR data/indices (12 B)
|
|
20
|
+
# + Dinic residual graph & flow/residual CSRs (~88 B) ≈ 140 B/arc (75,696 blocks / ~5.5M arcs ≈ 1.07 GB vs 0.82 GB RSS).
|
|
21
|
+
BYTES_PER_ARC_SCIPY = 140
|
|
22
|
+
BYTES_PER_BLOCK = 4_000
|
|
23
|
+
SAFETY = 0.85 # leave the rest for the OS, the UI server and the reports
|
|
24
|
+
|
|
25
|
+
_BYTES_PER_ARC_BY_METHOD = {
|
|
26
|
+
"preflow_push": BYTES_PER_ARC,
|
|
27
|
+
"networkx": BYTES_PER_ARC,
|
|
28
|
+
"scipy_dinic": BYTES_PER_ARC_SCIPY,
|
|
29
|
+
"edmonds_karp": BYTES_PER_ARC_SCIPY,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ModelTooLarge(ValueError):
|
|
34
|
+
"""The precedence graph would not fit in the memory available."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _macos_available_memory_bytes() -> int | None:
|
|
38
|
+
"""Available (free + inactive + speculative + purgeable) RAM on macOS."""
|
|
39
|
+
try:
|
|
40
|
+
out = subprocess.check_output(["vm_stat"], text=True, timeout=2)
|
|
41
|
+
page_match = re.search(r"page size of (\d+) bytes", out)
|
|
42
|
+
page_size = int(page_match.group(1)) if page_match else 4096
|
|
43
|
+
pages = 0
|
|
44
|
+
for key in ("Pages free", "Pages inactive", "Pages speculative", "Pages purgeable"):
|
|
45
|
+
m = re.search(rf"^{re.escape(key)}:\s+(\d+)\.", out, re.M)
|
|
46
|
+
if m:
|
|
47
|
+
pages += int(m.group(1))
|
|
48
|
+
free = pages * page_size if pages > 0 else 0
|
|
49
|
+
except Exception:
|
|
50
|
+
free = 0
|
|
51
|
+
try:
|
|
52
|
+
total = int(os.sysconf("SC_PHYS_PAGES")) * int(os.sysconf("SC_PAGE_SIZE"))
|
|
53
|
+
except (ValueError, OSError, AttributeError):
|
|
54
|
+
return free or None
|
|
55
|
+
# macOS compresses and swaps instead of killing a process, and vm_stat's "free" is only the instantaneous
|
|
56
|
+
# slack (it was 1.4 GB on a busy 8 GB Mac for a run that peaks at 1.55 GB). Judge against half of physical RAM.
|
|
57
|
+
return max(free, total // 2)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _windows_available_memory_bytes() -> int | None:
|
|
61
|
+
"""Available physical RAM on native Windows via GlobalMemoryStatusEx."""
|
|
62
|
+
try:
|
|
63
|
+
class MEMORYSTATUSEX(ctypes.Structure):
|
|
64
|
+
_fields_ = [
|
|
65
|
+
("dwLength", ctypes.c_ulong),
|
|
66
|
+
("dwMemoryLoad", ctypes.c_ulong),
|
|
67
|
+
("ullTotalPhys", ctypes.c_ulonglong),
|
|
68
|
+
("ullAvailPhys", ctypes.c_ulonglong),
|
|
69
|
+
("ullTotalPageFile", ctypes.c_ulonglong),
|
|
70
|
+
("ullAvailPageFile", ctypes.c_ulonglong),
|
|
71
|
+
("ullTotalVirtual", ctypes.c_ulonglong),
|
|
72
|
+
("ullAvailVirtual", ctypes.c_ulonglong),
|
|
73
|
+
("ullAvailExtendedVirtual", ctypes.c_ulonglong),
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
stat = MEMORYSTATUSEX()
|
|
77
|
+
stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
|
|
78
|
+
if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)): # type: ignore[attr-defined]
|
|
79
|
+
return int(stat.ullAvailPhys)
|
|
80
|
+
except Exception:
|
|
81
|
+
pass
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def available_memory_bytes() -> int | None:
|
|
86
|
+
"""Available physical memory across Linux/WSL (/proc/meminfo), macOS (vm_stat), and Windows."""
|
|
87
|
+
try:
|
|
88
|
+
with open("/proc/meminfo") as f:
|
|
89
|
+
for line in f:
|
|
90
|
+
if line.startswith("MemAvailable:"):
|
|
91
|
+
return int(line.split()[1]) * 1024
|
|
92
|
+
except OSError:
|
|
93
|
+
pass
|
|
94
|
+
sys_name = platform.system()
|
|
95
|
+
if sys_name == "Darwin":
|
|
96
|
+
return _macos_available_memory_bytes()
|
|
97
|
+
if sys_name == "Windows":
|
|
98
|
+
return _windows_available_memory_bytes()
|
|
99
|
+
try:
|
|
100
|
+
return int(os.sysconf("SC_AVPHYS_PAGES")) * int(os.sysconf("SC_PAGE_SIZE"))
|
|
101
|
+
except (ValueError, OSError, AttributeError):
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def estimate_solver_bytes(n_blocks: int, arcs_upper_bound: int, method: str = "preflow_push") -> int:
|
|
106
|
+
bytes_per_arc = _BYTES_PER_ARC_BY_METHOD.get(method)
|
|
107
|
+
if bytes_per_arc is None:
|
|
108
|
+
raise ValueError(f"unknown solver method {method!r}; expected one of {tuple(_BYTES_PER_ARC_BY_METHOD)}")
|
|
109
|
+
return int(arcs_upper_bound) * bytes_per_arc + int(n_blocks) * BYTES_PER_BLOCK
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def check_solver_memory(
|
|
113
|
+
n_blocks: int,
|
|
114
|
+
arcs_upper_bound: int,
|
|
115
|
+
available: int | None = None,
|
|
116
|
+
method: str = "preflow_push",
|
|
117
|
+
) -> dict:
|
|
118
|
+
"""Raises ModelTooLarge when the estimate exceeds what is free; returns the estimate otherwise.
|
|
119
|
+
Set PITOPT_SKIP_MEMORY_CHECK=1 to run anyway (for example with swap you know is large)."""
|
|
120
|
+
need = estimate_solver_bytes(n_blocks, arcs_upper_bound, method=method)
|
|
121
|
+
have = available if available is not None else available_memory_bytes()
|
|
122
|
+
info = {
|
|
123
|
+
"blocks": int(n_blocks),
|
|
124
|
+
"arcs_upper_bound": int(arcs_upper_bound),
|
|
125
|
+
"method": method,
|
|
126
|
+
"need_gb": need / 1e9,
|
|
127
|
+
"available_gb": None if have is None else have / 1e9,
|
|
128
|
+
}
|
|
129
|
+
if have is not None and need > SAFETY * have and not os.environ.get("PITOPT_SKIP_MEMORY_CHECK"):
|
|
130
|
+
raise ModelTooLarge(
|
|
131
|
+
f"Model too large for this machine: {n_blocks:,} blocks and up to {arcs_upper_bound:,} precedence arcs "
|
|
132
|
+
f"needs about {need / 1e9:.1f} GB, {have / 1e9:.1f} GB is available. "
|
|
133
|
+
"Reduce it: reblock to a larger block (doubling the block size in all three directions cuts the "
|
|
134
|
+
"blocks eight-fold), clip the model to the area around the deposit, or run on a machine with more memory."
|
|
135
|
+
)
|
|
136
|
+
return info
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Turn a solved pit into a surface.
|
|
3
|
+
|
|
4
|
+
The deliverable a planner or surveyor can actually use is a surface, not
|
|
5
|
+
a column of booleans: for every x/y column the pit surface sits at the
|
|
6
|
+
base of the lowest block taken out of that column, and reverts to
|
|
7
|
+
original topography wherever nothing was mined. Walls appear on their own
|
|
8
|
+
as the step between neighbouring columns, and the surface ties into the
|
|
9
|
+
natural ground at the crest, so it can be draped straight over the topo
|
|
10
|
+
in any design package.
|
|
11
|
+
|
|
12
|
+
Grid resolution is the block size — the surface is as detailed as the
|
|
13
|
+
model that produced it, and no smoother. Bench faces will look blocky at
|
|
14
|
+
coarse block sizes; that is honest, not an artifact to be polished out
|
|
15
|
+
before a design is put on it.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Callable
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import pandas as pd
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def pit_surface_grid(
|
|
26
|
+
blocks: pd.DataFrame, in_pit: np.ndarray, elevation: Callable | None = None
|
|
27
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
28
|
+
"""
|
|
29
|
+
Returns (xs, ys, grid_z): 1-D node coordinates and the (len(xs), len(ys))
|
|
30
|
+
elevation grid, NaN where there is neither topography nor model.
|
|
31
|
+
"""
|
|
32
|
+
dx = float(blocks["dx"].iloc[0])
|
|
33
|
+
dy = float(blocks["dy"].iloc[0])
|
|
34
|
+
dz = float(blocks["dz"].iloc[0])
|
|
35
|
+
|
|
36
|
+
gi, gj = blocks["gi"].to_numpy(), blocks["gj"].to_numpy()
|
|
37
|
+
gi_values = np.arange(gi.min(), gi.max() + 1)
|
|
38
|
+
gj_values = np.arange(gj.min(), gj.max() + 1)
|
|
39
|
+
# true centre coordinates: the lowest column's centre plus whole blocks (never `index * size`, which
|
|
40
|
+
# moves the surface by up to half a block whenever the model origin is not a multiple of the block size)
|
|
41
|
+
x_first = float(blocks.loc[blocks["gi"] == gi.min(), "x"].min())
|
|
42
|
+
y_first = float(blocks.loc[blocks["gj"] == gj.min(), "y"].min())
|
|
43
|
+
xs, ys = x_first + (gi_values - gi.min()) * dx, y_first + (gj_values - gj.min()) * dy
|
|
44
|
+
|
|
45
|
+
grid_z = np.full((len(gi_values), len(gj_values)), np.nan)
|
|
46
|
+
|
|
47
|
+
if elevation is not None:
|
|
48
|
+
mesh_x, mesh_y = np.meshgrid(xs, ys, indexing="ij")
|
|
49
|
+
grid_z = np.asarray(elevation(mesh_x.ravel(), mesh_y.ravel()), dtype=float).reshape(mesh_x.shape)
|
|
50
|
+
else:
|
|
51
|
+
tops = blocks.groupby(["gi", "gj"])["z"].max() + dz / 2.0
|
|
52
|
+
for (i, j), top in tops.items():
|
|
53
|
+
grid_z[i - gi_values[0], j - gj_values[0]] = top
|
|
54
|
+
|
|
55
|
+
if in_pit.any():
|
|
56
|
+
floors = blocks[in_pit].groupby(["gi", "gj"])["z"].min() - dz / 2.0
|
|
57
|
+
idx_i = floors.index.get_level_values(0).to_numpy() - gi_values[0]
|
|
58
|
+
idx_j = floors.index.get_level_values(1).to_numpy() - gj_values[0]
|
|
59
|
+
grid_z[idx_i, idx_j] = floors.to_numpy()
|
|
60
|
+
|
|
61
|
+
return xs, ys, grid_z
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def check_pit_closure(blocks: pd.DataFrame, in_pit: np.ndarray) -> dict:
|
|
65
|
+
"""
|
|
66
|
+
Does the pit close inside the block model, or run into its edges?
|
|
67
|
+
|
|
68
|
+
A pit that reaches the bottom bench or a lateral limit of the model is
|
|
69
|
+
constrained by where the model stops, not by economics — the true
|
|
70
|
+
optimum lies outside the data. That makes the tonnes and the pit
|
|
71
|
+
outline understatements, and it is a modelling problem to fix before
|
|
72
|
+
the result is used, not a result to report. Standard practice is to
|
|
73
|
+
extend the model (even with barren blocks) until the pit closes
|
|
74
|
+
within it.
|
|
75
|
+
"""
|
|
76
|
+
if not in_pit.any():
|
|
77
|
+
return {"closed": True, "on_bottom": 0, "on_sides": 0}
|
|
78
|
+
|
|
79
|
+
pit = blocks[in_pit]
|
|
80
|
+
on_bottom = int((pit["bench"] == blocks["bench"].min()).sum())
|
|
81
|
+
on_sides = int(
|
|
82
|
+
(
|
|
83
|
+
(pit["gi"] == blocks["gi"].min())
|
|
84
|
+
| (pit["gi"] == blocks["gi"].max())
|
|
85
|
+
| (pit["gj"] == blocks["gj"].min())
|
|
86
|
+
| (pit["gj"] == blocks["gj"].max())
|
|
87
|
+
).sum()
|
|
88
|
+
)
|
|
89
|
+
return {"closed": on_bottom == 0 and on_sides == 0, "on_bottom": on_bottom, "on_sides": on_sides}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def pit_depth_stats(blocks: pd.DataFrame, in_pit: np.ndarray, elevation: Callable | None = None) -> dict:
|
|
93
|
+
"""Crest/toe elevations and maximum depth — the numbers that get
|
|
94
|
+
quoted about a pit before anything else."""
|
|
95
|
+
if not in_pit.any():
|
|
96
|
+
return {"crest_rl": float("nan"), "toe_rl": float("nan"), "max_depth": 0.0}
|
|
97
|
+
|
|
98
|
+
pit = blocks[in_pit]
|
|
99
|
+
dz = float(blocks["dz"].iloc[0])
|
|
100
|
+
toe_rl = float(pit["z"].min() - dz / 2.0)
|
|
101
|
+
|
|
102
|
+
if elevation is not None:
|
|
103
|
+
crest = np.asarray(elevation(pit["x"].to_numpy(), pit["y"].to_numpy()), dtype=float)
|
|
104
|
+
crest_rl = float(np.nanmax(crest))
|
|
105
|
+
else:
|
|
106
|
+
crest_rl = float(pit["z"].max() + dz / 2.0)
|
|
107
|
+
|
|
108
|
+
return {"crest_rl": crest_rl, "toe_rl": toe_rl, "max_depth": crest_rl - toe_rl}
|