Skip to content

Return a plain Grid when indexing grid subclasses - #352

Open
syahra712 wants to merge 1 commit into
theochem:masterfrom
syahra712:fix-grid-subclass-indexing
Open

syahra712 wants to merge 1 commit into
theochem:masterfrom
syahra712:fix-grid-subclass-indexing

Conversation

@syahra712

Copy link
Copy Markdown
Contributor

Summary

Indexing most Grid subclasses fails, although indexing a plain Grid works:

import numpy as np
from grid.angular import AngularGrid
from grid.atomgrid import AtomGrid
from grid.basegrid import Grid
from grid.cubic import UniformGrid
from grid.onedgrid import GaussLegendre
from grid.rtransform import BeckeRTransform

AngularGrid(degree=5)[0:3]
# TypeError: AngularGrid.__init__() takes from 1 to 2 positional arguments but 3 were given

rgrid = BeckeRTransform(1e-4, 1.5).transform_1d_grid(GaussLegendre(10))
AtomGrid(rgrid, degrees=[5])[0]
# TypeError: Argument rgrid is not an instance of OneDGrid, got <class 'numpy.ndarray'>.

UniformGrid(np.zeros(3), np.eye(3) * 0.5, np.array([3, 3, 3]))[0]
# TypeError: UniformGrid.__init__() missing 1 required positional argument: 'shape'

Grid(np.random.rand(10, 3), np.ones(10)).get_localgrid(np.zeros(3), np.inf)[0]
# TypeError: LocalGrid.__init__() missing 1 required positional argument: 'center'

Cause: Grid.__getitem__ builds the selection with self.__class__(points, weights). That only works for classes whose constructor takes (points, weights). OneDGrid, MolGrid and PeriodicGrid define their own __getitem__. The classes above inherit the base one, and their constructors take other arguments.

Fix: Grid.__getitem__ now returns a plain Grid, as its docstring already says ("Return a new Grid object with selected points"). A subset of an atomic, angular or uniform grid is no longer that kind of grid anyway, for example it has no full set of shells or no regular shape. The classes with their own __getitem__ are unchanged.

Tests

  • New test_getitem_subclasses in src/grid/tests/test_grid.py indexes a LocalGrid, AngularGrid, AtomGrid and UniformGrid with 0, np.int64(2) and slice(1, 4). It checks that the result is a Grid with the selected points and weights.
  • All 4 cases fail on master and pass with this change. test_grid.py, test_periodicgrid.py and test_angular.py pass (159 passed).
  • black -l 100 --check on basegrid.py passes. On test_grid.py, black flags one blank line near the top that is already on master.

Grid.__getitem__ rebuilt the selection with self.__class__(points,
weights). AtomGrid, AngularGrid, LocalGrid and UniformGrid have other
constructor arguments, so grid[0] or grid[1:4] on them raised TypeError.

This branch has not been deployed

No deployments
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

Successfully merging this pull request may close these issues.

1 participant