Exercise 2.5
Unit Consistency Checker
One of the most common (and most dangerous) sources of error in petroleum engineering is mixed units: feeding a value in metres into a formula that expects feet, or kg/m³ into one that expects ppg. Real incidents have been traced to a single line of code that quietly multiplied wrong-unit numbers together.
Write hydrostatic_psi(mud_weight, tvd, mw_unit, depth_unit) that returns the hydrostatic pressure in psi. It must accept:
mw_unit: either"ppg"or"kg/m3"depth_unit: either"ft"or"m"
Use these conversions:
- 1 ppg = 119.826 kg/m³
- 1 ft = 0.3048 m
- Hydrostatic in oilfield units:
Convert both inputs to oilfield units internally, then return psi.
Reject unknown unit strings with ValueError. It is much better to crash on bad metadata than to compute a confidently wrong number.
> Think about it: verify that computing (10.0, 10000, "ppg", "ft") > and the same well expressed in SI units ((1198.26, 3048, "kg/m3", "m")) > produce the same psi within rounding tolerance. If they don't, your > conversion has a bug.
Stuck? Reveal hints one at a time — they progress from nudge to near-solution.
visibilityReveal reference solutionexpand_more
Try solving it yourself first — the hints walk you through it. The solution below is one valid approach; yours may differ and still be correct.
def hydrostatic_psi(mud_weight, tvd, mw_unit, depth_unit):
if mw_unit == "ppg":
mw_ppg = mud_weight
elif mw_unit == "kg/m3":
mw_ppg = mud_weight / 119.826
else:
raise ValueError(f"unknown mw_unit {mw_unit!r}; use 'ppg' or 'kg/m3'")
if depth_unit == "ft":
tvd_ft = tvd
elif depth_unit == "m":
tvd_ft = tvd / 0.3048
else:
raise ValueError(f"unknown depth_unit {depth_unit!r}; use 'ft' or 'm'")
return 0.052 * mw_ppg * tvd_ft
a = hydrostatic_psi(10.0, 10000, "ppg", "ft")
b = hydrostatic_psi(1198.26, 3048, "kg/m3", "m")
print(f"oilfield: {a:.2f} psi")
print(f"SI: {b:.2f} psi")
print(f"|Δ| : {abs(a - b):.4f} psi (should be < 1)")
lockCopying code is a Full Access feature.