def dispatch(self, url, *args, **kwargs): """ Call the corresponding method based on protocol in url. chained protocols will be called with the result of the previous protocol as input overrides are passed to any protocol whos signature can accept them. """ # separate the protocol name from the path protocol, _, path = url.partition(self.SCHEME_SEP) # find the corresponding protocol method meth = self._LOOKUP.get(protocol, None) if meth is None: # unrecognized protocol # evaluate as string-literal return url if self.SCHEME_SEP in path: # url contains a nested protocol # first call sub-protocol arg = self.dispatch(path, **kwargs) else: # we are at the end of the chain # method should be called with path as argument arg = path # filter kwargs to pass only the kwargs # accepted by the method. kwargs = straxen.filter_kwargs(meth, kwargs) return meth(arg, *args, **kwargs)
def test_filter_kwargs(self): all_kwargs = dict(a=1, b=2, c=3) # test a function that takes only a seubset of the kwargs def func1(a=None, b=None): return filtered1 = straxen.filter_kwargs(func1, all_kwargs) self.assertEqual(filtered1, dict(a=1, b=2)) func1(**filtered1) # test function that accepts wildcard kwargs def func2(**kwargs): return filtered2 = straxen.filter_kwargs(func2, all_kwargs) self.assertEqual(filtered2, all_kwargs) func2(**filtered2)
def _weighted_nearest_neighbors(csys, map_data, array_valued, **kwargs): if array_valued: map_data = map_data.reshape((-1, map_data.shape[-1])) else: map_data = map_data.flatten() kwargs = straxen.filter_kwargs(InterpolateAndExtrapolate, kwargs) return InterpolateAndExtrapolate(csys, map_data, array_valued=array_valued, **kwargs)
def _regular_grid_interpolator(csys, map_data, array_valued, **kwargs): dimensions = len(csys[0]) grid = [np.unique(csys[:, i]) for i in range(dimensions)] grid_shape = [len(g) for g in grid] if array_valued: map_data = map_data.reshape((*grid_shape, map_data.shape[-1])) else: map_data = map_data.reshape(*grid_shape) config = dict(bounds_error=False, fill_value=None) kwargs = straxen.filter_kwargs(RegularGridInterpolator, kwargs) config.update(kwargs) return RegularGridInterpolator(tuple(grid), map_data, **config)
def _rect_bivariate_spline(csys, map_data, array_valued, **kwargs): dimensions = len(csys[0]) grid = [np.unique(csys[:, i]) for i in range(dimensions)] grid_shape = [len(g) for g in grid] assert dimensions == 2, 'RectBivariateSpline interpolate maps of dimension 2' assert not array_valued, 'RectBivariateSpline does not support interpolating array values' map_data = map_data.reshape(*grid_shape) kwargs = straxen.filter_kwargs(RectBivariateSpline, kwargs) rbs = RectBivariateSpline(grid[0], grid[1], map_data, **kwargs) def arg_formated_rbs(positions): if isinstance(positions, list): positions = np.array(positions) return rbs.ev(positions[:, 0], positions[:, 1]) return arg_formated_rbs