def DHPotential(DH_Regions, heat_density_map): if isinstance(heat_density_map, np.ndarray): hdm_arr = heat_density_map elif isinstance(heat_density_map, str): hdm_arr, gt = RA(heat_density_map, return_gt=True) struct = np.ones((3, 3)).astype(int) labels, numLabels = measurements.label(DH_Regions, structure=struct) DHPot = np.zeros((numLabels + 1)).astype(float) sparseRow, sparseCol = np.nonzero(labels) # This helps to implement "np.unique" much faster sparse_labels = labels[sparseRow, sparseCol] sparse_hdm = hdm_arr[sparseRow, sparseCol] # sort sparse values based on sparse_labels. This helps to implement # summation process much faster. sortedSparseData = np.asarray( sorted(zip(sparseRow, sparseCol, sparse_labels, sparse_hdm), key=lambda x: x[2])) unique, counts = np.unique(sparse_labels, return_counts=True) end = np.cumsum(counts) st = np.concatenate((np.zeros((1)), end[0:numLabels - 1])) for i in range(numLabels): # input: [MWh/ha] for each ha --> to get potential in GWh it # should be multiplied by 0.001 DHPot[i + 1] = 0.001 * np.sum(sortedSparseData[int(st[i]):int(end[i]), 3]) #DH_Potential = DHPot[labels] DHPot = DHPot[1::] # potential of each coherent area in GWh is assigned to its pixels return DHPot, labels
def main(hdm_path, selected_area, updated_demand_value, output_dir, outRasterPath): hdm, gt = RA(hdm_path, return_gt=True) hdm_cut, geo_transform = CM22.main(hdm, selected_area, output_dir, gt, nodata=0, return_array=True) scale.scaling(hdm_cut, geo_transform, updated_demand_value, outRasterPath)
def DHReg(heat_density_map, pix_threshold, DH_threshold, in_orig=None): # Factor 1000 for conversion from GWh/a to MWh/a DH_threshold = DH_threshold * 1000 if isinstance(heat_density_map, np.ndarray): gt = in_orig hdm_arr = heat_density_map elif isinstance(heat_density_map, str): hdm_arr, gt = RA(heat_density_map, return_gt=True) hdm_arr_filtered = hdm_arr * (hdm_arr > pix_threshold) DH_Selected_Region = DHRegions(hdm_arr_filtered, DH_threshold) # return DH_Selected_Region and raster geotransform array return DH_Selected_Region, gt
def DHReg(heat_density_map, strd_vector_path, pix_threshold, DH_threshold, in_orig=None): # Factor 10 for conversion from GWh/km2 to MWh/ha pix_threshold = pix_threshold * 10 # Factor 1000 for conversion from GWh/a to MWh/a DH_threshold = DH_threshold * 1000 inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(strd_vector_path, 0) inLayer = inDataSource.GetLayer() shp_minX, shp_maxX, shp_minY, shp_maxY = inLayer.GetExtent() if isinstance(heat_density_map, np.ndarray): if not in_orig: raise TypeError('The raster origin is of None type!') minx, maxy = in_orig[0], in_orig[1] arr1 = heat_density_map elif isinstance(heat_density_map, str): arr1, gt = RA(heat_density_map, return_gt=True) minx, maxy = gt[0], gt[3] (dimX0, dimY0) = arr1.shape (lowIndexX, upIndexX, lowIndexY, upIndexY) = CM20.main(minx, maxy, dimX0, dimY0, shp_minX, shp_maxX, shp_minY, shp_maxY) minx = minx + 100 * lowIndexY maxy = maxy - 100 * lowIndexX rasterOrigin = (minx, maxy) arr1 = arr1[lowIndexX:upIndexX, lowIndexY:upIndexY] DH = arr1 * (arr1 > pix_threshold) (dimX, dimY) = DH.shape DH_Regions = np.zeros((dimX, dimY)).astype(bool) for fid in range(inLayer.GetFeatureCount()): if verbose: print(fid) inFeature = inLayer.GetFeature(fid) geom = inFeature.GetGeometryRef() # Get boundaries fminx, fmaxx, fminy, fmaxy = geom.GetEnvelope() # define exact index that encompasses the feature. (lowIndexX, upIndexX, lowIndexY, upIndexY) = CM20.main(minx, maxy, dimX, dimY, fminx, fmaxx, fminy, fmaxy) # rasterOrigin2 = (minx + lowIndexY*100, maxy - lowIndexX*100) arr_out = DH[lowIndexX:upIndexX, lowIndexY:upIndexY] DH_Selected_Region = DHRegions(arr_out, DH_threshold) DH_Regions[lowIndexX:upIndexX, lowIndexY:upIndexY] += DH_Selected_Region arr_out = None inFeature = None return DH_Regions, arr1, rasterOrigin
def DHReg(heat_density_map, pix_threshold, DH_threshold, in_orig=None): # Factor 1000 for conversion from GWh/a to MWh/a DH_threshold = DH_threshold * 1000 if isinstance(heat_density_map, np.ndarray): if not in_orig: raise TypeError('The raster origin is of None type!') hdm_arr = heat_density_map elif isinstance(heat_density_map, str): hdm_arr, gt = RA(heat_density_map, return_gt=True) # division by 1000 for MWh to GWh total_heat_demand = np.sum(hdm_arr) / 1000 hdm_arr_filtered = hdm_arr * (hdm_arr > pix_threshold) DH_Selected_Region = DHRegions(hdm_arr_filtered, DH_threshold) hdm_dh_region_cut = hdm_arr * (DH_Selected_Region > 0).astype(int) # return DH_Selected_Region and raster geotransform array return DH_Selected_Region, hdm_dh_region_cut, gt, total_heat_demand
def main(input_raster_NUTS_id, input_raster_GFA_RES, input_raster_ENERGY_RES, input_raster_LAU2_id, input_raster_cp_share_1975, input_raster_cp_share_1990, input_raster_cp_share_2000, input_raster_cp_share_2014, output_raster_energy, output_csv_result): data_type = "f4" data_type_int = "uint32" local_input_dir = path + "/input_data" NUTS_id, gt = RA(input_raster_NUTS_id, dType=data_type_int, return_gt=True) GFA_RES = RA(input_raster_GFA_RES, dType=data_type) ENERGY_RES = RA(input_raster_ENERGY_RES, dType=data_type) LAU2_id = RA(input_raster_LAU2_id, dType=data_type_int) cp_share_1975 = RA(input_raster_cp_share_1975, dType=data_type) cp_share_1990 = RA(input_raster_cp_share_1990, dType=data_type) cp_share_2000 = RA(input_raster_cp_share_2000, dType=data_type) cp_share_2014 = RA(input_raster_cp_share_2014, dType=data_type) NUTS_id_size = NUTS_id.shape cp_share_2000_and_2014 = cp_share_2000 + cp_share_2014 NUTS_RESULTS_ENERGY_BASE = READ_CSV_DATA(local_input_dir + "/RESULTS_SHARES_2012.csv", skip_header=3)[0] NUTS_RESULTS_ENERGY_FUTURE = READ_CSV_DATA(local_input_dir + "/RESULTS_SHARES_2030.csv", skip_header=3)[0] NUTS_RESULTS_ENERGY_FUTURE_abs = READ_CSV_DATA(local_input_dir + "/RESULTS_ENERGY_2030.csv", skip_header=3)[0] NUTS_RESULTS_GFA_BASE = READ_CSV_DATA(local_input_dir + "/RESULTS_GFA_2012.csv", skip_header=3)[0] NUTS_RESULTS_GFA_FUTURE = READ_CSV_DATA(local_input_dir + "/RESULTS_GFA_2030.csv", skip_header=3)[0] csv_data_table = READ_CSV_DATA(local_input_dir + "/Communal2_data.csv", skip_header=6) _, _ = CalcEffectsAtRasterLevel( NUTS_RESULTS_GFA_BASE, NUTS_RESULTS_GFA_FUTURE, NUTS_RESULTS_ENERGY_BASE, NUTS_RESULTS_ENERGY_FUTURE, NUTS_RESULTS_ENERGY_FUTURE_abs, NUTS_id, LAU2_id, cp_share_1975, cp_share_1990, cp_share_2000_and_2014, ENERGY_RES, GFA_RES, gt, NUTS_id_size, csv_data_table, output_raster_energy, output_csv_result)
def add_label_field(dh_bool_raster, label_raster, outPolygon, heat_dem_coh, epsg=3035): label_list = [] outShapefile = outPolygon[:-12] + 'label.shp' outDriver = ogr.GetDriverByName("ESRI Shapefile") # Remove output shapefile if it already exists if os.path.exists(outShapefile): outDriver.DeleteDataSource(outShapefile) bool_arr, gt = RA(dh_bool_raster, return_gt=True) label_arr = RA(label_raster) numLabels = np.max(label_arr) coords = measurements.center_of_mass(bool_arr, label_arr, index=np.arange(1, numLabels+1)) x0, y0, w, h = gt[0], gt[3], gt[1], gt[5] X0 = x0 + w/2 Y0 = y0 + h/2 for item in coords: xl = round(X0 + 100 * item[1], 1) yl = round(Y0 - 100 * item[0], 1) label_list.append((xl, yl)) inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(outPolygon, 0) inLayer = inDataSource.GetLayer() srs = osr.SpatialReference() srs.ImportFromEPSG(epsg) geom_typ = inLayer.GetGeomType() geom_typ_dict = {1: ogr.wkbPoint, 2: ogr.wkbLineString, 3: ogr.wkbPolygon} # Create the output Layer outDriver = ogr.GetDriverByName("ESRI Shapefile") outDataSource = outDriver.CreateDataSource(outShapefile) outLayer = outDataSource.CreateLayer("newSHP", srs, geom_type=geom_typ_dict[geom_typ]) Fields = ['label', 'pot_DH'] Fields_dtype = [ogr.OFTInteger, ogr.OFTReal] for i, f in enumerate(Fields): Field = ogr.FieldDefn(f, Fields_dtype[i]) outLayer.CreateField(Field) # Get the output Layer's Feature Definition outLayerDefn = outLayer.GetLayerDefn() for feature in inLayer: geom = feature.GetGeometryRef() centroid = geom.Centroid() x = round(centroid.GetX(), 1) y = round(centroid.GetY(), 1) outFeature = ogr.Feature(outLayerDefn) try: geom_label = label_list.index((x, y)) except: nearest_dist = 1000 for p, point in enumerate(label_list): x_temp, y_temp = point temp_dist = ((x-x_temp)**2 + (y-y_temp)**2)**0.5 if temp_dist < nearest_dist: geom_label = p outFeature.SetField(outLayerDefn.GetFieldDefn(0).GetNameRef(), geom_label+1) outFeature.SetField(outLayerDefn.GetFieldDefn(1).GetNameRef(), heat_dem_coh[geom_label]) outFeature.SetGeometry(geom) # Add new feature to output Layer outLayer.CreateFeature(outFeature) outFeature = None # Save and close DataSources inDataSource = None outDataSource = None if os.path.exists(outPolygon): outDriver.DeleteDataSource(outPolygon)
def add_label_field(heat_dem_coh_last, heat_dem_spec_area, q, q_spec_cost, economic_bool, area_coh_area, out_raster_coh_area_bool, out_raster_labels, out_raster_maxDHdem, out_raster_economic_maxDHdem, out_shp_prelabel, out_shp_label, epsg=3035): color_map = ["#de2d26", "#2ca25f"] label_list = [] outDriver = ogr.GetDriverByName("ESRI Shapefile") # Remove output shapefile if it already exists if os.path.exists(out_shp_label): outDriver.DeleteDataSource(out_shp_label) bool_arr, gt = RA(out_raster_coh_area_bool, return_gt=True) maxDHdem_arr = RA(out_raster_maxDHdem) economic_maxDHdem_arr = maxDHdem_arr * bool_arr.astype(int) CM19.main(out_raster_economic_maxDHdem, gt, "float64", economic_maxDHdem_arr) label_arr = RA(out_raster_labels) numLabels = np.max(label_arr) coords = measurements.center_of_mass(bool_arr, label_arr, index=np.arange(1, numLabels+1)) x0, y0, w, h = gt[0], gt[3], gt[1], gt[5] X0 = x0 + w/2 Y0 = y0 + h/2 for item in coords: xl = round(X0 + 100 * item[1], 1) yl = round(Y0 - 100 * item[0], 1) label_list.append((xl, yl)) inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(out_shp_prelabel, 0) inLayer = inDataSource.GetLayer() srs = osr.SpatialReference() srs.ImportFromEPSG(epsg) geom_typ = inLayer.GetGeomType() geom_typ_dict = {1: ogr.wkbPoint, 2: ogr.wkbLineString, 3: ogr.wkbPolygon} # Create the output Layer outDriver = ogr.GetDriverByName("ESRI Shapefile") outDataSource = outDriver.CreateDataSource(out_shp_label) outLayer = outDataSource.CreateLayer("newSHP", srs, geom_type=geom_typ_dict[geom_typ]) Fields = ['Label', 'Economic', 'Dem_last', 'Spec_Dem', 'Potent_DH', 'Distr_Cost', 'Area', 'color', 'fillColor', 'opacity'] Fields_dtype = [ogr.OFTInteger, ogr.OFTString, ogr.OFTString, ogr.OFTString, ogr.OFTString, ogr.OFTString, ogr.OFTString, ogr.OFTString, ogr.OFTString, ogr.OFTString] for i, f in enumerate(Fields): Field = ogr.FieldDefn(f, Fields_dtype[i]) outLayer.CreateField(Field) # Get the output Layer's Feature Definition outLayerDefn = outLayer.GetLayerDefn() econ_bool_dict = {0: " No", 1: " Yes"} for feature in inLayer: geom = feature.GetGeometryRef() centroid = geom.Centroid() x = round(centroid.GetX(), 1) y = round(centroid.GetY(), 1) outFeature = ogr.Feature(outLayerDefn) try: geom_label = label_list.index((x, y)) except: nearest_dist = 1000 for p, point in enumerate(label_list): x_temp, y_temp = point temp_dist = ((x-x_temp)**2 + (y-y_temp)**2)**0.5 if temp_dist < nearest_dist: geom_label = p outFeature.SetField(outLayerDefn.GetFieldDefn(0).GetNameRef(), geom_label+1) outFeature.SetField(outLayerDefn.GetFieldDefn(1).GetNameRef(), econ_bool_dict[int(economic_bool[geom_label])]) # demand in GWh outFeature.SetField(outLayerDefn.GetFieldDefn(2).GetNameRef(), str(round(heat_dem_coh_last[geom_label]/1000, 2)) + " GWh") outFeature.SetField(outLayerDefn.GetFieldDefn(3).GetNameRef(), str(round(heat_dem_spec_area[geom_label], 2)) + " MWh/ha") # potential in GWh outFeature.SetField(outLayerDefn.GetFieldDefn(4).GetNameRef(), str(round(q[geom_label]/1000, 2)) + " GWh") outFeature.SetField(outLayerDefn.GetFieldDefn(5).GetNameRef(), str(round(q_spec_cost[geom_label], 2)) + " EUR/MWh") outFeature.SetField(outLayerDefn.GetFieldDefn(6).GetNameRef(), str(area_coh_area[geom_label]) + " hectare") outFeature.SetField(outLayerDefn.GetFieldDefn(7).GetNameRef(), color_map[int(economic_bool[geom_label])]) outFeature.SetField(outLayerDefn.GetFieldDefn(8).GetNameRef(), color_map[int(economic_bool[geom_label])]) outFeature.SetField(outLayerDefn.GetFieldDefn(9).GetNameRef(), "0.7") outFeature.SetGeometry(geom) # Add new feature to output Layer outLayer.CreateFeature(outFeature) outFeature = None # Save and close DataSources inDataSource = None outDataSource = None if os.path.exists(out_shp_prelabel): outDriver.DeleteDataSource(out_shp_prelabel)
OutputSRS=3035): output = cr(rast, features_path, output_dir, gt, nodata, save2csv, save2raster, save2shp, unit_multiplier, return_array, OutputSRS) if return_array: return output if __name__ == "__main__": start = time.time() # path to the src data_warehouse = path + os.sep + 'AD/data_warehouse' features_path = data_warehouse + os.sep + "AT_NUTS3.shp" raster = data_warehouse + os.sep + "heat_tot_curr_density_AT.tif" output_dir = path + os.sep + 'Outputs' if not os.path.exists(output_dir): os.mkdir(output_dir) nodata = 0 rast, gt = RA(raster, return_gt=True) cr(rast, features_path, output_dir, gt, save2raster=True, save2shp=True, save2csv=True, return_array=True, nodata=0) elapsed = time.time() - start print("%0.3f seconds" % elapsed)