Inverting a MetPy function #2871
-
MetPy provides from scipy.optimize import minimize_scalar
from metpy.units import units
import metpy.calc as mpcalc
def theta_e_to_temp(thetae, p):
"""Given thetae and p, find temperature"""
def objective(T):
return mpcalc.saturation_equivalent_potential_temperature(p, T) - thetae
solution = minimize_scalar(objective)
return solution
p = 850 * units('hPa')
T = 280 * units('degK')
thetae = mpcalc.saturation_equivalent_potential_temperature(p, T)
T = theta_e_to_temp(thetae, p) where I am hoping at the end, T (
I figured I'd ask here before devoting too much time to possibly reinventing the wheel. Is there an easy way around this? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Oops, I should be using |
Beta Was this translation helpful? Give feedback.
-
To make that work, inside |
Beta Was this translation helpful? Give feedback.
-
For completeness, here's the working code. import numpy as np
from scipy.optimize import root_scalar
from metpy.units import units
import metpy.calc as mpcalc
import metpy.interpolate as interp
def theta_e_to_temp(thetae, p):
"""Given thetae and p, find temperature"""
p1 = p * units('Pa')
def objective(T):
T1 = T * units('degK')
result = mpcalc.saturation_equivalent_potential_temperature(p1, T1).m_as('kelvin') - thetae
return result
solution = root_scalar(objective, bracket=(200, 365))
return solution
p = 85000 * units('Pa')
T = 280 * units('degK')
thetae = mpcalc.saturation_equivalent_potential_temperature(p, T)
print(thetae)
thetae = thetae.m
p = p.m
T = theta_e_to_temp(thetae, p)
print(T.root) |
Beta Was this translation helpful? Give feedback.
To make that work, inside
objective
you'd want to attach units before callingsaturation_equivalent_potential_temperature
, then convert back with.m_as('kelvin')
for the return.