def get_tidal_vectors(self, layer, time, bbox, vector_scale=None, vector_step=None): vector_scale = vector_scale or 1 vector_step = vector_step or 1 with netCDF4.Dataset(self.topology_file) as nc: data_obj = nc.variables[layer.access_name] data_location = getattr(data_obj, 'location', 'node') mesh_name = data_obj.mesh ug = UGrid.from_nc_dataset(nc, mesh_name=mesh_name) coords = np.empty(0) if data_location == 'node': coords = ug.nodes elif data_location == 'face': coords = ug.face_coordinates elif data_location == 'edge': coords = ug.edge_coordinates lon = coords[:, 0] lat = coords[:, 1] padding_factor = calc_safety_factor(vector_scale) padding = calc_lon_lat_padding(lon, lat, padding_factor) * vector_step spatial_idx = data_handler.ugrid_lat_lon_subset_idx( lon, lat, bbox=bbox, padding=padding) tnames = nc.get_variables_by_attributes( standard_name='tide_constituent')[0] tfreqs = nc.get_variables_by_attributes( standard_name='tide_frequency')[0] from utide import _ut_constants_fname from utide.utilities import loadmatbunch con_info = loadmatbunch(_ut_constants_fname)['const'] # Get names from the utide constant file utide_const_names = [e.strip() for e in con_info['name'].tolist()] # netCDF4-python is returning ugly arrays of bytes... names = [] for n in tnames[:]: z = ''.join([x.decode('utf-8') for x in n.tolist() if x]).strip() names.append(z) if 'STEADY' in names: names[names.index('STEADY')] = 'Z0' extract_names = list( set(utide_const_names).intersection(set(names))) ntides = data_obj.shape[data_obj.dimensions.index('ntides')] extract_mask = np.zeros(shape=(ntides, ), dtype=bool) for n in extract_names: extract_mask[names.index(n)] = True if not spatial_idx.any() or not extract_mask.any(): e = np.ma.empty(0) return e, e, e, e ua = nc.variables['u'][extract_mask, spatial_idx] va = nc.variables['v'][extract_mask, spatial_idx] up = nc.variables['u_phase'][extract_mask, spatial_idx] vp = nc.variables['v_phase'][extract_mask, spatial_idx] freqs = tfreqs[extract_mask] omega = freqs * 3600 # Convert from radians/s to radians/hour. from utide.harmonics import FUV from matplotlib.dates import date2num v, u, f = FUV( t=np.array([date2num(time) + 366.1667]), tref=np.array([0]), lind=np.array( [utide_const_names.index(x) for x in extract_names]), lat= 55, # Reference latitude for 3rd order satellites (degrees) (55 is fine always) ngflgs=[0, 0, 0, 0]) # [NodsatLint NodsatNone GwchLint GwchNone] s = calendar.timegm(time.timetuple()) / 60 / 60. v, u, f = map(np.squeeze, (v, u, f)) v = v * 2 * np.pi # Convert phase in radians. u = u * 2 * np.pi # Convert phase in radians. U = (f * ua.T * np.cos(v + s * omega + u - up.T * np.pi / 180)).sum(axis=1) V = (f * va.T * np.cos(v + s * omega + u - vp.T * np.pi / 180)).sum(axis=1) return U, V, lon[spatial_idx], lat[spatial_idx]
def getmap(self, layer, request): time_index, time_value = self.nearest_time(layer, request.GET['time']) wgs84_bbox = request.GET['wgs84_bbox'] with self.dataset() as nc: data_obj = nc.variables[layer.access_name] data_location = data_obj.location mesh_name = data_obj.mesh ug = UGrid.from_ncfile(self.topology_file, mesh_name=mesh_name) coords = np.empty(0) if data_location == 'node': coords = ug.nodes elif data_location == 'face': coords = ug.face_coordinates elif data_location == 'edge': coords = ug.edge_coordinates lon = coords[:, 0] lat = coords[:, 1] # Calculate any vector padding if we need to padding = None vector_step = request.GET['vectorstep'] if request.GET['image_type'] == 'vectors': padding_factor = calc_safety_factor(request.GET['vectorscale']) padding = calc_lon_lat_padding(lon, lat, padding_factor) * vector_step # Calculate the boolean spatial mask to slice with bool_spatial_idx = data_handler.ugrid_lat_lon_subset_idx(lon, lat, bbox=wgs84_bbox.bbox, padding=padding) # Randomize vectors to subset if we need to if request.GET['image_type'] == 'vectors' and vector_step > 1: num_vec = int(bool_spatial_idx.size / vector_step) step = int(bool_spatial_idx.size / num_vec) bool_spatial_idx[np.where(bool_spatial_idx==True)][0::step] = False # noqa: E225 # If no triangles intersect the field of view, return a transparent tile if not np.any(bool_spatial_idx): logger.info("No triangles in field of view, returning empty tile.") return self.empty_response(layer, request) if isinstance(layer, Layer): if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data = data_obj[time_index, z_index, :] elif (len(data_obj.shape) == 2): data = data_obj[time_index, :] elif len(data_obj.shape) == 1: data = data_obj[:] else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) return self.empty_response(layer, request) if request.GET['image_type'] in ['pcolor', 'contours', 'filledcontours']: # Avoid triangles with nan values bool_spatial_idx[np.isnan(data)] = False # Get the faces to plot faces = ug.faces[:] face_idx = data_handler.face_idx_from_node_idx(faces, bool_spatial_idx) faces_subset = faces[face_idx] tri_subset = Tri.Triangulation(lon, lat, triangles=faces_subset) if request.GET['image_type'] == 'pcolor': return mpl_handler.tripcolor_response(tri_subset, data, request, data_location=data_location) else: return mpl_handler.tricontouring_response(tri_subset, data, request) elif request.GET['image_type'] in ['filledhatches', 'hatches']: raise NotImplementedError('matplotlib does not support hatching on triangular grids... sorry!') else: raise NotImplementedError('Image type "{}" is not supported.'.format(request.GET['image_type'])) elif isinstance(layer, VirtualLayer): # Data needs to be [var1,var2] where var are 1D (nodes only, elevation and time already handled) data = [] for l in layer.layers: data_obj = nc.variables[l.var_name] if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data.append(data_obj[time_index, z_index, bool_spatial_idx]) elif (len(data_obj.shape) == 2): data.append(data_obj[time_index, bool_spatial_idx]) elif len(data_obj.shape) == 1: data.append(data_obj[bool_spatial_idx]) else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) return self.empty_response(layer, request) if request.GET['image_type'] == 'vectors': return mpl_handler.quiver_response(lon[bool_spatial_idx], lat[bool_spatial_idx], data[0], data[1], request) else: raise NotImplementedError('Image type "{}" is not supported.'.format(request.GET['image_type']))
def minmax(self, layer, request): time_index, time_value = self.nearest_time(layer, request.GET['time']) wgs84_bbox = request.GET['wgs84_bbox'] with self.dataset() as nc: data_obj = nc.variables[layer.access_name] data_location = data_obj.location mesh_name = data_obj.mesh ug = UGrid.from_ncfile(self.topology_file, mesh_name=mesh_name) coords = np.empty(0) if data_location == 'node': coords = ug.nodes elif data_location == 'face': coords = ug.face_coordinates elif data_location == 'edge': coords = ug.edge_coordinates lon = coords[:, 0] lat = coords[:, 1] spatial_idx = data_handler.ugrid_lat_lon_subset_idx(lon, lat, bbox=wgs84_bbox.bbox) vmin = None vmax = None data = None if isinstance(layer, Layer): if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data = data_obj[time_index, z_index, spatial_idx] elif (len(data_obj.shape) == 2): data = data_obj[time_index, spatial_idx] elif len(data_obj.shape) == 1: data = data_obj[spatial_idx] else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) if data is not None: vmin = np.nanmin(data).item() vmax = np.nanmax(data).item() elif isinstance(layer, VirtualLayer): # Data needs to be [var1,var2] where var are 1D (nodes only, elevation and time already handled) data = [] for l in layer.layers: data_obj = nc.variables[l.var_name] if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data.append(data_obj[time_index, z_index, spatial_idx]) elif (len(data_obj.shape) == 2): data.append(data_obj[time_index, spatial_idx]) elif len(data_obj.shape) == 1: data.append(data_obj[spatial_idx]) else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) if ',' in layer.var_name and data: # Vectors, so return magnitude data = [ sqrt((u * u) + (v * v)) for (u, v,) in data.T if u != np.nan and v != np.nan ] vmin = min(data) vmax = max(data) return gmd_handler.from_dict(dict(min=vmin, max=vmax))
def getmap(self, layer, request): time_index, time_value = self.nearest_time(layer, request.GET['time']) wgs84_bbox = request.GET['wgs84_bbox'] with self.dataset() as nc: data_obj = nc.variables[layer.access_name] data_location = data_obj.location mesh_name = data_obj.mesh ug = UGrid.from_ncfile(self.topology_file, mesh_name=mesh_name) coords = np.empty(0) if data_location == 'node': coords = ug.nodes elif data_location == 'face': coords = ug.face_coordinates elif data_location == 'edge': coords = ug.edge_coordinates lon = coords[:, 0] lat = coords[:, 1] # Calculate any vector padding if we need to padding = None vector_step = request.GET['vectorstep'] if request.GET['image_type'] == 'vectors': padding_factor = calc_safety_factor(request.GET['vectorscale']) padding = calc_lon_lat_padding(lon, lat, padding_factor) * vector_step # Calculate the boolean spatial mask to slice with bool_spatial_idx = data_handler.ugrid_lat_lon_subset_idx(lon, lat, bbox=wgs84_bbox.bbox, padding=padding) # Randomize vectors to subset if we need to if request.GET['image_type'] == 'vectors' and vector_step > 1: num_vec = int(bool_spatial_idx.size / vector_step) step = int(bool_spatial_idx.size / num_vec) bool_spatial_idx[np.where(bool_spatial_idx==True)][0::step] = False # If no triangles intersect the field of view, return a transparent tile if not np.any(bool_spatial_idx): logger.warning("No triangles in field of view, returning empty tile.") return self.empty_response(layer, request) if isinstance(layer, Layer): if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data = data_obj[time_index, z_index, :] elif (len(data_obj.shape) == 2): data = data_obj[time_index, :] elif len(data_obj.shape) == 1: data = data_obj[:] else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) return self.empty_response(layer, request) if request.GET['image_type'] in ['pcolor', 'contours', 'filledcontours']: # Avoid triangles with nan values bool_spatial_idx[np.isnan(data)] = False # Get the faces to plot faces = ug.faces[:] face_idx = data_handler.face_idx_from_node_idx(faces, bool_spatial_idx) faces_subset = faces[face_idx] tri_subset = Tri.Triangulation(lon, lat, triangles=faces_subset) if request.GET['image_type'] == 'pcolor': return mpl_handler.tripcolor_response(tri_subset, data, request, data_location=data_location) else: return mpl_handler.tricontouring_response(tri_subset, data, request) elif request.GET['image_type'] in ['filledhatches', 'hatches']: raise NotImplementedError('matplotlib does not support hatching on triangular grids... sorry!') else: raise NotImplementedError('Image type "{}" is not supported.'.format(request.GET['image_type'])) elif isinstance(layer, VirtualLayer): # Data needs to be [var1,var2] where var are 1D (nodes only, elevation and time already handled) data = [] for l in layer.layers: data_obj = nc.variables[l.var_name] if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data.append(data_obj[time_index, z_index, bool_spatial_idx]) elif (len(data_obj.shape) == 2): data.append(data_obj[time_index, bool_spatial_idx]) elif len(data_obj.shape) == 1: data.append(data_obj[bool_spatial_idx]) else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) return self.empty_response(layer, request) if request.GET['image_type'] == 'vectors': return mpl_handler.quiver_response(lon[bool_spatial_idx], lat[bool_spatial_idx], data[0], data[1], request) else: raise NotImplementedError('Image type "{}" is not supported.'.format(request.GET['image_type']))
def minmax(self, layer, request): time_index, time_value = self.nearest_time(layer, request.GET['time']) wgs84_bbox = request.GET['wgs84_bbox'] with self.dataset() as nc: data_obj = nc.variables[layer.access_name] data_location = data_obj.location mesh_name = data_obj.mesh ug = UGrid.from_ncfile(self.topology_file, mesh_name=mesh_name) coords = np.empty(0) if data_location == 'node': coords = ug.nodes elif data_location == 'face': coords = ug.face_coordinates elif data_location == 'edge': coords = ug.edge_coordinates lon = coords[:, 0] lat = coords[:, 1] spatial_idx = data_handler.ugrid_lat_lon_subset_idx(lon, lat, bbox=wgs84_bbox.bbox) vmin = None vmax = None data = None if isinstance(layer, Layer): if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data = data_obj[time_index, z_index, spatial_idx] elif (len(data_obj.shape) == 2): data = data_obj[time_index, spatial_idx] elif len(data_obj.shape) == 1: data = data_obj[spatial_idx] else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) if data is not None: vmin = np.nanmin(data).item() vmax = np.nanmax(data).item() elif isinstance(layer, VirtualLayer): # Data needs to be [var1,var2] where var are 1D (nodes only, elevation and time already handled) data = [] for l in layer.layers: data_obj = nc.variables[l.var_name] if (len(data_obj.shape) == 3): z_index, z_value = self.nearest_z(layer, request.GET['elevation']) data.append(data_obj[time_index, z_index, spatial_idx]) elif (len(data_obj.shape) == 2): data.append(data_obj[time_index, spatial_idx]) elif len(data_obj.shape) == 1: data.append(data_obj[spatial_idx]) else: logger.debug("Dimension Mismatch: data_obj.shape == {0} and time = {1}".format(data_obj.shape, time_value)) if ',' in layer.var_name and data: # Vectors, so return magnitude data = [ sqrt((u*u) + (v*v)) for (u, v,) in data.T if u != np.nan and v != np.nan] vmin = min(data) vmax = max(data) return gmd_handler.from_dict(dict(min=vmin, max=vmax))
def get_tidal_vectors(self, layer, time, bbox, vector_scale=None, vector_step=None): vector_scale = vector_scale or 1 vector_step = vector_step or 1 with netCDF4.Dataset(self.topology_file) as nc: data_obj = nc.variables[layer.access_name] data_location = getattr(data_obj, 'location', 'node') mesh_name = data_obj.mesh ug = UGrid.from_nc_dataset(nc, mesh_name=mesh_name) coords = np.empty(0) if data_location == 'node': coords = ug.nodes elif data_location == 'face': coords = ug.face_coordinates elif data_location == 'edge': coords = ug.edge_coordinates lon = coords[:, 0] lat = coords[:, 1] padding_factor = calc_safety_factor(vector_scale) padding = calc_lon_lat_padding(lon, lat, padding_factor) * vector_step spatial_idx = data_handler.ugrid_lat_lon_subset_idx(lon, lat, bbox=bbox, padding=padding) tnames = nc.get_variables_by_attributes(standard_name='tide_constituent')[0] tfreqs = nc.get_variables_by_attributes(standard_name='tide_frequency')[0] from utide import _ut_constants_fname from utide.utilities import loadmatbunch con_info = loadmatbunch(_ut_constants_fname)['const'] # Get names from the utide constant file utide_const_names = [ e.strip() for e in con_info['name'].tolist() ] # netCDF4-python is returning ugly arrays of bytes... names = [] for n in tnames[:]: z = ''.join([ x.decode('utf-8') for x in n.tolist() if x ]).strip() names.append(z) if 'STEADY' in names: names[names.index('STEADY')] = 'Z0' extract_names = list(set(utide_const_names).intersection(set(names))) ntides = data_obj.shape[data_obj.dimensions.index('ntides')] extract_mask = np.zeros(shape=(ntides,), dtype=bool) for n in extract_names: extract_mask[names.index(n)] = True if not spatial_idx.any() or not extract_mask.any(): e = np.ma.empty(0) return e, e, e, e ua = nc.variables['u'][extract_mask, spatial_idx] va = nc.variables['v'][extract_mask, spatial_idx] up = nc.variables['u_phase'][extract_mask, spatial_idx] vp = nc.variables['v_phase'][extract_mask, spatial_idx] freqs = tfreqs[extract_mask] omega = freqs * 3600 # Convert from radians/s to radians/hour. from utide.harmonics import FUV from matplotlib.dates import date2num v, u, f = FUV(t=np.array([date2num(time) + 366.1667]), tref=np.array([0]), lind=np.array([ utide_const_names.index(x) for x in extract_names ]), lat=55, # Reference latitude for 3rd order satellites (degrees) (55 is fine always) ngflgs=[0, 0, 0, 0]) # [NodsatLint NodsatNone GwchLint GwchNone] s = calendar.timegm(time.timetuple()) / 60 / 60. v, u, f = map(np.squeeze, (v, u, f)) v = v * 2 * np.pi # Convert phase in radians. u = u * 2 * np.pi # Convert phase in radians. U = (f * ua.T * np.cos(v + s * omega + u - up.T * np.pi / 180)).sum(axis=1) V = (f * va.T * np.cos(v + s * omega + u - vp.T * np.pi / 180)).sum(axis=1) return U, V, lon[spatial_idx], lat[spatial_idx]