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

interpolPlot: Lasso() is giving Value Error #44

Open
Tanvi-Jain01 opened this issue Jun 26, 2023 · 0 comments
Open

interpolPlot: Lasso() is giving Value Error #44

Tanvi-Jain01 opened this issue Jun 26, 2023 · 0 comments

Comments

@Tanvi-Jain01
Copy link

Tanvi-Jain01 commented Jun 26, 2023

InterpolPlot: Lasso is giving ValueError in Colormesh

Code:

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression,Lasso

 
`[Delhi.zip](https://github.com/sustainability-lab/vayu/files/11862499/Delhi.zip)`
gdf_shape = (r'C:\Users\...\Delhi\Districts.shp')
gdf_shape = gpd.read_file(gdf_shape)
print(gdf_shape)


from vayu.interpolPlot import interpolPlot

min_lat = 28.4
max_lat = 28.8
min_lon = 76.8
max_lon = 77.3


resolution = 3
np.random.seed(123)  

lat_grid, lon_grid = np.meshgrid(np.linspace(min_lat, max_lat, resolution), np.linspace(min_lon, max_lon, resolution))

date = pd.to_datetime('2022-08-23')
pm25_grid=np.random.rand(resolution,resolution)

df = pd.DataFrame({
    'longitude': lon_grid.flatten(),
    'latitude': lat_grid.flatten(),
    'pm25': pm25_grid.flatten(),
    'date': pd.Series([date] * (resolution ** 2))
})

print(df)

interpolator = Lasso()

interpolPlot(df, gdf_shape, 'longitude','latitude', 'pm25', interpolator, resolution=50, partitions=15, cmap='inferno', Tcolor='k', markersize=0.3, plot_train_points=True, extrapolate=True)
 

Error:

ValueError                                Traceback (most recent call last)
Cell In[20], line 39
     32 interpolator = Lasso()
     33 #interpolator = LinearRegression()
---> 39 interpolPlot(df, gdf_shape, 'longitude','latitude', 'pm25', interpolator, resolution=50, partitions=15, cmap='inferno', Tcolor='k', markersize=0.3, plot_train_points=True, extrapolate=True)

File ~\anaconda3\lib\site-packages\vayu\interpolPlot.py:191, in interpolPlot(df, shape_df, long, lat, pollutant, Interpolator, resolution, partitions, cmap, Tcolor, markersize, plot_train_points, extrapolate)
    188 ax.legend()
    190 bounds = np.linspace(vmin, vmax, partitions)
--> 191 fig.colorbar(sm, cax=cax, ticks=bounds, 
    192     boundaries=bounds, format="%.2f")
    193 return ax

File ~\anaconda3\lib\site-packages\matplotlib\figure.py:1293, in FigureBase.colorbar(self, mappable, cax, ax, use_gridspec, **kwargs)
   1289 NON_COLORBAR_KEYS = ['fraction', 'pad', 'shrink', 'aspect', 'anchor',
   1290                      'panchor']
   1291 cb_kw = {k: v for k, v in kwargs.items() if k not in NON_COLORBAR_KEYS}
-> 1293 cb = cbar.Colorbar(cax, mappable, **cb_kw)
   1295 if not userax:
   1296     self.sca(current_ax)

File ~\anaconda3\lib\site-packages\matplotlib\_api\deprecation.py:384, in delete_parameter.<locals>.wrapper(*inner_args, **inner_kwargs)
    379 @functools.wraps(func)
    380 def wrapper(*inner_args, **inner_kwargs):
    381     if len(inner_args) <= name_idx and name not in inner_kwargs:
    382         # Early return in the simple, non-deprecated case (much faster than
    383         # calling bind()).
--> 384         return func(*inner_args, **inner_kwargs)
    385     arguments = signature.bind(*inner_args, **inner_kwargs).arguments
    386     if is_varargs and arguments.get(name):

File ~\anaconda3\lib\site-packages\matplotlib\colorbar.py:402, in Colorbar.__init__(self, ax, mappable, cmap, norm, alpha, values, boundaries, orientation, ticklocation, extend, spacing, ticks, format, drawedges, filled, extendfrac, extendrect, label, location)
    399 self.ticklocation = ticklocation
    401 self.set_label(label)
--> 402 self._reset_locator_formatter_scale()
    404 if np.iterable(ticks):
    405     self._locator = ticker.FixedLocator(ticks, nbins=len(ticks))

File ~\anaconda3\lib\site-packages\matplotlib\colorbar.py:1173, in Colorbar._reset_locator_formatter_scale(self)
   1167 def _reset_locator_formatter_scale(self):
   1168     """
   1169     Reset the locator et al to defaults.  Any user-hardcoded changes
   1170     need to be re-entered if this gets called (either at init, or when
   1171     the mappable normal gets changed: Colorbar.update_normal)
   1172     """
-> 1173     self._process_values()
   1174     self._locator = None
   1175     self._minorlocator = None

File ~\anaconda3\lib\site-packages\matplotlib\colorbar.py:1107, in Colorbar._process_values(self)
   1105     self.norm.vmin = 0
   1106     self.norm.vmax = 1
-> 1107 self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(
   1108     self.norm.vmin, self.norm.vmax, expander=0.1)
   1109 if (not isinstance(self.norm, colors.BoundaryNorm) and
   1110         (self.boundaries is None)):
   1111     b = self.norm.inverse(b)

