def __init__(self, center, bbox, zoom, basemap, opacity, size=None): self._configure_event_loop() point = center['geometry']['coordinates'] if size is None: size = IMAGE_SIZE self.num_tiles = [ math.ceil(size[x] / TILE_SIZE[x]) + 1 for x in (0, 1) ] center_tile = mercantile.tile(point[0], point[1], zoom) mercator = Proj(init='epsg:3857') wgs84 = Proj(init='epsg:4326') center_tile_bbox = BBox(mercantile.bounds(*center_tile), projection=wgs84).project(mercator, edge_points=0) center_to_image = world_to_image(center_tile_bbox, TILE_SIZE) center_to_world = image_to_world(center_tile_bbox, TILE_SIZE) center_point_px = center_to_image(*mercantile.xy(*point)) self.ul_tile = mercantile.tile(*transform( mercator, wgs84, *center_to_world(center_point_px[0] - math.ceil(IMAGE_SIZE[0] / 2), center_point_px[1] - math.ceil(IMAGE_SIZE[1] / 2)), zoom)) lr_tile = mercantile.Tile(x=min(2**zoom, self.ul_tile.x + self.num_tiles[0]), y=min(2**zoom, self.ul_tile.y + self.num_tiles[1]), z=zoom) ul = mercantile.xy(*mercantile.ul(*self.ul_tile)) lr = mercantile.xy(*mercantile.ul(*lr_tile)) self.image_bbox = BBox((ul[0], lr[1], lr[0], ul[1])) self.image_size = (TILE_SIZE[0] * self.num_tiles[0], TILE_SIZE[1] * self.num_tiles[1]) self.to_image = world_to_image(self.image_bbox, self.image_size) self.to_world = image_to_world(self.image_bbox, self.image_size) self.point_px = [ round(x) for x in self.to_image(*mercantile.xy(*point)) ] self.target_size = size self.point = point self.zoom = zoom self.basemap = basemap self._basemap_image = None self.opacity = opacity
def get_management_action_map(tsm): geojson_file = os.path.join( STSIM_MULTIPLIER_DIR, tsm.transition_multiplier_file_name).replace('.tif', '.json') with open(geojson_file, 'r') as f: polygons = json.load(f) transition_group = tsm.transition_group.name timestep = int( tsm.transition_multiplier_file_name.split('_')[-1].split('.') [0]) label = '{} performed on {} {}'.format(transition_group, timestep_units, timestep) image_data, bbox = map_maker.get_polygon_image(polygons) to_world = image_to_world(bbox, image_data.size) image_handle = BytesIO() image_data.save(image_handle, 'png') return { 'label': label, 'image_data': b64encode(image_handle.getvalue()), 'scale': get_scale(to_world, image_data.size[1]), **basic_map_config }
def get_map_context(label, name, service, is_output=False, iteration=None, timestep=None, legend=None): service_url = service[name] if is_output: service_url = service_url.replace('{it}', str(iteration)).replace( '{t}', str(timestep)) image_data, bbox = map_maker.get_image(service_url) to_world = image_to_world(bbox, image_data.size) bbox = bbox.project(WGS84, edge_points=0) image_handle = BytesIO() image_data.save(image_handle, 'png') scale = get_scale(to_world, image_data.size[1]) legend_data = get_legend(service_url, is_output) if legend is None else legend return { 'label': label, 'image_data': b64encode(image_handle.getvalue()), 'north': format_y_coord(bbox.ymax), 'east': format_x_coord(bbox.xmax), 'west': format_x_coord(bbox.xmin), 'south': format_y_coord(bbox.ymin), 'scale': scale, 'legend': legend_data }
def execute(self, bounds, zoom, basemap, single_color, kept_colors, gained_colors, species, **kwargs): historic = kwargs['historic'] futures = kwargs.get('futures', []) opacity = kwargs.get('opacity', 1.) map_image = self.get_basemap_image(basemap, bounds, IMAGE_SIZE, zoom) results_image = self.get_results_image( bounds, IMAGE_SIZE, single_color, kept_colors, gained_colors, species, historic, futures ) map_image.paste(Image.blend(map_image, results_image, opacity), (0, 0), results_image) image_data = BytesIO() map_image.save(image_data, 'png') def format_x_coord(x): return '{}° W'.format(round(abs(x), 2)) if x < 0 else '{}° E'.format(round(x, 2)) def format_y_coord(y): return '{}° S'.format(round(abs(y), 2)) if y < 0 else '{}° N'.format(round(y, 2)) to_world = image_to_world(BBox(bounds, projection=WGS84).project(WEB_MERCATOR), IMAGE_SIZE) images_dir = self.get_images_dir() with open(os.path.join(images_dir, 'scale.png'), 'rb') as f: scale_data = b64encode(f.read()) scale_bar_x = 38 scale_bar_y = IMAGE_SIZE[1] - 15 scale_bar_start = transform(WEB_MERCATOR, WGS84, *to_world(scale_bar_x, scale_bar_y)) scale_bar_end = transform(WEB_MERCATOR, WGS84, *to_world(scale_bar_x + 96, scale_bar_y)) scale = '{} mi'.format(round(vincenty(reversed(scale_bar_start), reversed(scale_bar_end)).miles, 1)) context = { 'today': now(), 'image_data': b64encode(image_data.getvalue()), 'east': format_x_coord(bounds[0]), 'south': format_y_coord(bounds[1]), 'west': format_x_coord(bounds[2]), 'north': format_y_coord(bounds[3]), 'scale_image_data': scale_data, 'scale': scale, 'single_color': single_color, 'kept_colors': self.get_colors(kept_colors, len(futures)+1), 'gained_colors': self.get_colors(gained_colors, len(futures)+1), 'historic': historic.replace('_', '-'), 'futures': [ {'rcp': RCP_LABELS[rcp], 'year': YEAR_LABELS[year]} for rcp, year in [x.split('_', 1) for x in futures] ], 'species': SPECIES_LABELS[species], } uuid = str(uuid4()) report_dir = os.path.join(settings.MEDIA_ROOT, uuid) if not os.path.exists(report_dir): os.makedirs(report_dir) path = os.path.join(report_dir, 'SPHT Report.pdf') with open(path, 'wb') as f: HTML(BytesIO(render_to_string('spht/report.html', context).encode())).write_pdf(f) return '{}{}/SPHT Report.pdf'.format(settings.MEDIA_URL, uuid)
def __init__(self, size, point, zoom, center, tile_layers, region, zone_id, opacity, constraint_geometry=None): self._configure_event_loop() self.num_tiles = [ math.ceil(size[x] / TILE_SIZE[x]) + 1 for x in (0, 1) ] center_tile = mercantile.tile(center[1], center[0], zoom) mercator = Proj(init='epsg:3857') wgs84 = Proj(init='epsg:4326') center_tile_bbox = BBox(mercantile.bounds(*center_tile), projection=wgs84).project(mercator, edge_points=0) center_to_image = world_to_image(center_tile_bbox, TILE_SIZE) center_to_world = image_to_world(center_tile_bbox, TILE_SIZE) center_point_px = center_to_image(*mercantile.xy(center[1], center[0])) self.ul_tile = mercantile.tile(*transform( mercator, wgs84, *center_to_world(center_point_px[0] - math.ceil(IMAGE_SIZE[0] / 2), center_point_px[1] - math.ceil(IMAGE_SIZE[1] / 2)), zoom)) lr_tile = mercantile.Tile(x=min(2**zoom, self.ul_tile.x + self.num_tiles[0]), y=min(2**zoom, self.ul_tile.y + self.num_tiles[1]), z=zoom) ul = mercantile.xy(*mercantile.ul(*self.ul_tile)) lr = mercantile.xy(*mercantile.ul(*lr_tile)) self.image_bbox = BBox((ul[0], lr[1], lr[0], ul[1])) self.image_size = (TILE_SIZE[0] * self.num_tiles[0], TILE_SIZE[1] * self.num_tiles[1]) self.to_image = world_to_image(self.image_bbox, self.image_size) self.to_world = image_to_world(self.image_bbox, self.image_size) self.point_px = [ round(x) for x in self.to_image(*mercantile.xy(*point)) ] self.center_point_px = self.to_image( *mercantile.xy(center[1], center[0])) self.target_size = size self.point = point self.zoom = zoom self.center = center self.tile_layers = tile_layers self.region = region self.zone_id = zone_id self.opacity = opacity self.constraint_geometry = constraint_geometry
def get_context(self, img_as_bytes=False): point = self.configuration['point'] elevation = get_elevation_at_point(Point(point['x'], point['y'])) / 0.3048 method = self.configuration['method'] objective = self.configuration['objective'] climates = self.configuration['climate'] if self.configuration['method'] == 'seedzone' and elevation is not None: zone_uid = self.configuration['zones']['selected'] try: zone = SeedZone.objects.get(zone_uid=zone_uid) zone_id = zone.pk try: limit = zone.transferlimit_set.filter( low__lt=elevation, high__gte=elevation)[:1].get() band = [0 if limit.low == -1 else limit.low, limit.high] except TransferLimit.DoesNotExist: band = None except SeedZone.DoesNotExist: zone_id = None zone = None band = None else: zone_id = None zone = None band = None mercator = Proj(init='epsg:3857') wgs84 = Proj(init='epsg:4326') map_image, map_bbox = MapImage( IMAGE_SIZE, (point['x'], point['y']), self.zoom, self.center, self.tile_layers, self.configuration.get('region'), zone_id, self.opacity, constraint_geometry=self.get_constraint_geometry()).get_image() to_world = image_to_world(map_bbox, map_image.size) map_bbox = map_bbox.project(Proj(init='epsg:4326'), edge_points=0) image_data = BytesIO() map_image.save(image_data, 'png') if img_as_bytes: image_data.seek(0) # seek to file start so we can read into ppt with open(os.path.join(get_images_dir(), 'north.png'), 'rb') as f: north_image_data = b64encode(f.read()) with open(os.path.join(get_images_dir(), 'scale.png'), 'rb') as f: scale_image_data = b64encode(f.read()) scale_bar_x = 38 scale_bar_y = map_image.size[1] - 15 scale_bar_start = transform(mercator, wgs84, *to_world(scale_bar_x, scale_bar_y)) scale_bar_end = transform(mercator, wgs84, *to_world(scale_bar_x + 96, scale_bar_y)) scale = '{} mi'.format( round( vincenty(reversed(scale_bar_start), reversed(scale_bar_end)).miles, 1)) legend = RESULTS_RENDERER.get_legend()[0] def format_x_coord(x): return '{}° W'.format(round( abs(x), 2)) if x < 0 else '{}° E'.format(round(x, 2)) def format_y_coord(y): return '{}° S'.format(round( abs(y), 2)) if y < 0 else '{}° N'.format(round(y, 2)) return { 'today': datetime.today(), 'image_data': b64encode(image_data.getvalue()) if not img_as_bytes else image_data, 'north': format_y_coord(map_bbox.ymax), 'east': format_x_coord(map_bbox.xmax), 'south': format_y_coord(map_bbox.ymin), 'west': format_x_coord(map_bbox.xmin), 'north_image_data': north_image_data, 'scale_image_data': scale_image_data, 'scale': scale, 'legend_image_data': legend, 'objective': 'Find seedlots' if objective == 'seedlots' else 'Find planting sites', 'location_label': 'Planting site location' if objective == 'seedlots' else 'Seedlot location', 'point': { 'x': round(point['x'], 4), 'y': round(point['y'], 4) }, 'elevation': round(elevation), 'seedlot_year': self.get_year(climates['seedlot']), 'site_year': self.get_year(climates['site']), 'site_model': self.get_model(climates['site']), 'method': method, 'center': self.configuration['center'], 'species': self.configuration.get('species') if method in ('seedzone', 'function') else None, 'zone': getattr(zone, 'name', None), 'band': band, 'variables': self.get_context_variables(), 'traits': self.get_context_traits(), 'constraints': self.get_context_constraints(), 'title': SEEDSOURCE_TITLE }