Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistency when multiplying NumPy masked arrays #633

Open
dopplershift opened this issue Apr 17, 2018 · 3 comments
Open

Inconsistency when multiplying NumPy masked arrays #633

dopplershift opened this issue Apr 17, 2018 · 3 comments

Comments

@dopplershift
Copy link
Contributor

There's a weird inconsistency when working with numpy masked arrays:

>>> import numpy as np
>>> import pint
>>> ureg = pint.UnitRegistry()
>>> a = np.arange(5)
>>> type(a * ureg.meter)
pint.quantity.build_quantity_class.<locals>.Quantity

>>>type(a * ureg('meter'))
pint.quantity.build_quantity_class.<locals>.Quantity

>>> ma = np.ma.arange(5)
>>> type(ma * ureg.meter)
pint.quantity.build_quantity_class.<locals>.Quantity

>>> type(ma * ureg('meter'))
numpy.ma.core.MaskedArray

That last one is creating quite a bit of heartache for me.

So I see that unit.meter is a Unit instance, whereas unit('meter') is a Quantity. Also, Unit.__rmul__ delegates to Unit.__mul__:

pint/pint/unit.py

Lines 141 to 147 in 19d0547

def __mul__(self, other):
if self._check(other):
if isinstance(other, self.__class__):
return self.__class__(self._units*other._units)
else:
qself = self._REGISTRY.Quantity(1.0, self._units)
return qself * other

So this changes a Unit into a Quantity, and delegates to Quantity.__mul__ by multiply the Quantity on the left--that explains why it works.

Based on some tracing with numpy 1.15, it looks like we end up in numpy.ma.core:

    def __mul__(self, other):
        "Multiply self by other, and return a new masked array."
        if self._delegate_binop(other):
            return NotImplemented
        return multiply(self, other)

and inside self._delegate_binop():

    def _delegate_binop(self, other):
        # This emulates the logic in
        #     private/binop_override.h:forward_binop_should_defer
        if isinstance(other, type(self)):
            return False
        array_ufunc = getattr(other, "__array_ufunc__", False)
        if array_ufunc is False:
            other_priority = getattr(other, "__array_priority__", -1000000)
            return self.__array_priority__ < other_priority
        else:
            # If array_ufunc is not None, it will be called inside the ufunc;
            # None explicitly tells us to not call the ufunc, i.e., defer.
            return array_ufunc is None

Unfortunately, this ends up returning False, which results in using the multiply function from numpy.ma.core. This is because Quantity delegates the __array_ufunc__ attribute to numpy.ndarray.

I wonder if it would be enough to set __array_ufunc__ to None in Quantity...

@hgrecco
Copy link
Owner

hgrecco commented Apr 19, 2018

Maybe the right way will be to implement __array_ufunc__ properly. This can be useful for many other things.

@dopplershift
Copy link
Contributor Author

I think so too, but I haven't had a chance to dig into those docs and see what that should look like...yet. I can confirm that just setting it to None results in the desired behavior, at least in this case.

