def removeLandPixels(self): # Remove values that are on mainland or lakes print("Removing values on mainland and lakes...\n") lats, lons = np.meshgrid(self.lats, self.lons) isLand = globe.is_land(lats.T, lons.T) for k in range(len(self.data)): self.data[k].mask = isLand | self.data[k].mask latsRef, lonsRef = np.meshgrid(self.RefSet.lats, self.RefSet.lons) isLand = globe.is_land(latsRef.T, lonsRef.T) for k in range(len(self.RefSet.data)): self.RefSet.data[k].mask = isLand | self.RefSet.data[k].mask lats, lons = np.meshgrid(self.lons, self.lats) latsRef, lonsRef = np.meshgrid(self.RefSet.lons, self.RefSet.lats) newMask = griddata((lonsRef.flatten(), latsRef.flatten()), self.RefSet.data[0].mask.flatten(), (lons, lats), method='nearest') for k in range(len(self.data)): self.data[k].mask = newMask | self.data[k].mask print("Finished preprocessing.\n")
def extract(self): # Get IBTrACS table table_name = self.CONFIG['ibtracs']['table_name'][self.basin] IBTrACS = utils.get_class_by_tablename(self.engine, table_name) tc_query = self.session.query(IBTrACS).filter( IBTrACS.date_time >= self.period[0], IBTrACS.date_time <= self.period[1]) total = tc_query.count() # Traverse WP TCs for idx, tc in enumerate(tc_query): try: converted_lon = utils.longitude_converter( tc.lon, '360', '-180') if bool(globe.is_land(tc.lat, converted_lon)): continue if tc.date_time.minute or tc.date_time.second: continue if idx < total - 1: next_tc = tc_query[idx + 1] # This TC and next TC is same TC if tc.sid == next_tc.sid: self.extract_between_two_tc_records(tc, next_tc) # This TC differents next TC else: success = self.extract_detail(tc) self.info_after_extracting_detail(tc, success, True) else: success = self.extract_detail(tc) self.info_after_extracting_detail(tc, success, True) except Exception as msg: breakpoint() exit(msg)
def land_sea_mask(array, boundaries): """ Parameters ---------- array : np.array geolocated 2d np.array that describes the values to be tested for land/sea. boundaries : list list defining the boundaries of array: [lat_min, lat_max, lon_min, lon_max]. Returns ------- None. """ # Defining the lat and longitudinal ranges latrange = np.linspace(boundaries[0], boundaries[1], len(array)) lonrange = np.linspace(boundaries[2], boundaries[3], len(array[0])) # Check for all lat/lon values if they are land (1) or water (0) mask = [] for lat in range(len(latrange)): is_on_land = globe.is_land(latrange[lat], lonrange) is_on_land = is_on_land.astype(int) mask.append(is_on_land) mask = np.array(mask) land_arr = mask * array return land_arr
def _create_coordinate_grid(self, cell_size = 1): """ Create a grid of lon/lat points based on training boundaries Args: cell_size (float): Degrees contained within each grid cell Returns: coordinate_grid (array): Coordinate grid (land-mass only) """ ## Boundaries xmin = int(self._coord_bounds[0][0] - 1) xmax = int(self._coord_bounds[0][1] + 1) ymin = int(self._coord_bounds[1][0] - 1) ymax = int(self._coord_bounds[1][1] + 1) ## Coordinates lon_coord = [xmin] lat_coord = [ymin] while lon_coord[-1] < xmax: lon_coord.append(min(lon_coord[-1] + cell_size, xmax)) while lat_coord[-1] < ymax: lat_coord.append(min(lat_coord[-1] + cell_size, ymax)) coordinate_grid = [] for x in lon_coord: for y in lat_coord: if globe.is_land(y, x): coordinate_grid.append([x, y]) coordinate_grid = np.array(coordinate_grid) return coordinate_grid
def get_land_coordinates(progressbar, number=500): ''' It generates a list of points distributed on the Earth land ''' #pb = ProgressBar('Generating points...', number) progressbar.start() progressbar["maximum"] = number i = 0 points = np.zeros((3, number)) while i < number: lat, lon = new_point() # If the generated point is on land, it will be added to the list # otherwise a new point will be generated if globe.is_land(lat, lon): points[0, i] = lat points[1, i] = lon progressbar["value"] = i progressbar.update() i = i + 1 print(' # Points generated') save_points(points) progressbar.stop() return points
def yoke(): while True: x = Latitude() if x > 90: x = 90 y = Longtitude() if y > 180: y = 180 globe_land_mask = globe.is_land(x, y) if globe_land_mask == False: break yoke = "yoke," + str(x) + "," + str(y) return yoke ##################################################################### #print("Random float number between 10 and 100 is ", rd.uniform(10, 100)) #print("Random float number between 25.5 and 250 is ", rd.uniform(25.5, 250)) #print("Random float number between 250 and 25.5 is ", rd.uniform(250, 25.5)) #globe_land_mask = globe.is_land(-42.13718611111111, 54.26108055555555) #print(globe_land_mask) #for _ in range(3): # t=turtle() # y=yoke() # print(t) # print(y)
def gen_scs_era5_entity(self, SCSERA5): entity = [] lons_num = int((self.lon2 - self.lon1) / self.spa_resolu) + 1 lats_num = int((self.lat2 - self.lat1) / self.spa_resolu) + 1 # Traverse through meridians first for lon in np.linspace(self.lon1, self.lon2, lons_num): x = self.grid_lons.index(lon) # Traverse through parallels then for lat in np.linspace(self.lat1, self.lat2, lats_num): is_land = bool(globe.is_land(lat, lon)) if is_land: continue y = self.grid_lats.index(lat) row = SCSERA5() row.x = x row.y = y row.lon = float(lon) row.lat = float(lat) row.land = is_land row.x_y = f'{x}_{y}' row.satel_era5_diff_mins = 0 entity.append(row) return entity
def setup_grid(self): # Create grid table # Grid = self.create_grid_table() Base.metadata.create_all(self.engine) lons, lats = self.gen_lons_lats() xs = [x for x in range(len(lons))] ys = [y for y in range(len(lats))] save_pickle = [ {'name': 'lons', 'var': lons}, {'name': 'lats', 'var': lats}, {'name': 'x', 'var': xs}, {'name': 'y', 'var': ys} ] for name_var_pair in save_pickle: name = name_var_pair['name'] var = name_var_pair['var'] pickle_path = self.CONFIG['grid']['pickle'][name] os.makedirs(os.path.dirname(pickle_path), exist_ok=True) with open(pickle_path, 'wb') as f: pickle.dump(var, f) total = len(lons) half_edge = 0.5 * self.spa_resolu grid_pts = [] self.logger.info(f'Generating grid') # Traverse lon for lon_idx, lon in enumerate(lons): print(f'\r{lon_idx+1}/{total}', end='') # Traverse lat for lat_idx, lat in enumerate(lats): # Cal y and x pt = Grid() pt.x = lon_idx pt.y = lat_idx pt.x_y = f'{pt.x}_{pt.y}' pt.lon = lon pt.lat = lat pt.lon1, pt.lon2 = pt.lon - half_edge, pt.lon + half_edge pt.lat1, pt.lat2 = pt.lat - half_edge, pt.lat + half_edge # Check whether the point is ocean or not pt.land = bool(globe.is_land(lat, lon)) grid_pts.append(pt) utils.delete_last_lines() print('Done') # Bulk insert utils.bulk_insert_avoid_duplicate_unique( grid_pts, self.CONFIG['database']\ ['batch_size']['insert'], Grid, ['x_y'], self.session, check_self=True)
def land_mask(): x = np.arange(-180, 180, 5) lon_grid, lat_grid = get_lon_lat() is_on_land = globe.is_land(lat_grid, lon_grid) is_on_land = np.concatenate([is_on_land[:, x >= 0], is_on_land[:, x < 0]], axis=1) # plt.imshow(is_on_land[::-1, :]) # plt.show() return is_on_land
def get_land_mask(ds): lat = ds.lat.values.copy() lon = ds.lon.values.copy() lon[lon > 180] = lon[lon > 180] - 360 lon[lon <= -180] = lon[lon <= -180] + 360 lon_grid, lat_grid = np.meshgrid(lon, lat) land_mask = torch.from_numpy( globe.is_land(lat_grid, lon_grid).astype(np.float32)).unsqueeze(0) return land_mask
def create_static_groups(self, static_objects: Dict[int, Dict[str, Any]], country_name: str, coalition: str, max_dist: int = 1000, min_objects: int = 5) -> List[Group]: """ :param static_objects: the static objects from the mission.lua file :param country_name: the static objects' country :param coalition: blue or red :param max_dist: maximum distance of a static from a group to be in that group :param min_objects: minimum amount of objects to be considered a base :return: list of groups """ dist = lambda p1, p2: np.sqrt(((p1[0] - p2[0])**2) + ((p1[1] - p2[1])**2)) static_clumps = [] for static_i, static in static_objects.items(): for group_i, group in enumerate(static_clumps): if dist((group['x'].mean(), group['y'].mean()), (static['x'], static['y'])) < max_dist: new_group = group.copy() new_group['x'] = np.append(new_group['x'], static['x']) new_group['y'] = np.append(new_group['y'], static['y']) new_group['objects'].append(static_i) new_group['type'] = 'FARP' if static['units'][1].get( "category") == 'Heliports' else new_group['type'] static_clumps[group_i] = new_group break else: group_type = 'Base' group_type = 'FARP' if static['units'][1].get( 'category') == 'Heliports' else group_type new_group = { 'x': np.array(static['x']), 'y': np.array(static['y']), 'objects': [static_i], 'type': group_type } static_clumps.append(new_group) groups = [] for clump in static_clumps: if len(clump['objects']) >= min_objects: lat, lon = self.xy2ll.transform(clump['x'].mean(), clump['y'].mean()) if globe.is_land(lat, lon): group = Group(group_type='static', unit_type=clump['type'], name=uuid.uuid4().hex, country=country_name, coalition=coalition, lat=lat, lon=lon) groups.append(group) return groups
def _pandas(cls, column, land_or_ocean="land", **kwargs): if land_or_ocean == "land": return column.apply( lambda point: globe.is_land(point[0], point[1])) elif land_or_ocean == "ocean": return column.apply( lambda point: globe.is_ocean(point[0], point[1])) else: raise ValueError("land_or_ocean must be 'land' or 'ocean'")
def makeLandMaskYear(data): log.info('[START] {}'.format('makeLandMaskYear')) result = None try: lon1D = sorted(set(data['lon'].values)) lat1D = sorted(set(data['lat'].values)) time1D = sorted(set(data['year'].values)) # 경도 변환 (0~360 to -180~180) convLon1D = [] for i, lon in enumerate(lon1D): convLon1D.append((lon + 180) % 360 - 180) lon2D, lat2D = np.meshgrid(convLon1D, lat1D) isLand2D = globe.is_land(lat2D, lon2D) isLand3D = np.tile(isLand2D, (len(time1D), 1, 1)) landData = xr.Dataset( { 'isLand': (('year', 'lat', 'lon'), (isLand3D).reshape(len(time1D), len(lat1D), len(lon1D))) }, coords={ 'lat': lat1D, 'lon': lon1D, 'year': time1D }) # 육해상에 대한 강수량 dataL1 = xr.merge([data, landData]) result = { 'msg': 'succ', 'lon1D': lon1D, 'lat1D': lat1D, 'time1D': time1D, 'isLand2D': isLand2D, 'isLand3D': isLand3D, 'resData': dataL1 } return result except Exception as e: log.error('Exception : {}'.format(e)) return result finally: # try, catch 구문이 종료되기 전에 무조건 실행 log.info('[END] {}'.format('makeLandMaskYear'))
def is_on_land(points): leng = len(points) w = [] for index in range(leng): [lat, lon] = points[index] is_on = globe.is_land(lat, lon) if is_on: w.append(True) else: w.append(False) return w
def naptan_coastal_nodes(cls, gdf): # TODO - add a column to the master naptan dataframe, and then count up # false values, to get the percent of stops that fail, and then compare # those stops, to find out which ones are near the coast and how near # the coast they are. """[summary] provided a dataframe, returns a list of nodes that are near the coast line, this uses global land mask library, a numpy & pandas extension, for mapping the boundaries of the coastline. Arguments: df {[geospatial dataframe]} -- [the naptan master dataframe.] Raises: ve: [Raises description] e: [] Returns: [type] -- [description] """ check_name = "naptan_coastal_nodes" try: # remove ferry based stops / jetty stop types, as they proximity to the # coastline isn't a problem. coastal_infrastructure = ['FTD', 'FBT', 'FER'] gdf = gdf[~gdf['StopType'].isin(coastal_infrastructure)] # we compare against the compressed land geometry dataset for # coordinates outside the coastline. gdf['Land_State'] = globe.is_land(gdf['Latitude'], gdf['Longitude']) coastal_nodes = gdf.loc[~gdf.Land_State] # get the count of failing nodes as a values high_node_areas = coastal_nodes['LocalityName'].value_counts() percent = ((len(coastal_nodes) / len(gdf)) * 100.0) # if the number of nodes is over this percent, console warning. if percent >= 1.1: print( f"The {gdf.AreaName.iloc[0]} has {len(coastal_nodes)} stops\ that are off the UK Coastline, that is {percent: 0.2f} %\ of all stops in the named admin area.") elif percent <= 0: print('No Nodes were found along the coastline.') pass else: print( f"The area has {len(coastal_nodes)} nodes that are off the\ coastline boundary. UK coastline, this is {percent: 0.2f} % of all nodes in the area.") rep.report_failing_nodes(gdf, check_name, coastal_nodes) return high_node_areas except ValueError as ve: raise(ve) except Exception as e: print(e)
def compare_with_isd(self): """Compare wind speed from different data sources with ISD's wind speed. """ # Get ISD windspd isd_manager = isd.ISDManager(self.CONFIG, self.period, self.region, self.db_root_passwd, work_mode='') # Download ISD csvs in period isd_csv_paths = isd_manager.download_and_read_scs_data() # Get windspd from different sources # Get IBTrACS table table_name = self.CONFIG['ibtracs']['table_name']['scs'] IBTrACS = utils.get_class_by_tablename(self.engine, table_name) sources_str = '' for idx, src in enumerate(self.sources): if idx < len(self.sources) - 1: sources_str = f"""{sources_str}{src.upper()} and """ else: sources_str = f"""{sources_str}{src.upper()}""" # Filter TCs during period for tc in self.session.query(IBTrACS).filter( IBTrACS.date_time >= self.period[0], IBTrACS.date_time <= self.period[1]).yield_per( self.CONFIG['database']['batch_size']['query']): # if tc.wind < 64: continue if tc.r34_ne is None: continue if bool(globe.is_land(tc.lat, tc.lon)): continue # Draw windspd from CCMP, ERA5, Interium # and several satellites # self.just_download_era5_equivalent_wind(tc) success = self.get_concurrent_data(isd_csv_paths, tc) if success: print((f"""Comparing {sources_str} with ISD record """ f"""when TC {tc.name} existed on """ f"""{tc.date_time}""")) else: print((f"""Skiping comparsion of {sources_str} with """ f"""ISD record when TC {tc.name} existed """ f"""on {tc.date_time}""")) print('Done')
def get_information(): """This function calls both api and add information to the pandas dataframe column""" new = getting_ip_address() new['info'] = new['ip'].apply(lambda row: getting_ip(row)) new['time_zone'] = new['info'].apply(lambda row: row['time_zone']) new['latitude'] = new['info'].apply(lambda row: row['latitude']) new['longitude'] = new['info'].apply(lambda row: row['longitude']) new['on_land'] = new.apply( lambda row: globe.is_land(row['latitude'], row['longitude']), axis=1) new = new[new['latitude'] != 0] new = new[new['on_land'] == True] new['address'] = new.apply(lambda row: getting_city_nominatim(row), axis=1) return new
def turtle(): while True: x = Latitude() if x > 90: x = 90 y = Longtitude() if y > 180: y = 180 globe_land_mask = globe.is_land(x, y) if globe_land_mask == False: break turtle = "turtle," + str(x) + "," + str(y) return turtle
def cutting_path_by_land(path, k=2): """ continuos k point on the land, cut it. init k = 2 :param path: predicted path :param k: :return: cutted path """ land_count = 0 for i, point in enumerate(path): if globe.is_land(point[0], point[1]): land_count += 1 if land_count >= k: return path[:i] return path
def simulate_smap_windspd(self): self.logger.info((f"""Comparing wind speed from different sources""")) # Get IBTrACS table table_name = self.CONFIG['ibtracs']['table_name'][self.basin] IBTrACS = utils.get_class_by_tablename(self.engine, table_name) query_obj = self.session.query(IBTrACS).filter( IBTrACS.date_time >= self.period[0], IBTrACS.date_time <= self.period[1]) in_expression = IBTrACS.name.in_(self.tc_names) tc_query = query_obj.filter(in_expression) total = tc_query.count() # Expand period if total < 2: self.logger.warning('Expand period') query_obj = self.session.query(IBTrACS).filter( IBTrACS.date_time >= (self.period[0] - datetime.timedelta(seconds=3600 * 3)), IBTrACS.date_time <= (self.period[1] + datetime.timedelta(seconds=3600 * 3))) in_expression = IBTrACS.name.in_(self.tc_names) tc_query = query_obj.filter(in_expression) total = tc_query.count() if total < 2: self.logger.error('Too few TCs') exit(1) # Filter TCs during period for idx, tc in enumerate(tc_query): if tc.name not in self.tc_names: continue converted_lon = utils.longitude_converter(tc.lon, '360', '-180') if bool(globe.is_land(tc.lat, converted_lon)): continue success = False if idx < total - 1: next_tc = tc_query[idx + 1] if tc.sid == next_tc.sid: if (tc.date_time >= self.period[1] or next_tc.date_time <= self.period[0]): continue print(f'Simulating {tc.date_time} - {next_tc.date_time}') self.simulate_between_two_tcs(tc, next_tc) print('Done')
def get_resilting_cube_with_land_mask(resulting_cube, lat, lon, times): # resulting_cube - 3D np.ndarray (time, lat, lon) # lat - 1D np.ndarray (latitude) # lon - 1D np.ndarray (longitude) # times - 1D np.ndarray (with 'yyyy.mm.dd hh:00:00') n_time, n_lat, n_lon = resulting_cube.shape resulting_cube_land_masked = np.zeros((n_time, n_lat, n_lon)) for k_lat in range(0, n_lat): for k_lon in range(0, n_lon): if globe.is_land(lat[k_lat], lon[k_lon]): resulting_cube_land_masked[:, k_lat, k_lon] = np.asarray( [np.nan] * len(times)) else: resulting_cube_land_masked[:, k_lat, k_lon] = resulting_cube[:, k_lat, k_lon] return resulting_cube_land_masked
def naptan_coastal_nodes(gdf): # TODO - add a column to the master naptan dataframe, and then count up # false values, to get the percent of stops that fail, and then compare # those stops, to find out which ones are near the coast and how near # the coast they are. """[summary] provided a dataframe, returns a list of nodes that are near the coast line, this uses global land mask library, a numpy & pandas extension, for mapping the boundaries of the coastline. Arguments: df {[geospatial dataframe]} -- [the naptan master dataframe.] Raises: ve: [Raises description] e: [] Returns: [type] -- [description] """ check_name = naptan_coastal_nodes.__name__ try: gdf['Land_State'] = globe.is_land(gdf['Latitude'], gdf['Longitude']) coastal_nodes = gdf.loc[~gdf.Land_State] high_node_areas = coastal_nodes['LocalityName'].value_counts() percentage = ((len(coastal_nodes) / len(gdf)) * 100.0) if percentage >= 1.1: print(f"The area has a total of {coastal_nodes}, nodes which are \ at sea error ratio is {percentage:0.2f}% too high.") elif percentage <= 0: print('No Nodes were found along the coastline') pass else: print(f"The area has a total of {coastal_nodes} in the area.\ {percentage:0.2f}") report.nodes_error_reporting(gdf, check_name, coastal_nodes) return high_node_areas except ValueError as ve: raise (ve) except Exception as e: print(e)
def get_land_coordinates(number=500, gui=False): ''' It generates a list of points distributed on the Earth land ''' i = 0 points = np.zeros((3, number)) while i < number: lat, lon = new_point() # If the generated point is on land, it will be added to the list # otherwise a new point will be generated if globe.is_land(lat, lon): points[0, i] = lat points[1, i] = lon i = i + 1 print(' # Points generated') return points
def filter_sites(site_details, location='usa only'): """ :param site_details: pandas dataframe :param location: 'on land only' or 'usa only' :return: """ # Load GEOJson geo_data = requests.get( "https://raw.githubusercontent.com/datasets/geo-countries/master/data/countries.geojson" ).json() # Creates a new dataframe to contain only the selected sites site_details_selected = pd.DataFrame(columns=[ 'site_nums', 'Lat', 'Lon', 'solar_filenames', 'wind_filenames' ]) # Only sites on land (includes lakes) if location == 'on land only': for site_index, site in site_details.iterrows(): is_on_land = globe.is_land(site['Lat'], site['Lon']) if is_on_land: site_details_selected = site_details_selected.append( site_details.loc[site_index, :]) # print('details appended for sites on land') # Only sites in the Continental US if location == 'usa only': for site_index, site in site_details.iterrows(): is_in_usa = (get_country( site['Lat'], site['Lon'], geo_data=geo_data) == 'United States of America') if is_in_usa: site_details_selected = site_details_selected.append( site_details.loc[site_index, :]) print( 'details appended for sites in the USA - Lat: {} Lon: {}'. format(site['Lat'], site['Lon'])) return site_details_selected
def getRandomLocations(longitude, latitude, samples): """ get randomised points around asset location """ # iterate number of samples pts = [] for idx in range(samples): while True: # loop until land location found pt = { 'longitude': longitude + random.uniform(-1.0, 1.0), 'latitude': latitude + random.uniform(-1.0, 1.0) } if globe.is_land(pt['latitude'], pt['longitude']): break # append to list pts.append(pt) return pts
def recursive_routing(iso1, boat, winds, delta_time, params, verbose=False): """ Progress one isochrone with pruning. Parameters: iso1 (Isochrone) - starting isochrone start_point (tuple) - starting point of the route end_point (tuple) - end point of the route x1_coords (tuple) - tuple of arrays (lats, lons) x2_coords (tuple) - tuple of arrays (lats, lons) boat (dict) - boat profile winds (dict) - wind functions start_time (datetime) - start time delta_time (float) - time to move in seconds params (dict) - isochrone calculation parameters Returns: iso (Isochrone) - next isochrone """ # branch out for multiple headings lats = np.repeat(iso1.lats1, params['ROUTER_HDGS_SEGMENTS'] + 1, axis=1) lons = np.repeat(iso1.lons1, params['ROUTER_HDGS_SEGMENTS'] + 1, axis=1) azi12 = np.repeat(iso1.azi12, params['ROUTER_HDGS_SEGMENTS'] + 1, axis=1) s12 = np.repeat(iso1.s12, params['ROUTER_HDGS_SEGMENTS'] + 1, axis=1) start_lats = np.repeat(iso1.start[0], lats.shape[1]) start_lons = np.repeat(iso1.start[1], lons.shape[1]) # determine new headings - centered around gcrs X0 -> X_prev_step hdgs = iso1.azi02 delta_hdgs = np.linspace( -params['ROUTER_HDGS_SEGMENTS'] * params['ROUTER_HDGS_INCREMENTS_DEG'], +params['ROUTER_HDGS_SEGMENTS'] * params['ROUTER_HDGS_INCREMENTS_DEG'], params['ROUTER_HDGS_SEGMENTS'] + 1) delta_hdgs = np.tile(delta_hdgs, iso1.lats1.shape[1]) hdgs = np.repeat(hdgs, params['ROUTER_HDGS_SEGMENTS'] + 1) hdgs = hdgs - delta_hdgs # move boat with defined headings N_coords x (ROUTER_HDGS_SEGMENTS+1) times move = move_boat_direct(lats[0, :], lons[0, :], hdgs, boat, winds, iso1.time1, delta_time, verbose=False) # create new isochrone before pruning lats = np.vstack((move['lats2'], lats)) lons = np.vstack((move['lons2'], lons)) azi12 = np.vstack((move['azi1'], azi12)) s12 = np.vstack((move['s12'], s12)) # determine gcrs from start to new isochrone gcrs = geod.inverse(start_lats, start_lons, move['lats2'], move['lons2']) # remove those which ended on land is_on_land = globe.is_land(move['lats2'], move['lons2']) gcrs['s12'][is_on_land] = 0 azi02 = gcrs['azi1'] s02 = gcrs['s12'] iso2 = Isochrone( start=iso1.start, finish=iso1.finish, gcr_azi=iso1.gcr_azi, count=iso1.count+1, elapsed=iso1.elapsed+dt.timedelta(seconds=delta_time), time1=iso1.time1+dt.timedelta(seconds=delta_time), lats1=lats, lons1=lons, azi12=azi12, s12=s12, azi02=azi02, s02=s02 ) # ---- pruning isochrone ---- # new gcr azimuth to finish from the current isochrone mean_dist = np.mean(iso2.s02) gcr_point = geod.direct( [iso1.start[0]], [iso1.start[1]], iso1.gcr_azi, mean_dist) new_azi = geod.inverse( gcr_point['lat2'], gcr_point['lon2'], [iso1.finish[0]], [iso1.finish[1]] ) azi0s = np.repeat( new_azi['azi1'], params['ISOCHRONE_PRUNE_SEGMENTS'] + 1) # determine bins delta_hdgs = np.linspace( -params['ISOCHRONE_PRUNE_SECTOR_DEG_HALF'], +params['ISOCHRONE_PRUNE_SECTOR_DEG_HALF'], params['ISOCHRONE_PRUNE_SEGMENTS']+1) bins = azi0s - delta_hdgs bins = np.sort(bins) iso2 = prune_isochrone(iso2, 'azi02', 's02', bins, True) return iso2
def landMask(lat, lon): lon_grid, lat_grid = np.meshgrid(lon, lat) is_on_land = globe.is_land(lat_grid, lon_grid) return is_on_land
""" Simple example script showing how to check if a point is on land or in the ocean. """ from global_land_mask import globe import numpy as np # Check if a point is on land: lat = 40 lon = -120 is_on_land = globe.is_land(lat, lon) print('lat={}, lon={} is on land: {}'.format(lat, lon, is_on_land)) # Check if several points are in the ocean lat = 40 lon = np.linspace(-150, -110, 3) is_in_ocean = globe.is_ocean(lat, lon) print('lat={}, lon={} is in ocean: {}'.format(lat, lon, is_in_ocean))
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt # Lat/lon points to get lat = np.linspace(-20,90,1000) lon = np.linspace(-130,-60,1002) # Make a grid lon_grid, lat_grid = np.meshgrid(lon,lat) # Get whether the points are on land. z = globe.is_land(lat_grid, lon_grid) # Set up map fig = plt.figure(0, figsize=(5.5, 4.5)) plt.clf() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45, lon_0=-95, area_thresh=200, resolution='i') m.drawstates(linewidth=0.2) m.drawcoastlines(linewidth=0.2) m.drawcountries(linewidth=0.2)
from netCDF4 import Dataset import matplotlib.pyplot as plt from global_land_mask import globe import cartopy.feature as cfeature from cartopy.util import add_cyclic_point u10 = Dataset('/Users/Pedro/Documents/DadosNC/u10_1019.nc') v10 = Dataset('/Users/Pedro/Documents/DadosNC/v10_1019.nc') u10w = u10.variables['uwnd'][0] v10w = v10.variables['vwnd'][0] lat = u10.variables['lat'][:] lon = u10.variables['lon'][:] lat_grid, lon_grid = N.meshgrid(lat, lon) is_on_land = globe.is_land(lat_grid, lon_grid-180) def windstress(CD,Pair,wind_speed): wind_speed = N.hypot(u10w, v10w) for w in wind_speed: if w #wind_speed = #Pair = 1.22 #CD = 0.0013 #t = CD * Pair * wind_speed**2 ax = plt.axes(projection=ccrs.PlateCarree()) ax.add_feature(cfeature.LAND, zorder=100, edgecolor='k') ax.set_extent([-80, 30, -75, 15])