File ~\anaconda3\lib\site-packages\matplotlib\colors.py:1250, in Normalize.vmin(self, value)
   1248 if value != self._vmin:
   1249     self._vmin = value
-> 1250     self._changed()

File ~\anaconda3\lib\site-packages\matplotlib\colors.py:1278, in Normalize._changed(self)
   1273 def _changed(self):
   1274     """
   1275     Call this whenever the norm is changed to notify all the
   1276     callback listeners to the 'changed' signal.
   1277     """
-> 1278     self.callbacks.process('changed')

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:309, in CallbackRegistry.process(self, s, *args, **kwargs)
    307 except Exception as exc:
    308     if self.exception_handler is not None:
--> 309         self.exception_handler(exc)
    310     else:
    311         raise

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:96, in _exception_printer(exc)
     94 def _exception_printer(exc):
     95     if _get_running_interactive_framework() in ["headless", None]:
---> 96         raise exc
     97     else:
     98         traceback.print_exc()

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:304, in CallbackRegistry.process(self, s, *args, **kwargs)
    302 if func is not None:
    303     try:
--> 304         func(*args, **kwargs)
    305     # this does not capture KeyboardInterrupt, SystemExit,
    306     # and GeneratorExit
    307     except Exception as exc:

File ~\anaconda3\lib\site-packages\matplotlib\cm.py:665, in ScalarMappable.changed(self)
    660 def changed(self):
    661     """
    662     Call this whenever the mappable is changed to notify all the
    663     callbackSM listeners to the 'changed' signal.
    664     """
--> 665     self.callbacks.process('changed', self)
    666     self.stale = True

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:309, in CallbackRegistry.process(self, s, *args, **kwargs)
    307 except Exception as exc:
    308     if self.exception_handler is not None:
--> 309         self.exception_handler(exc)
    310     else:
    311         raise

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:96, in _exception_printer(exc)
     94 def _exception_printer(exc):
     95     if _get_running_interactive_framework() in ["headless", None]:
---> 96         raise exc
     97     else:
     98         traceback.print_exc()

File ~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py:304, in CallbackRegistry.process(self, s, *args, **kwargs)
    302 if func is not None:
    303     try:
--> 304         func(*args, **kwargs)
    305     # this does not capture KeyboardInterrupt, SystemExit,
    306     # and GeneratorExit
    307     except Exception as exc:

File ~\anaconda3\lib\site-packages\matplotlib\colorbar.py:514, in Colorbar.update_normal(self, mappable)
    511     self.norm = mappable.norm
    512     self._reset_locator_formatter_scale()
--> 514 self._draw_all()
    515 if isinstance(self.mappable, contour.ContourSet):
    516     CS = self.mappable

File ~\anaconda3\lib\site-packages\matplotlib\colorbar.py:579, in Colorbar._draw_all(self)
    577 if self._extend_upper():
    578     ind = ind[:-1]
--> 579 self._add_solids(X, Y, self._values[ind, np.newaxis])

File ~\anaconda3\lib\site-packages\matplotlib\colorbar.py:595, in Colorbar._add_solids(self, X, Y, C)
    593     self._add_solids_patches(X, Y, C, mappable)
    594 else:
--> 595     self.solids = self.ax.pcolormesh(
    596         X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha,
    597         edgecolors='none', shading='flat')
    598     if not self.drawedges:
    599         if len(self._y) >= self.n_rasterize:

File ~\anaconda3\lib\site-packages\matplotlib\__init__.py:1442, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
   1439 @functools.wraps(func)
   1440 def inner(ax, *args, data=None, **kwargs):
   1441     if data is None:
-> 1442         return func(ax, *map(sanitize_sequence, args), **kwargs)
   1444     bound = new_sig.bind(ax, *args, **kwargs)
   1445     auto_label = (bound.arguments.get(label_namer)
   1446                   or bound.kwargs.get(label_namer))

File ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py:6220, in Axes.pcolormesh(self, alpha, norm, cmap, vmin, vmax, shading, antialiased, *args, **kwargs)
   6217 shading = shading.lower()
   6218 kwargs.setdefault('edgecolors', 'none')
-> 6220 X, Y, C, shading = self._pcolorargs('pcolormesh', *args,
   6221                                     shading=shading, kwargs=kwargs)
   6222 coords = np.stack([X, Y], axis=-1)
   6223 # convert to one dimensional array, except for 3D RGB(A) arrays

File ~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py:5717, in Axes._pcolorargs(self, funcname, shading, *args, **kwargs)
   5715 if funcname == 'pcolormesh':
   5716     if np.ma.is_masked(X) or np.ma.is_masked(Y):
-> 5717         raise ValueError(
   5718             'x and y arguments to pcolormesh cannot have '
   5719             'non-finite values or be of type '
   5720             'numpy.ma.core.MaskedArray with masked values')
   5721     # safe_masked_invalid() returns an ndarray for dtypes other
   5722     # than floating point.
   5723     if isinstance(X, np.ma.core.MaskedArray):

ValueError: x and y arguments to pcolormesh cannot have non-finite values or be of type numpy.ma.core.MaskedArray with masked values

Reason:

The error is in producing 15(or n) partition in colormesh when lasso is giving a constant value, as constant value cant be divided into 15(or n) partition.

Solution:

As a solution, code should have a try-catch block so it will ignore that error, for smooth execution.

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

1 participant