dopplershift added a commit to dopplershift/MetPy that referenced this issue May 14, 2018
Because masked arrays and pint don't necessarily play nicely together
(see hgrecco/pint#633), we need to make sure that the Quantity is on the
left side of the multiply so that it controls the result--otherwise
weird unit errors can result.
dopplershift added a commit to dopplershift/MetPy that referenced this issue May 15, 2018
Because masked arrays and pint don't necessarily play nicely together
(see hgrecco/pint#633), we need to make sure that the Quantity is on the
left side of the multiply so that it controls the result--otherwise
weird unit errors can result.
mgrover1 pushed a commit to mgrover1/MetPy that referenced this issue Jul 16, 2019
author Ryan May <rmay@ucar.edu> 1506983621 -0600
committer Max Grover <maxi2312@gmail.com> 1563309011 -0600

parent cf7d532f6e926677ca58cea0c269485db9387a74
author Ryan May <rmay@ucar.edu> 1506983621 -0600
committer Max Grover <maxi2312@gmail.com> 1563309007 -0600

parent cf7d532f6e926677ca58cea0c269485db9387a74
author Ryan May <rmay@ucar.edu> 1506983621 -0600
committer Max Grover <maxi2312@gmail.com> 1563309000 -0600

parent cf7d532f6e926677ca58cea0c269485db9387a74
author Ryan May <rmay@ucar.edu> 1506983621 -0600
committer Max Grover <maxi2312@gmail.com> 1563308996 -0600

parent cf7d532f6e926677ca58cea0c269485db9387a74
author Ryan May <rmay@ucar.edu> 1506983621 -0600
committer Max Grover <maxi2312@gmail.com> 1563308940 -0600

MNT: Fix python 3-ism that snuck into conf.py

Oops.

MNT: Fix CONTRIBUTING.md

Having it in the root as a link to the copy in docs breaks GitHub
displaying it. Instead, keep the copy in the root and link to it in
docs/.

MNT: Fix malformed record in station test data

CSV data had a comma in the remarks column. Remove that so that it
parses better.

MNT: Update and rework Wind SLP interpolation example

Main thrust was to eliminate some missing data that wasn't properly
flagged before (and was throwing a warning when run). Go ahead and use
pandas to read the data. Also optimize to only read and project the data
once.

MNT: Update station plot examples a bit

Use pandas to read in data. This is primarily so that we're more robust
to all the missing values--we were missing some which was evoking
warnings from get_wind_components. Also use clip_on as appropriate.

MNT: Clean up copyright years

Also update the list of authors.

Add the Unidata Python Gallery link to the MetPy README

Resolves: #581

Add Unidata Python gallery link (and brief description) to Related Projects in index.rst

Resolves: #581

MNT: Fix errors from flake8-docstring

pydocstyle 2.1.0 broke API, breaking flake8-docstrings. Pinning should
fix this for now.

MNT: Build examples with matplotlib < 2.1 for now

Matplotlib 2.1.0 is causing problems with CartoPy maps.

MNT: Fix erroring of builds when doc8 fails

Apparently we were not catching this properly, since a bit of lint crept
in.

MNT: Fix link redirect

DOC: Remove trailing whitespace

[MNT] Cleanup storm_relative_helicity

Add get_layer_heights function for retreiving layers without pressure data

Add tests for get_layer_heights

[MNT] Simplify storm relative helicity tests

Refactor SRH

Extend tests for SRH

Add refactored version of original test.

Fix unit handing during interpolation of segmented hodograph plots.

Update tests for proper interpolation behavior.

Add metpy logo for few plots.

Add for few more examples.

MNT: Move recommon dependency

This should be in the doc dependencies in setup.py rather than in the
Travis config, since it's needed to build the docs any time.

ENH: Hide table of contents on main landing page

This keeps the TOC in the side bar, but removes it from the landing
page, elminating some duplication.

MNT: A few minor cleanups for the contributing guide

MNT: Fix examples with matplotlib 2.1

linewidth should never have been specified as a string, not sure how
that happened.

MNT: Silence some matplotlib 2.1 warnings from examples

These caught incorrect behavior: mis-spelled/useless kwargs and wrong
function calls, so that's good.

MNT: Fix style lint from flake8 3.5

It now warns about variables named 'l', since they are easily confused
with '1'. Changing all of these did seem to result in better code
regardless.

MNT: Add Travis build with docs and pre-releases (Fixes #583)

This should help us do a better job of testing pre-releases by making
sure we also run our examples against them.

MNT: Add __repr__ for TextCollection

Just use __str__. This overrides the behavior that Text gives with
matplotlib 2.1, which was confusing to see in the output. Update the doc
tests to reflect this, as well as silence a matplotlib warning.

Add import alphabetically.

Add import alphabetically.

Turn on interpolation in CAPE/CIN shading by default.

Update test image for interpolated filling.

Increase mpl 1.4 threshold for shading test due to interpolation in 2.1

Update mpl version check to use string comparisons

Cleanup precipitable water function.

* Correct error in formula documentation.
* Add bottom pressure argument.
* Make default of top pressure None.

Update test to have top of 400 hPa (old default value).

Update reference to Salby 1996.

Add test for precipitable water with no bounds given.

BUG: Fix transformation of barbs with Cartopy (Fixes #598)

ENH: Use our wx_code_map in the station plot examples

MNT: Fix some warnings with missing data

Also fix coding nan cloud coverage.

MNT: Install proj4 regardless on Travis

Since we're now using CartoPy for testing, we need proj for all builds.

MNT: Need to move shapely spec on Travis

Also needed to run CartoPy

Add test case for issue #593

Sort pressure and heights before getting bounds.

Add test for bounds failure, issue #596

Improve handling of floating point comparisons.

* Use nanmin/nanmax for any data with nan values
* Change comparison logic to our greater/less or close
* Change interpolation point addition logic to check if the point is close
* Closes #596

[MNT] Update import order

Integrate all areas for CAPE/CIN, not only positive or negative.

Improve logo positioning

[MNT] Fix flake8 import order issues

Update returns of figure annotations to be the annotations, not the figure or axis

Add specific humidity from mixing ratio calculation

Fix spelling error in mixing_ratio_from_specific_humidity docstring.

Add test for specific humidity from mixing ratio calculation.

Rename Convergence Functions to Divergence

This commit is a simple rename of the kinematic functions labeled
"convergence" with "divergence" instead, which is what is actually
being calculated. It updates the corresponding tests along with that. It
also corrects a few small comments where the string "convergence"
happened to show up when it should not have.

Add Myself to the Authors List

Since the contributor's guide said to add my name to the list, I did.
Hopefully future contributions will be more substantial that my first
simple rename.

Fix See Also Reference and Alignment

As requested, fixes the changed "See Also" reference to refer to the
stretching_deformation function, instead of just deleting it, as well
as makes sure the hanging argument stays aligned with the shortened
function name.

Add tests for dry and moist static energy.

Add calculations for dry and moist static energy.

MNT: Clean up some docstring lint

The short breaks were harmless, but the bad indent caused the docstring
to render incorrectly.

MNT: Update copyright year in docs

MNT: Regenerate sphinx make files

sphinx-build now has a make mode that handles all of the options, so we
can have much smaller build scripts. Still need a bit more for clean and
autogen, since there's more we need due to sphinx-gallery.

MNT: Re-enable building docs on AppVeyor

BUG: Fix filename pattern for sphinx-gallery

This was not actually working correctly, as it's supposed to be a regex,
not a glob. It just happened to match against the '/' in Unix paths,
where as on windows the path '\' caused escaping of the '*' character,
resulting in no scripts matching.

MNT: Add pandas to environment file

We use this in examples now.

Add a Thickness Calculation

This commit adds a thickness calculation using an integral form of the
hypsometric equation with virtual temperature adjustment. This assumes
hydrostatic balance. Also included are two tests of this calculation,
one using matching data from other tests and one using a simple dry
isothermal layer.

Correct Thickness Formula Arguments

Based on feedback, corrects the thickness formula to use d(ln(pres)) instead
of d(pres)/pres. While these are equivalent in the continuous case, they do
not give the same results in the discrete case here. Tests have likewise
been updated to account for this change in formula (which should hopefully
also resolve the legacy test failure).

Updates to Optional Mixing Ratio and Depth Code

Based on review feedback, updates the optional mixing ratio to be handled conditionally rather than with an array of zeros (if none is given), as well as conditionally calling get_layer only when a bottom/depth is specified. Adds two additional tests to cover all four scenarios (full layer-moist, subset-moist, full layer-dry, subset-dry). Also adds a citation for the thickness formula.

Correction After Rebase with Upstream

The recent addition of the static energy calculations unfortunately caused a messy rebase conflict where the new functions got interleaved. I thought I got it all cleaned up, but unfortunately missed this exporter statement.

Improve supercell composite and sigtor equation representation.

Add tests for scalar values to sigtor and supercell composite.

Update sigtor and supercell composite to work with scalar values.

Add input unit verification to supercell composite and sigtor

Improve function signature

Add test for segmented hodograph with differing bounds units.

Convert bounds to base units before plotting segmented hodograph.

DOC: check presence of patched rtd_theme prior to setting versions

Allows docs to build on vanilla sphinx_rtd_theme, see #644

Update gridding_functions.py

Changes interpolate function docstring to offer more specific explanation of 'hres' parameter

Update gridding_functions.py

Further generalizes docstring for hres parameter in interpolate function. Omits meters from default parameter description, as units are dependent on X and Y.

Replace "View source" with "Improve this page"

Modify the ReadTheDocs 'breadcrumbs.html' template to include this link.
The link in the docs will point to the Github source in "edit" mode (on
the master branch). If the page is autogenerated, it will point to a new
issue instead with the page name included in the title and some
instructions in the body.

Add a Mixing Ratio from RH Calculation

As a part of resolving issue #295, this commit adds a calculation to convert from RH to mixing ratio, given temperature and pressure data.

Add the Thickness from RH Calculation

As discussed in issue #295, adds in the thickness_hydrostatic_from_relative_humidity function, which is basically a wrapper for thickness_hydrostatic that takes RH as input and converts it to mixing ratio for thickness_hydrostatic to use. Dependent upon mixing_ratio_from_relative_humidity, hence included in same PR.

Fix First Lines of Doc Strings in Tests to be Imperative

As per discussion in #669, make sure that the first line of the doc string for all the tests are imperative to fit with convention.

Update to Take RH as a Unitless Ratio

Per discussion, updates the added mixing_ratio_from_relative_humidity and hydrostatic_thickness_from_relative_humidity functions to treat RH as a a unitless ratio between 0 and 1 inclusive. Applying this same update to other functions in thermo.py will happen in a separate PR.

Updates mixing_ratio and saturation_mixing_ratio to force a true dimensionless return

Updates precipitable water test to use assert_array_almost_equal to account for machine precision

Added tests for dimensionless mixing ratio

Add sphinx_rtd_theme to development environment

DOC: Correct "the the" typos

Update to Treat RH as a Unitless Ratio in Existing Functions

As discussed in PR #669, for consistency with the rest of the library, relative humidity should be treated as a unitless ratio in [0, 1]. It was noticed that some previous functions in thermo.py treated it as a percentage. This aims to correct that.

Fix Percent vs. Unitless Error in isentropic_example.py

Added function for relative humidity from temperature and dewpoint

Added test for relative humidity from temperature and dewpoint

Removed imported constant no longer needed

Fixed pep8 styleguide issues

Fixed pep8 indentation problems

Fixed rest of pep8 errors

Added single blank line to satisfy styleguide

Adjusted docstring to conform with PEP257

Failed test due to desired value being calculated with slightly different equation than what was used in the test. Updating desired value to conform with equation used in function

Updated for use of existing functions with slightly different formula

Updated docstrings

Satisfy the linter

Updated/Fixed Relative Humidity from Dewpoint Test

Clean up isentropic interpolation example

Changed extend value in colorbar call to 'max'

Removed figure number 1 from the figure call

Added call to plt.show at the end of script

Changed unpacking interpolation results

Clean up isentropic interpolation example

Initial draft of GEMPAK Table

Update RELH based on PR #681.

Ensure that appropriate constants and function results are dimensionless (#625)

* ensure dimensionless units in constants and mixing ratio / specific humidity calc

BUG: Fix loading of custom javascript in docs

The fixed relative path is no good. Instead, we can use the method
suggested in the templating section of the sphinx docs: the script_files
variable for the layout template. Also remove the additional loading of
jquery, since that's guaranteed to happen with our theme.

BUG: Fix relative paths for doc version handling (Fixes #675)

This was not properly finding either the versions.json file nor properly
linking to other versions if the user is anywhere but the main page.

MNT: Fix title for "Say Thanks" button

Clean up isentropic interpolation example

Adds calculation for variable dx/dy

added tests for calc_dx_dy

Make calc_dx_dy take advantage of slicing and not return unknown dx dy values at the boundary.

Add tests for 2D inputs and mismatched inputs

Rename function to lat_lon_grid_spacing

[MNT] Pin Freetype at 2.7

New functions for calculation of geopotential from height and vice versa (#678)

Change unit attachment to LCL pressure (#694)

Rename v_vorticity to vorticity and h_divergence to divergence

Add wrappers for convergence, convergence_vorticity, and v_vorticity.

Clean up isentropic interpolation example

Changed extend value in colorbar call to 'max'

Removed figure number 1 from the figure call

Added call to plt.show at the end of script

Changed unpacking interpolation results

Create CODE_OF_CONDUCT.md

Link to code of conduct.

Add high contrast functionality to timestamp

MNT: Remove hyphen from reference tag

It doesn't break Sphinx, but it does break PyCharm. Just get rid of it
since it's not necessary.

MNT: Update matplotlib import in conftest

For some reason pyplot needs to be imported explicitly. Easy enough just
to fix.

ENH: Make unit versions of at_least1d/atleast_2d handle arrays

They were assuming they always got Quantities.

ENH: Add functions for derivatives on irregular grids

Adds first and second derivatives, as well as gradient and laplacian
functions. These work on grids that have uneven spacing between points.

BUG: Fix incorrect deprecation

The original, actually shipped name was `h_convergence`, not
`convergence`.

MNT: Elminate divergence_vorticity

With the new derivative functions, there's no performance benefit to the
combined function. Instead of adding the appropriate named version, just
deprecate the old one entirely in favor of the individual vorticity and
divergence functions.

MNT: Deprecate shearing_stretching_deformation

This will no longer give us any performance benefit, so remove it.

MNT: Silence deprecation warnings in tests

MNT: Fix typos

ENH: Replace use of numpy.gradient wrapper

Use our own first_derivative and gradient functions. Some tests needed
to be updated to account for changes to how values at the edge of the
grid are treated.

MNT: Disable printing test log output by default

ENH: Promote diff wrapper to part of the API

MNT: Handle normalize_axis_index for old numpy

It's just a nice helper for better error messages, so we can just
backport as a noop.

MNT: Change default dimension ordering for kinematics functions

We already promised that we were going to do this, so we probably
should.

MNT: Update mailmap

MNT: Work around flake8-docstrings problem

1.2.0 doesn't seem to like our code.

MNT: Fix travis pinnings

Need the latest flake8-docstrings AND pydocstyle.

MNT: Update flake8 config to silence pydocstyle problems

MNT: Update authors list

MNT: Update doctests for NumPy 1.14 (Fixes #687)

Since we really only need to run doctests on the latest numpy, just
update the text output rather than try to use numpy's support for the
"legacy" print mode.

Force `mixing_ratio_from_relative_humidity` to return dimensionless

Fixes issue #703 where `mixing_ratio_from_relative_humidity` returns percent when RH is supplied in percent. Adds a test to verify returned unit is indeed dimensionless.

Clean up sigma interpolation example (#710)

Export gradient

ENH: Add config for CircleCI

Try to get geos installed

Install proj4

Fix the container version

Add precipitation color table

Add Batch of Functions for Brunt-Väisälä Frequency and Period

This commit works towards implementing the functions discussed in issue #629: Brunt-Vaisala Frequency Squared, Frequency, and Period.

This is based on previous commit 5119f72, but modified to use the new `first_derivative` function and to place the functions in thermo.py (which seems like the more fitting location). The previous `brunt_vaisala_frequency_layer` fucntion has also been removed.

Add calls to 'add_timestamp' to examples

Changed order of imports for metpy.plots

Added 'add_timestamp' in the imports and at the end of the code for the sigma_to_pressure_interpolation.py file

Added 'add_timestamp' to the isentropic_example.py file

Added 'add_timestamp' to NEXRAD_Level_2_File.py file and change
position of Metpy logo to lower left position

Added 'add_timestamp' to NEXRAD_Level_3_File.py file and change
position of Metpy logo to lower left position

MNT: Adjust test tolerance

Looks like the newest matplotlib tweaked the end of the lines being
drawn, so slightly bump up the tolerance.

Deprecate lat_lon_grid_spacing and add signed lat_lon_grid_deltas

Port tests from lat_lon_grid_spacing to lat_lon_grid_deltas and parameterize

[MNT] Remove landscape from code quality checker links.

Add web bulb temperature calculation using Normand's rule.

Add test for scalar values to wet_bulb_temperature

Generalize for nD arrays

Add tests for 1/2D inputs

Add reference for wet bulb temperature calculation.

Add values from NWS online calculator for reference.

format fixups

Add Dry Air Density Constant

While working on some problems using MetPy, I tried using the density constant, and found that it wasn't actually there, despite being in the documentation! This commit adds it in.

Ignore print statements in examples and tutorials.

Add pretext and time_format options to add_timestamp.

Add timestamp tests for pretext and time_format.

Add test images for add_timestamp.

ENH: Update Code Climate config

First steps to trying to make this thing useful.

BUG: Fix missing filename attribute

So when we refactored the handling of files, we removed the filename
attribute from Level3File. This attribute, it turns out, is used in all
of the logging for the class, as well as __str__. More disturbingly, not
one test screamed about it being broken.

MNT: Disable a few more Code Climate checks

Fix dependecies. #734 (#744)

Fix dependecies. #734

Add AMS talk (#745)

* MNT: Ignore new pytest cache directory

* ENH: Add link to 2018 AMS talk

Add ageostrophic wind calculation

Add tests for ageostrophic wind

Fix return types in docstrings of logo functions

Add potential temperature to temperature conversion (#746)

* Add potential temperature to temperature calculation

Add county outline files

MNT: Fix Travis testing with CartoPy

Need to explicitly install Cython for CartoPy to build. This needs to be
a global extra package since we use CartoPy for at least one test.

MNT: Fix test with new CartoPy and old Matplotlib

There's some kind of interaction here that changes the default
gridlines. Fix this by explicitly specifying the gridlines.

MNT: Tweak license text and update year

Update to 2018. Also pull a fresh copy of the license text from GitHub
to hopefully fix the license detection.

MNT: Fix some missing copyright years

It's 2018 now.

MNT: Move some doc links to https to avoid redirects

Rename testdata to staticdata

Point get_test_data at staticdata folder

[MNT] Update path to test data.

Add unit conversion capability to plot_barbs.

Add tests for barb unit conversion.

Disable method length checks in codeclimate.

Add wind barb unit conversion to skewt

Add tests for skewt wind barb conversion.

Bump test tolerance

Add saturation equivalent potential temperature (#748)

* Add saturation equivalent potential temperature

Adds custom grid boundary to interpolate (#741)

* Adds custom grid boundary to interpolate

[MNT] Fix rendering issues in Montgomery Streamfunction

MNT: use `mpcalc` as import alias for `metpy.calc`

fixes #756

Add absolute vorticity calculation

Add tests for absolute vorticity

MNT: Update contributing instructions

If we intend to update the AUTHORS.txt ourselves (which is good), we
should probably stop telling people to do it themselves in the
Contributor's Guide.

Update state and coastline features for Cartopy 0.16

Add baroclinic and barotropic potential vorticity calculations.

Add tests for baroclinic and barotropic potential vorticity.

[MNT] Update maximum argument count to 10

Force coriolis parameter output to 1/s

Test coriolis units are 1/s

MNT: Fix up a couple of barb tests

These fail due to changing freetype because they still have text, even
though remove_text=True. This is from pytest-mpl, and really matplotlib,
where it doesn't turn off axis labels. Let's turn them off manually
since these tests are not meant to test axis labelling (due to units).
This should allow these tests to be more reliable.

MNT: Remove pinning to freetype 2.7

Replace with using testing packages for matplotlib from conda-forge.

MNT: Slightly adjust some thresholds for new freetype

Image diffs don't show any difference, so likely just a pixel or two.
Good enough just to bump threshold.

MNT: Install recommonmark from conda-forge

Elminates the need to use pip separately.

MNT: Blacklist problematic flake8-builtins version

It doesn't seem to like loops where tuples are pulled out.

Four panel example edit

Added missing whitespaces as indicated by Stickler-ci.

Modified subplot_kw parameter value to the proper dictionary format.

Make any user kwargs to lat_lon_grid_deltas override the default geod ellps.

Test user kwarg override on lat_lon_grid_deltas

MNT: Remove unneeded blocks in turbulence tests

Was trying to just remove use of "keys()", but it turns out that the
blocks aren't necessary.

MNT: Remove unnecessary use of keys().

Unless it adds clarity, it's best to just rely on the fact that
iteration on a dictionary (including conversion to list) uses the keys
anyway.

Add Exner Function

As discussed in #757, this commit adds the Exner function (as a function of pressure), and refactors `potential_temperature` and `temperature_from_potential_temperature` to use it.

Closes #757.

Update Equation and Add Reference Pressure Optional Argument

Rename sample data to more meaningful names.

Remove upper air functionality and add data method for testing.

Change testing for newer test data retreival.

Remove unused testing file

ENH: Add Stack Overflow information (Fixes #782)

Updates all of the support, contact, etc. to include information about
posting on Stack Overflow.

MNT: Use logging.basicConfig()

This takes care of setting a default handler, formatter, and allows us
to set the *default* logging level. The way we were doing it would make
the module's level setting override any previous setting. This way
allows the user to more easily override.

MNT: Make NEXRAD decode WMO with ascii

It doesn't make any sense to use utf8.

MNT: Add some debug logging to NEXRAD

This gives us some information about the search for the header and
footer bytes.

MNT: Improve logging in NEXRAD level 3

Replace an assert (about bytes remaining) with a warning message
instead, since in some cases parsing can happen just fine. Also replace
a commented out print statement with a debug log message.

BUG: Fix get_layer_heights modifying heights in-place (Fixes #789)

MNT: Remove unneeded comment from conf.py

ENH: Add an issue template

Add inertial advective wind calculation.

Add test for inertial advective wind.

MNT: Fix some doc http->https redirects

MNT: Update codacy link

Removes a redirect.

MNT: Update link to WMO#8 report

MNT: Remove unneeded use of matplotlib pyplot

This started as cleaning up a warning from matplotlib that was using
plt.axes() to return an existing axes. I ended up removing all uses of
pyplot that were readily replaced by a call to the appropriate figure or
axes method.

Add utility to attach units to pandas dataframes.

Add tests for pandas unit functionality.

Add pandas to testing requirements.

MNT: Add python_requires to setup.py

This will be more important once we drop 2.7.

ENH: Add Python 2.7 plans to docs (Fixes #803)

ENH: Add information about semantic versioning (Fixes #802)

MNT: Fix travis doc build

With pip 10, we need an extra flag to make it blindly upgrade
everything, which is what we want for our CI setup.

Add wind vector plotting to the hodograph.

Add test of hodograph vector plotting.

Add feels like temperature.

Add test for feels like temperature.

Add reference PDF to NWS 10-201

Refactor colored line segment hodograph

Add Q-vector and Static Stability Calculations

Implements the Q-vector and static stability calculations as discussed
in #661, based of formulas from Bluestein1992.

Closes #661.

Add new metpy/calc/tools parse_angle and its subfunction _abbrieviate_direction

parse_angle allows users to easily convert directional text into a degree/radian value
such as N becomes 0 deg, east becomes 90 deg, south_east becomes (135 deg) etc

Adds calculation for dewpoint from specific humidity, temperature, and pressure

Adds test for dewpoint from specific humidity

Modify calculation of LFC and EL for arbitrary parcel profile

Added tests for ML LFC and EL calculations

Clarify get_layer doumentation.

Clarify bulk shear documentation.

Update development installation instructions.

Make sure LFC is not below LCL.

Add test for LFC not below LCL

Pass parcel profile through cape_cin calculation.

Add test for custom profile in cape_cin

Removes grid size warning from generate_grid (#811)

* Removes grid size warning from generate_grid

This removes the grid size warning for grids with dimensions less than 10000 units. The message implies the use of meters, which means it could appear for users using other grid dimensions (like degrees).

Make default_units work with lists or tuples and return dimensionless as the default unit.

Add test for hodograph with united component range. Fails currently due to mpl bug

Don't allow flake builtins 1.4.0

Add parse_angle() example to calculations page.

Fixes issue that would error out parcel_profile if the profile did not reach the LCL. #827

Add test for parcel profile when the profile does not reach the LCL.

[MNT] Pin at not netCDF4 1.4 for examples.

Rename delete_masked_points to _delete_masked_points

Update tests and skewt for renaming to _delete_masked_points.

Import interp from calc instead of calc.tools

Allow apparent temperature to take and return scalars.

Add test for apparent temperature working with scalars.

Add tests for gradient

Add detail to gradient documentation.

Add example of using gradient.

Remove requirements text

ENH: Support Unidata GINI NEXRAD composites (Fixes #795)

Adds support for reading PNG compressed data, as well as fudging around
the fact that year values are less than 100, but should be years since
1900.

ENH: Enhance GINI tests

Add a test of actual values in the data array, as well as the values of
datetime in the netCDF interface.

ENH: Add XArray support to GINI

This makes GINIFile work as an XArray data store, so that it can be
passed directly to xarray.open_dataset(). Port the example over to use
it.

MNT: Deprecate CDM and GINIFile.to_dataset()

This deprecates the CDM layer, which is only used by the netCDF-like
interface for GINIFile, in favor of the XArray support.

MNT: Add a configuration for LGTM

Reclassify/ignore a few files.

MNT: Work around docstring formatting in xarray

The formatting for the load docstring is incorrect in xarray, which
causes sphinx to warn when building our own docs. Inheritance is
wonderful.

Add new functionality to GEMPAK table.

Export wx_symbols to plots level.

Update examples for wx_symbols being exported to plots level.

Update testing for wx_symbols being exported to plots level.

Export colortable registry and update examples.

Export gridding functions.

Rename colortables directory to colortable_files.

ENH: Add simple registry implementation

This adds a class with a register decorator that can be used to register
callables under a string.

ENH: Add framework for converting CF attributes to CartoPy

ENH: Add xarray accessors to simplify getting projection

ENH: Add example of using xarray projection info

MNT: Bump up complexity threshold for CodeClimate

ENH: Use xarray support to simplify GINI example

MNT: Fix import on Python 2.7

Default behavior of Python 2.7 gets confused by our having our own
xarray module and trying to import the main library. Some future imports
solve this...

MNT: Move pyproj import

Right now metpy.calc won't import without having pyproj installed, which
is a bit more of a pain in the but than I want for a hard dependency
right now.

MNT: Add xarray as a hard dependency

MNT: Update codecov config

Looks like we were missing some test lines

MNT: Fix README link to install guide

BUG: Fix interp with unit-ed masked arrays

Because masked arrays and pint don't necessarily play nicely together
(see hgrecco/pint#633), we need to make sure that the Quantity is on the
left side of the multiply so that it controls the result--otherwise
weird unit errors can result.

MNT: Simplify isentropic interpolation code

Simplify the interpolation of other variables, taking advantage of the
fact that the linear interpolation can handle multiple variables at a
time.

MNT: Remove use of assert_almost_equal with .shape

Should just be doing an explict assert arr.shape == truth.

MNT: Simplify some of isentropic_interpolation

This just eliminates some unneeded named temporaries, ensuring that
their memory is released sooner.

BUG: Fix isentropic_interpolation for masked data (Fixes #769)

If an entire column of data was masked, the sorting would end up trying
to interpolate off the bounds of the array.

MNT: Ensure we handle columns of nans in isentropic_interpolation

ENH: Add utility function to search for indices around a value

ENH: Use linear search in isentropic_interpolation (Fixes #798)

Previously, this was using numpy.searchsorted(), which is only strictly
correct if the points are sorted/monotonic increasing. Theta can easily
violate this condition. Instead, switch to a linear search, which allows
also controlling which direction to search. This also seems to be faster
since we're no longer using apply_along_axis, but can rely on indexing
operations.

Added a function to calculate critical angle as well as a reference and a test for it. (#843)

MNT: Move location of xarray helpers

This moves to a top-level module, which is imported by the top-level
__init__. This causes any import of metpy to activate the xarray
accessors, which simplifies using them in a few places.

ENH: Add xarray preprocessing decorator

This currently handles converting xarray DataArray's passed to
functions into pint Quantity instances.

ENH: Apply xarray decorator to calculations

This changes all exported functions to have DataArray instances passed
to them automatically converted to pint Quantity instances. I added one
test to ensure this works; ideally all calculations would have such
tests, but that seems overly repetitive.

MNT: Fix close test functions with mixed units and not

This was triggering a warning about numpy.float64 and a lack of a _units
attribute. The root cause was comparing a value with units with one that
had them. One fix is to make sure neither have units in parcel profile
(since both values have been coerced already to have the same).

The other change is to tweak _greater_or_close and _less_or_close to use
> and < rather than numpy.greater and numpy.less, so that an error
results if a Quantity and an array are compared.

MNT: Use strftime as a method in add_timestamp

Rather than hardcoding the use of the strftime function from the
datetime module, use it as a method. This way a passed in object can
have their own implementation of strftime, which paves the way to using
the '.dt' accessor from xarray.

ENH: Monkey patch in strftime for xarray

This is going to be a PR, but without it things are far too ugly, so
we'll monkey patch one in for now. This requires moving to xarray 0.9.6
which is when the .dt accessor was added.

MNT: Clean up isentropic example

This passes in CartoPy transforms to plotting functions instead of
manually tranforming everything. It also uses xarray instead of netcdf4
to handle data parsing.

MNT: Fix up sigma interpolation example

This now passes CartoPy projections as transforms rather than manually
projecting. It also works around the masked array and pint issue by
hard-coding units rather than parsing them. We cannot use xarray for
this right now because there are problems with how the file does
lat/lons.

MNT: Update Four Panel Map example

Moves to use xarray.

MNT: Remove pinning netcdf4

We've addressed all of the issues in the examples.

Optimize parse_angle (#850)

Optimized parse_angle() for long list of directional strings.

BUG: Fix mask propagation in gradient (Fixes #642)

The calculation propagates masked values fine, in that any calculation
involving one more more masked values ends up as masked (similar to NaN
propagation). The problem was using numpy's concatenate, which stripped
masks. Use np.ma.concatentate instead, dropping to a regular array if
there are no masked values.

MNT: Extend Travis build time.

MNT: Clean up CircleCI build

Reduce log output so we can figure out what's going on, and fix the
build.

MNT: Bump CartoPy requirement for tests

We need some of the newer projection options.

MNT: Update AUTHORS

Also update the .mailmap for that.

MNT: Fix some non-standard naming

Capitalized names are reserved for classes. Picked up by pep8-naming
0.7.

Update thermo.py

Fix docstring for wet bulb temperature function.

Drop 3.4 from the .travis.yml matrix, setpy.py, and README

Change x to coordinates in gradient and laplacian interface

Fixes #842 by replacing the x keyword argument in _process_gradient_args
with coordinates, and including x as a deprecated option. Also adds
tests to verify that use of x as a keyword argument raises the
deprecation warning.

Additional changes to drop python 3.4

Rename wind functions to remove get_

Renames:
	- `get_wind_speed` -> `wind_speed`
	- `get_wind_dir` -> `wind_direction`
	- `get_wind_components` -> `wind_components`

Also, deprecates the old functions, and updates the usage of these
functions in the examples/tutorials.

Fixes #865.

Specify handling for calm and north winds

This commit modifies `wind_direction` so that calm winds return 0 and
north winds return 360, according to the meteorological convention.

Also forces `wind_direction` to return in degrees (some past results had
it returning as dimensionless).

Fixes #794.

Add conversions between omega and w under hydrostatic conditions

This commit adds two basic equations that assume hydrostatic balence in
order to convert between omega (Dp/Dt) and w (Dz/Dt).

Initial move of gridding to interpolate

This (rather substantial) commit refactors the current gridding package
to become the interpolate package. This includes making gridding exist as
a wrapper module (that deprecation warns whenever used), pulling out
some of the internals of the old gridding functions to work on a point
basis, and renaming/reorganizing many of the functions to make them fit
better within a more general interpolation package.

This does not yet include moving over interpolation functionality that
currently resides in calc.

Move interpolation functionality in calc to interpolate

This commit moves the interpolation functionality in metpy.calc.tools
(all forms of interpolation along a single axis) to a new module in
interpolate.

This also contains a series of changes to fix syntax errors and other
mistakes based on CI and code review

Build in identification of spatiotemporal coordinates

Adds coordinate mapping utilities to the Dataset accessor, and uses them
in `parse_cf` to relabel the `axis` attributes appropriately. Then, adds
in methods to the DataArray accessor so that the spatiotemporal
coordinates can be easily accessed.

Add xarray tutorial

This commit adds a new tutorial to demonstrate the extent of MetPy's
xarray integration, and how to perform basic operations. This tutorial
should be kept up to date as integration with xarray improves.

Add tests

This commit adds tests for systematic coordinate identification.

Clean up DataArray equality tests

Instead of checking equality of values and attributes, use the
`indentical` method, which is much cleaner.

Let dimension coordinates take precedence

In working with the GOES16 data, the coordinate identification in
parse_cf fails because there are two coordinates with
"projection_x_coordinate" as their standard name. But, only one of them
is actually a dimension coordinate, and we would want that one to be
selected. This commit implements and tests for this.

Expose cartopy globe in CFProjection and xarray accessor

This commit changes the protected method _make_cartopy_globe in
CFProjection into a property, and exposes that property in our xarray
DataArray accessor as well.

permit usage of temperature in Kelvin for heat_index calc

"Improve page" links for examples and tutorials

Adds the sphinx-gallery configuration to the template so we can link to
the Github edit page for the gallery .py files.
The template also identifies the index.html files and directs them to
the README.txt files.

fix apparent_temperature when only windchill is calculated

workaround numpy=1.10.0 issue?

Modify lat_lon_grid_deltas to allow for >2D arrays

In the course of working on xarray examples in metpy, the current
implementation of lat_lon_grid_deltas only allowing 1D or 2D input was a
hinderance. This commit makes a simple change to allow >2D arrays, so
long as the trailing dimensions are y, x.

Fix remnants from lat_lon_grid_spacing deprecation

The deprecation warnings for lat_lon_grid_spacing were not being
tested/handled, and some of the comments for lat_lon_grid_deltas still
referenced lat_lon_grid_spacing instead. This commit fixes those.

Remove deprecated kinematics functionality from 0.7

This commit removes the deprecated kinematics functions slated for
removal in 0.9, as well as stopping the warning for using the default
dim_order, as outlined in #690.

Allow extra leading dimensions in gradient and kinematics calculations

Based on issues with some kinematics calculations generalizing to data
that has extra leading dimensions (such as time or vertical as commonly
encountered when working with xarray examples), this commit modifies the
default derivative axes in kinematics calculations to be based on
trailing axes (-2 and -1) rather than leading (0 and 1), to follow our
convention (and CF option) of (..., Y, X) dimension ordering. Numerous
tests are added to make sure that the affected calculations work with
extra dimensions (tested on 4-D data).

Additionally, the gradient function previously only supported the full
gradient of an array according to its description, but a useful case is
just obtaining the horizontal gradient along all levels or times. Handling
of the "axes" kwarg and was added to the _process_gradient_args function
to resolve this, so that "axes" becomes a kwarg of gradient and
laplacian. It must be less than or equal to in length compared to the
coordinates/deltas.

Add netcdf4 to testing requirements

MNT: Replace assert with log message in NEXRAD

We're just checking a size here, so be less aggressive and warn rather
than error out. It's completely possible to be off a little in size and
still parse through the file fine.

MNT: Update NEXRAD for new message size

With latest RDA Build 18.0, the size of the status message has increased
with some spare bytes. Just include the spares in the size check for
now.

Add xarray to intersphinx mapping

In conf.py, adds xarray to intersphinx mapping so that we can easily
link from our documentation to xarray's.

Add API doc module override, and use it with metpy.calc

This commit modifies the module template to allow it to be overridden by
a custom module page, implements a make checker for that override, and
implements this to better organize the docs for metpy.calc.

Also updates the Travis and AppVeyor doc builds to use the overridecheck option.

Remove removed functions from doc page override

After #889 and #882 were merged, there was a conflict where the override
doc page created in #889 had functions that were removed in #882. This
commit removes those and should restore the doc builds to working order.

Also cleans up a line from code review in #889.

Fix NEP 14 broken link

Bump minimum xarray to v0.10.7, numpy to v1.11.0

Add cross section function and supporting calculations

This commit adds a `cross_section` function to `interpolate`. It allows
interpolation to a cross-sectional slice through gridded data along a
geodesic path between two lat/lon points. Associated changes are also
made to some xarray functionality.

Additionally, this adds a number of calculations to the calc subpackage
in support of cross section functionality:
 - unit vectors
 - tangential and normal components
 - absolute momentum (pseudoangular momentum)

NARR Example CF Parsing

While I was working through examples, I noticed that the parse_cf
function, when applied to the full dataset of the NARR example, would
fail...the x and y coordinates would double in size, and many NaN's
appeared. This was because the lon and lat variables lacked a
grid_mapping attribute, and so, their x and y coordinates did not get
scaled from km to m like the other variables that did. Thus, they did
not line up when xarray tried to combine them back together in a
non-unit-aware fashion.

This commit fixes this by changing when _fixup_coords is called, so that
all x/y coordinates get scaled accordingly.

Fixes based on CI, code coverage analysis, and review

Update docstring for vorticity

Documentation for the vorticity function hadn't been updated to reflect
the fact that the function can handle varying grid spacings. This commit
updates the documentation accordingly.

Add NARR Cross Section Example

This commit adds a basic example of cross section analysis using the
NARR example dataset. It plots potential temperature, relative humidity,
and projected winds, with an inset 500 hPa map with the cross section
path depicted.

Make derivative calculations work with xr.DataArray

This commit modifies the current derivative calculations
(first_derivative, second_derivative, gradient, and laplacian) to work
with DataArrays themselves, rather than by conversion to (and output as)
pint Quantities. In order to support lat/lon non-uniform coordinates,
the lat_lon_grid_deltas function has moved from kinematics to tools to
be alongside the derivative calculations, and a helper function to make
it work nicely with a DataArray was added.

Some small fixes are also made to the xarray tutorial along the way.

Add additional units to the pint registry

Units such as 'degrees_north' are part of CF standard for latitude and
longitude coordinates, and unless they are renamed, the xarray to pint
quantity conversion breaks with these units. This commit defines these
as new units in our registry, with aliases/abbriviations as needed.

Clean up exisiting workarounds

In order to work with data that had 'degrees_north' (or
similar), workarounds were needed in the past. With the unit update,
these are no longer needed.

Part of the remaining discussion involved how exactly to handle 'gpm'
non-standard units. A comment referencing the relevant issue has been
added to the tutorial section on the existing workaround, since the
issue needs further implementation discussion.

Fix non-tuple NumPy indexing in MetPy

Since NumPy 1.15 came out, we have been getting pages and pages of
warnings about our use of non-tuple based indexing. This commit converts
all of our previous list-based indexing to tuple-based indexing. This
doesn't yet clear out all the warnings (some of them are upstream in
Pint and scipy), but it does drop the number down from 600-something to
10-something.

Add GWFS function from GEMPAK

This commit wraps the gaussian_filter function from SciPy so that it
emulates the GWFS function from GEMPAK as closely as possible. The key
difference is that GEMPAK adds the leftover weights from outside the
averaging window to the center point, but there is no option for
gaussian_filter to do this.

Left unfinished is restoring metadata to the result. For instance, an
xarray.DataArray provided as input becomes a lowly numpy.ndarray on
output.

Add tests and docs for gwfs()

This commit adds a few basic tests for the metpy.calc.gwfs function,
and also updates the GEMPAK compatibility table.

I'm not sure how to add new documentation to the MetPy API section.

Fix whitespace issues re pep8

Extend functionality of gwfs and update docs

gwfs is extended to preserve units and ensure that only horizontal
directions are smoothed (assuming last two axes are
horizontal). Documentation is updated so that this function appears.

Rename gwfs() to smooth_gaussian()

Update GEMPAK Conversion Guide

One place was overlooked when changing gwfs() to
smooth_gaussian(). This corrects the oversight.

Add link to SciPy 2018 talk

Add links for scipy 2018 poster

Respell doc page names for clarity.

MNT: List matplotlib >= 2.2 in requirements for examples (Fixes #867)

This may help people to not run into problems with older matplotlibs.

MNT: Add some implemented functions to GEMPAK table (Fixes #857)

These got missed for 0.8

MNT: Update some redirecting links

BUG: Increase default x clipping radius for SkewT

The previous default of 0.08 was just a little too tight.

Add gempak_color() and related tests (#916)

* Add convert_gempak_color() and related tests

This commit adds a new convert_gempak_color function to metpy.plots to
facilitate conversion between GEMPAK color numbers and corresponding
Matplotlib colors. All known GEMPAK quirks are accomodated (such as
101 representing the background color).

Add unit tutorial

MNT: Add warning filter for numpy messages

The "dtype size has changed" warning is harmless enough, and is really
becoming verbose of late, at least in terms of the number of places it
pops up. Silence that for now here.

MNT: Add additional assert to check

If there are no log messages, before this change you just get an
IndexError. Now you get a failed assert and it's quicker to see what's
going on.

BUG: Don't use basicConfig for logging (Fixes #866)

What basicConfig does is install a root handler if none is already
installed. This breaks applications that also try to use it to set a
different level. It's completely unnecessary on Python 3, since by
default there is a handler that logs anything WARNING or higher to
stderr, which is really what we want. This isn't the case on Python 2,
so what we can do in that case is put a StreamHandler (which defaults to
stderr) for all of metpy (all submodules will defer to it by default).
WARNING is already the default logging level anyway.

Add gpm unit as an alias to meters

Use Pooch to download sample data

Add it to `metpy/cbook.py` and include the dependency on setup.py.
Create the registry file using `pooch.make_registry` and stored it in
the `metpy` package.

Remove 32-bit windows builds

A Few Doc Fixes

This commit contains a few documentation fixes:

- Fix the description of the cross_section/interpolate_to_slice
functions to reference xarray's interpolation, not metpy's
- Clear up some usage details with Dataset.metpy.parse_cf() (see Issue
 #909)
- Update dx/dy handling wording (as in #901) for all applicable
functions in kinematics
- Add notes to kinematics functions about handling of >2 dimensions
(similar what ageostrophic_wind had in parameter descriptions)
- Update the GEMPAK table for closed issues

BUG: Fix SRH unexpectedly returning masked values

BUG: Fix edge cases in profiles calculations (Fixes #902)

By not including the LCL in the profiles used in calculations, some odd
corner cases result where, e.g., the intersection points with the
ambient profile change. It also has an impact in cape/cin calculations.
Refactor profile handling to explicitly work with a profile that
includes the LCL and expose this as an API function.

MNT: Tweak test profile

With changes to LFC calculation to use a profile that includes the LCL,
the old data does not match the test case of an uncapped sounding. Tweak
a temperature to get back to that case, since that's what we want to
test here.

MNT: Adjust CIN value in test

Now that sfc cape/cin uses a profile that includes the LCL, this
increases the amount of negative area in the profile, so we need to
adjust the value here.

Add rest of shapefile associated data

Add county features

Add example of using counties with different resolutions.

Remove cartopy dependence in cross-sections

Add v to beginning of version number for pooch search path.

Add instructions for adding a file to the cache

Adds US State borders at same scales as counties

refactor class to MetPyMapFeature

Access constants via module (#930)

Access all constants via module

MNT: Only pin to minor version of pooch

Rather than pinning to exact version including bug fix. Turns out we
were already doing this for conda.

MNT: Fixup tests for matplotlib 3.0

Tests were broken by matplotlib 3.0 due to our tests' use of old
matplotlib style parameters. Main code was note affected.

MNT: Eliminate some unnecessary uses of pyplot

This specifically fixes a problem between matplotlib 3.0 and CartoPy.

MNT: Add workaround for CartoPy/Matplotlib incompatibility

Replace deprecated interp with interpolate_1d

Add decorator to ignore metpy deprecation warnings.

Turn metpy deprecation warnings into errors with pytest.

Decorate tests of deprecated functionality.

Remove edgecolor from example

address pytest fixture warnings emitted by pytest==3.8.1

MNT: Remove unused warnings.simplefilter

Really shouldn't be filtering out our own deprecation warnings
anyways--this has been made an explicit error unless otherwise flagged.

MNT: Replace use of warnings.simplefilter with pytest

pytest has the ability to mark individual tests to filter, so that's
better anyway.

MNT: Change wrapping around binary operators

Recommended by pep8 for new code, and I kinda prefer it, so went ahead
and adjusted.

MNT: Remove use of numpy.asscalar

Numpy 1.16 will deprecate numpy.asscalar.

remove inaccessible/noop code in metpy.deprecation

increase coverage of metpy.interpolate.points

increase coverage of metpy.units

MNT: Make io module docstring conform to standards

Picked up by pydocstyle 3.0.

MNT: Fix up copyright year

MNT: Silence numpy warning about using a tuple

The warning was blaming Pint, but it was actually coming from this code.

MNT: Clean up code for nexrad spec parser

flake8 is picking up this file now, might as well make it compliant.

MNT: Correctly escape regular expression groups

Can't use raw strings since we need \n and \r, so need to use \\ for the
regular expression groups.

MNT: Remove hacks for Matplotlib 3.0.0/CartoPy

Matplotlib 3.0.1 has been released.

Add Skew-T axes at arbitrary locations (#959)

Add support for drawing SkewT on an axes at an arbitrary location.

Adds n point smoothing function

Update docs for dropping 3.5 and adding 3.7

Add 3.7 to CI builds

Update for dropping 3.5 and adding 3.7

Add sudo required

Use xenial

[MNT] Remake test image with cartopy 0.17

[MNT] Use https links

Bump to mpl 1.5.1 for cartopy

Bump test tolerances for mpl 2.0

Remove old mpl patches.

Update PV calc for isobaric

Fix interpolation tests for SciPy 1.2

Scipy 1.2 fixed a bug in 2D cubic interpolation, so we need to adjust
the values in the sample files. We can avoid shipping mulitple versions
of the static data by skipping the tests on older Scipy versions.

Using log.warning insted of  warnings.warn

Add test to verify warning is logged

Add a reference pressure to moist_lapse and dry_lapse

Clean up empty array creation.

relax pooch requirement to >=0.1

closes #977

Pin pooch at <0.3

Clarify wind_components docstring and close #969

fixes issue #960 and add test function

Reattach grid_mapping after cross-section calculations.

Add unit- and axis-aware selection to the metpy accessors

This commit adds the .loc indexer and .sel method to both the DataArray
and Dataset metpy accessors to allow for unit-aware indexing/selection.
For DataArrays (for which axis types are uniquely determined), this also
allows selection via the axis name ('time', 'vertical', etc.) instead of
the coordinate name.

Also, adds this new unit-aware selection to the xarray tutorial.

Change axis-tracking attribute from axis to _metpy_axis

Previously, any existing axis attribute was removed to enforce
uniqueness of any given axis, but this modified the user's data. Now,
the axis is tracked in _metpy_axis to avoid collisions.

[MNT] Update requirements

Add link to install guide.

Make necessary coordinate information for cross sections clearer

As discussed in Unidata/MetPy#949, the error message from the cross
section function could be made clearer in the case where coordinate
information is missing. This catches the AttributeError that was raised
and instead raises a more informative error. The docstrings have also
been updated.

ENH: Implement simplified plotting interface

Adds a declarative interface for creating plots, similar in nature to
GEMPAK.

DOC: Add examples for simplified plotting

ENH: Add GEMPAK area definitions

ENH: Add tests for simplified plotting interface

ENH: Add traitlets to dependencies

ENH: Rename maps to layers

Seems a bit clearer.

[MNT] Pin pint <= 0.8.1

Mark noqa on case in metpy deprecations.

Switch from recommonmark to m2r

[MNT] Bump to numpy 1.12

[MNT] Pin flake8-comprehensions for 2.7 builds

MNT: Update mailmap

ENH: Add roadmap (fixes #941)

MNT: Disallow pyproj 2.0.0

This has completely busted us.

updates docs for latitude units

Adds more combinations for wx symbols

Adds a function to linearly interpolate to level

MNT: Update doc8 configuration

Sphinx-gallery changed their output and it completely buggers doc8.
Probably shouldn't be running doc8 on generated files anyway. This does
eliminate checking some of our index.rst files, but it's a small price
to pay to have things working again.

MNT: Update some redirecting URLs

MNT: Fix broken link to Miniconda

Fix rst style links in the Contributing Guide

Replace some rst style links with markdown syntax.

Use https for PEP8 link

Fix LFC calculation when positive area exists below LCL

Soundings can exist where there is positive area only below the
LCL. This commonly occurs when there is a superadiabatic lapse rate
near the ground. Other soundings may have positive area all the way
from the surface to an EL above the LCL. The current code conflated
these two situations, assuming that any positive area in the sounding
must mean the second case is at play. This commit makes sure that any
positive area that is found is above the LCL. If so, the LFC is set to
the LCL as before, but if not, there is no LFC (it is set
np.nan). Changes suggested by @dopplershift are incorporated.

Add test for LFC fix

Fix crash with mixed-layer LFC calculation

This commit fixes a crash when computing the LFC of a mixed-layer
parcel and adds a corresponding test for this situation.

Fix incorrect results with LFC calculation

Currently, some of the logic in the lfc() function assumes a surface
parcel is being considered, but that is no longer necessarily the
case.  This commit addresses the two places where a surface parcel has
been assumed.  First, when looking for intersections, the code assumed
the first point of the parcel trajectory had an identical temperature
to the environment.  This is only true if a surface-based parcel is
being used.  Second, the LCL of the parcel is computed using surface
values.  This, too, is not appropriate if the parcel is not a surface
parcel.  The lfc_ml2 testcase was giving wrong results because of the
second problem.

This commit addresses both problems and corrects the associated
testcase.

Add additional test for latest LFC fix

This test gives 990 hPa for the LFC (the LCL value in this case) if
the fix to the find_intersections() call is not present.

Use NumPy's isclose() so that Python 2.7 is supported

Update Advanced Sounding doc to explain why 0 index is chosen

Add line break

Update potential_vorticity_baroclinic() docstring

Fixes #1035

MNT: fix flake8 errors

fix doc issue

remove link to ejssm article

add functionality to declarative plotting

Fix Scipy 1.3 not-C-contiguous error

As pointed out by @akrherz, using `np.vstack` followed by transposition
causes problems (the array not being C-contiguous, which scipy needs).
This stacks the points in a safer way.

Fixes #1043.

migrate mpl.cbook.iterable to numpy.iterable

Due to lack of support for the '%' as a unit within pint,
this update converts '%' units to 'percent' units within the
MetPy xarray accessor.

Fixes #1038.

Docstrings improved for thermo calculations requiring pressure
arrays to be from high to low pressure.

Update to test_mpl.py to update deprecated function

Update EL calculation to prevent an EL existing below a LCL.
Completes the fix to #1003.

first pass at better docs for declarative

Make parse_cf() not keep attributes in parsed dataset

Rename xarray accessor classes and move check_axis outside of accessor

Refactor xarray coordinate parsing to be on-demand on the DataArray

Update xarray tutorial for on-demand coordinate parsing

Improves documtation for interpolate_to_grid to specify
that linear distance or degrees can be the units of the
input coordinates (and resultantly, the resolution of the grid).

Fixes #1060.

Remove lat_lon_grid_spacing and the cdm module and related components

Add warning if lat/lon is assumed for projection

Fix docstring for vertical velocity functions to render equations

This update to the lfc() function allows for multiple LFCs to be
identified within a sounding. This fixes #992 and begins to address

Add in altimeter_to_station_pressure and altimeter_to_sea_level_pressure

Updated tests to include METAR calculations

Removed changes

Removed all additional changes

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Update metpy/calc/basic.py

Co-Authored-By: Zach Bruick <zachary.bruick@valpo.edu>

Removed whitespace

Corrected sea-level pressure

Remove conversion within the function since it supports units, update documentation

removed check units lines

Consolidate standard atmosphere variables

removed trailing whitespace

Changed incorrect variable, added documentation

Fixed indentation error

Fixed units issue with station pressure calculation

Fixed incorrect value for gamma

Added additional placeholders

Adds a conditional import of the DatetimeAccessor due to a change in the
backend API of xarray v0.12.2. Fixes #1077.

Updated import method per @jthielen's suggestion

Added note that x-axis can be any variable, due to feedback received from a user

BUG: Fixup geopotential<->height calculation (Fixes #1075)

Previous implementations was a naive implementation that directly
translated formulas from source material. It included a lot of division
and subtraction, resulting in catastrophic cancellation and severe loss
of floating point precision. New formulation is just an algebraic
reformulation that avoids these problems.

Vendor functionality from xarray.core

Add tests for otherwised unused portions of xarray utilities

Add formulas to geopotential functions in docs and correct reference

MNT: Update ticks for SkewT (Fixes #987)

This updates the implementation for ticks in SkewT based on changes in
matplotlib. This greatly cleans this up, and for some reason, is
necessary with matplotlib 3.1.

MNT: Update some skewT image test thresholds

This gets the test suite passing with Matplotlib 3.1. Not sure what
changed, but a deep look at the differences only reveals some subtle
changes to just how black the individual tick marks are.

Added 3.7-dev to the matrix

Updated year in LICENSE

Replace jrleeman with zbruick as a codeowner

Updated contributors in AUTHORS.txt and .mailmap

allow any pooch >= 0.1 to be used

Update install guide for new pooch requirement

Fix pint 0.9 errors from units.wraps and iterable

Work around matplotlib issue with pint 0.9

Pint 0.9 fails to setup matplotlib on Python 2.7. We can work around
this by catching the resulting ImportError and falling back to our
internal matplotlib unit code.

Test issues with pull request

More precise decimal

Seperated gamma value into individual calculations

Remove space between header in new functions

Add in additional line

Remove extra line

Updated documentation

Updated docs

Updated documentation

update

test

Removed files

Add in indentation

Added note that x-axis can be any variable, due to feedback received from a user

Vendor functionality from xarray.core

Add tests for otherwised unused portions of xarray utilities

Add formulas to geopotential functions in docs and correct reference

MNT: Update some skewT image test thresholds

This gets the test suite passing with Matplotlib 3.1. Not sure what
changed, but a deep look at the differences only reveals some subtle
changes to just how black the individual tick marks are.

Updated year in LICENSE

Replace jrleeman with zbruick as a codeowner

Updated contributors in AUTHORS.txt and .mailmap

allow any pooch >= 0.1 to be used

Update install guide for new pooch requirement

Fix pint 0.9 errors from units.wraps and iterable

Work around matplotlib issue with pint 0.9

Pint 0.9 fails to setup matplotlib on Python 2.7. We can work around
this by catching the resulting ImportError and falling back to our
internal matplotlib unit code.

Add in indentation

Add in indentation

Edit indentation

Add in indentation

Edit indentation

Remove space

Edit indentation

Edited indentation

Edit indentation

Edit equation documentation

Edit equations

Update documentation

Fixed equation

Add in extra space

Realigned Equations

Fixed Indentation

Edited equations

Add in extra space

Removed blank line

Remove indent

Update documentation

Added in underscore for documentation

Updated references

Edit Documentation
@jthielen
Copy link
Contributor

After spending probably too much time on debugging this for #845, I'm pretty sure the issue is upstream in NumPy, so I've created an issue there: numpy/numpy#15200.

With that in mind, my PR for downcast types (incoming soon) will mark the relevant tests as xfail.

bors bot added a commit that referenced this issue Dec 30, 2019
963: Add tests and documentation with improvement of downcast type compatibility (part of #845) r=hgrecco a=jthielen

As a part of #845, this PR adds tests for downcast type compatibility with Sparse's `COO` and NumPy's `MaskedArray`, along with more careful handling of downcast types throughout the library. Also included is new documentation on array type compatibility, including the type casting hierarchy digraph by @shoyer and @crusaderky.

While this PR doesn't fully bring Pint's downcast type compatibility to a completed state, I think this gets it "good enough" for the upcoming release, and the remaining issues are fairly well defined:

- MaskedArray non-commutativity (#633 / numpy/numpy#15200)
- Dask compatibility (#883)
- Addition of CuPy tests (no issue on issue tracker yet)

Because of that, I think this can close #845, but if @hgrecco you want that kept open until the above items are resolved, let me know.

- [x] Closes #37; Closes #845
- [x] Executed ``black -t py36 . && isort -rc . && flake8`` with no errors
- [x] The change is fully covered by automated unit tests
- [x] Documented in docs/ as appropriate
- [x] Added an entry to the CHANGES file


Co-authored-by: Jon Thielen <github@jont.cc>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants