Holley Kenward
Holley Kenward

Reputation: 21

Is there an issue with the metpy.units function?

I am trying to use a metpy.calc function however every time I attempt to assign units using metpy.units, it will not run. It will sit there and continue running for hours if I let it. The metpy function has worked perfectly fine for me in the past with the same dataset, but for some reason will no longer work. I have tried updating metpy and spyder and have also used multiple laptops to ensure it wasn't just occurring on one. I also tried the metpy.units two different ways. It runs using units('kg/kg') however won't actually assign the units to the array. Any thoughts on how to get this to work?

This is my code:

import numpy as np 
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import metpy
import metpy.calc as mpcalc
from metpy.units import units

f = Dataset('C:/Users/hkenward/Desktop/MS/cm1out.nc', mode = 'r', format="NETCDF4")
mrv=f.variables['qv'][:]
pt=f.variables['th'][:]
p=f.variables['prs'][:]
p=p/100.
mrv=mrv*units('kg/kg')
p=p * units.hPa
pt=pt*units.kelvin

e=mpcalc.vapor_pressure(p,mrv)
Td=mpcalc.dewpoint(e)
T=mpcalc.temperature_from_potential_temperature(p, pt)
Te=mpcalc.equivalent_potential_temperature(p, T, Td)

Upvotes: 2

Views: 1123

Answers (2)

DopplerShift
DopplerShift

Reputation: 5853

This is a compatibility issue with the Pint units framework (used by MetPy) and masked arrays (which is what netCDF4-python spits out by default). The easiest work around is to multiply your units on the left like:

pt = units.kelvin * pt

That makes everything work. Hopefully things like this will get better in the future by using things like Xarray.

Upvotes: 2

AKX
AKX

Reputation: 169338

metpy.calc and metpy.units work fine for me (here on Repl.it):

import metpy.calc as mc
from metpy.units import units

print(mc.density(
  pressure=(1500 * units.pascal),
  temperature=(26 * units.celsius),
  mixing=0.5,
))

outputs

0.014524968314683053 kilogram / meter ** 3

Upvotes: 1

Related Questions