Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_wind_comps_scalar():
"""Test wind components calculation with scalars."""
u, v = wind_components(8 * units('m/s'), 150 * units.deg)
assert_almost_equal(u, -4 * units('m/s'), 3)
assert_almost_equal(v, 6.9282 * units('m/s'), 3)
# Drop any rows with all NaN values for T, Td, winds
df = df.dropna(subset=('temperature', 'dewpoint', 'direction', 'speed'
), how='all').reset_index(drop=True)
##########################################################################
# We will pull the data out of the example dataset into individual variables and
# assign units.
p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)
##########################################################################
# Thermodynamic Calculations
# --------------------------
#
# Often times we will want to calculate some thermodynamic parameters of a
# sounding. The MetPy calc module has many such calculations already implemented!
#
# * **Lifting Condensation Level (LCL)** - The level at which an air parcel's
# relative humidity becomes 100% when lifted along a dry adiabatic path.
# * **Parcel Path** - Path followed by a hypothetical parcel of air, beginning
# at the surface temperature/pressure and rising dry adiabatically until
# reaching the LCL, then rising moist adiabatially.
# Calculate the LCL
lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
skiprows=5, usecols=[0, 1, 2, 3, 6, 7], names=col_names)
# Drop any rows with all NaN values for T, Td, winds
df = df.dropna(subset=('temperature', 'dewpoint', 'direction', 'speed'
), how='all').reset_index(drop=True)
###########################################
# We will pull the data out of the example dataset into individual variables and
# assign units.
p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)
###########################################
# Create a new figure. The dimensions here give a good aspect ratio
fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 630, 80, size='large')
# Grid for plots
gs = gridspec.GridSpec(3, 3)
skew = SkewT(fig, rotation=45, subplot=gs[:, :2])
# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
def plot_skewt(df):
# We will pull the data out of the example dataset into individual variables
# and assign units.
p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)
# Create a new figure. The dimensions here give a good aspect ratio.
fig = plt.figure(figsize=(9, 9))
add_metpy_logo(fig, 115, 100)
skew = SkewT(fig, rotation=45)
# Plot the data using normal plotting functions, in this case using
# log scaling in Y, as dictated by the typical meteorological plot
skew.plot(p, T, 'r')
skew.plot(p, Td, 'g')
skew.plot_barbs(p, u, v)
skew.ax.set_ylim(1000, 100)
skew.ax.set_xlim(-40, 60)
# Calculate LCL height and plot as black dot
lcl_pressure, lcl_temperature = mpcalc.lcl(p[0], T[0], Td[0])
from metpy.plots import Hodograph, SkewT
from metpy.units import units
#########################################################################
# Getting Data
# ------------
#
# Upper air data can be obtained using the siphon package, but for this tutorial we will use
# some of MetPy's sample data. This event is the Veterans Day tornado outbreak in 2002.
col_names = ['pressure', 'height', 'temperature', 'dewpoint', 'direction', 'speed']
df = pd.read_fwf(get_test_data('nov11_sounding.txt', as_file_obj=False),
skiprows=5, usecols=[0, 1, 2, 3, 6, 7], names=col_names)
df['u_wind'], df['v_wind'] = mpcalc.wind_components(df['speed'],
np.deg2rad(df['direction']))
# Drop any rows with all NaN values for T, Td, winds
df = df.dropna(subset=('temperature', 'dewpoint', 'direction', 'speed',
'u_wind', 'v_wind'), how='all').reset_index(drop=True)
##########################################################################
# We will pull the data out of the example dataset into individual variables and
# assign units.
p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
cursor = dbconn.cursor()
nt = NetworkTable("RAOB")
df = read_sql(
f"""
select f.fid, f.station, pressure, dwpc, tmpc, drct, smps, height,
levelcode from
raob_profile_{year} p JOIN raob_flights f
on (p.fid = f.fid) WHERE not computed and height is not null
and pressure is not null
ORDER by pressure DESC
""",
dbconn,
)
if df.empty or pd.isnull(df["smps"].max()):
return
u, v = wind_components(
df["smps"].values * units("m/s"),
df["drct"].values * units("degrees_north"),
)
df["u"] = u.to(units("m/s")).m
df["v"] = v.to(units("m/s")).m
count = 0
progress = tqdm(df.groupby("fid"), disable=not sys.stdout.isatty())
for fid, gdf in progress:
progress.set_description("%s %s" % (year, fid))
try:
do_profile(cursor, fid, gdf, nt)
except (RuntimeError, ValueError, IndexError) as exp:
LOG.debug(
"Profile %s fid: %s failed calculation %s",
gdf.iloc[0]["station"],
fid,
plot_units = ctx["units"]
df = read_sql(
"""
SELECT extract(doy from valid) as doy, sknt, drct from alldata
where station = %s and sknt >= 0 and drct >= 0 and report_type = 2
""",
asos,
params=(station,),
index_col=None,
)
if df.empty:
raise NoDataFound("No data Found.")
# Compute components in MPS
u, v = wind_components(
(df["sknt"].values * units("knot")).to(units("meter / second")),
df["drct"].values * units("degree"),
)
df["u"] = u.m
df["v"] = v.m
gdf = df.groupby(by="doy").mean()
u = (
(gdf["u"].values * units("meter / second"))
.to(XREF_UNITS[plot_units])
.m
)
v = (
(gdf["v"].values * units("meter / second"))
.to(XREF_UNITS[plot_units])
.m
)
import metpy.calc as mpcalc
from metpy.cbook import get_test_data
from metpy.plots import add_metpy_logo, Hodograph, SkewT
from metpy.units import units
###########################################
# Upper air data can be obtained using the siphon package, but for this example we will use
# some of MetPy's sample data.
col_names = ['pressure', 'height', 'temperature', 'dewpoint', 'direction', 'speed']
df = pd.read_fwf(get_test_data('may4_sounding.txt', as_file_obj=False),
skiprows=5, usecols=[0, 1, 2, 3, 6, 7], names=col_names)
df['u_wind'], df['v_wind'] = mpcalc.wind_components(df['speed'],
np.deg2rad(df['direction']))
# Drop any rows with all NaN values for T, Td, winds
df = df.dropna(subset=('temperature', 'dewpoint', 'direction', 'speed',
'u_wind', 'v_wind'), how='all').reset_index(drop=True)
###########################################
# We will pull the data out of the example dataset into individual variables and
# assign units.
p = df['pressure'].values * units.hPa
T = df['temperature'].values * units.degC
Td = df['dewpoint'].values * units.degC
wind_speed = df['speed'].values * units.knots
wind_dir = df['direction'].values * units.degrees
u, v = mpcalc.wind_components(wind_speed, wind_dir)
and date(valid at time zone tzname) = %s
ORDER by valid ASC
""",
asos,
params=(
ts - datetime.timedelta(days=2),
ts + datetime.timedelta(days=2),
ts.strftime("%Y-%m-%d"),
),
index_col=None,
)
if df.empty:
LOG.info("no ASOS database entries for %s", ts)
return
# derive some parameters
df["u"], df["v"] = mcalc.wind_components(
df["sknt"].values * munits.knots, df["drct"].values * munits.deg
)
df["localvalid_lag"] = df.groupby("iemid")["localvalid"].shift(1)
df["timedelta"] = df["localvalid"] - df["localvalid_lag"]
ndf = df[pd.isna(df["timedelta"])]
df.loc[ndf.index.values, "timedelta"] = pd.to_timedelta(
ndf["localvalid"].dt.hour * 3600.0
+ ndf["localvalid"].dt.minute * 60.0,
unit="s",
)
df["timedelta"] = df["timedelta"] / np.timedelta64(1, "s")
updates = 0
for iemid, gdf in df.groupby("iemid"):
if len(gdf.index) < 6:
continue