Ziyuan111 commited on
Commit
5a63e98
1 Parent(s): 8d59145

Upload urban_tree_canopy_in_durham.py

Browse files
Files changed (1) hide show
  1. urban_tree_canopy_in_durham.py +298 -0
urban_tree_canopy_in_durham.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Urban_Tree_Canopy_in_Durham
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1X59zPtI7ydiX10ZnfjsNGvnKNTXgwrWs
8
+ """
9
+
10
+ ! pip install datasets
11
+ import csv
12
+ import json
13
+ import os
14
+ from typing import List
15
+ import datasets
16
+ import logging
17
+ from datasets import DatasetBuilder, DownloadManager, SplitGenerator, Split
18
+
19
+ import zipfile
20
+ import json
21
+ import pandas as pd
22
+ import geopandas as gpd
23
+
24
+ class Urban_Tree_Canopy_in_Durham(DatasetBuilder):
25
+ # Define the `_info` method, which provides dataset metadata
26
+ def _info(self):
27
+ return DatasetInfo(
28
+ description="A description of the dataset.",
29
+ features=Features(
30
+ {
31
+ "objectid": Value("int32"),
32
+ "streetaddr": Value("string"),
33
+ "city_x": Value("string"),
34
+ "zipcode_x": Value("string"),
35
+ "facilityid_x": Value("string"),
36
+ "present_x": Value("string"),
37
+ "genus_x": Value("string"),
38
+ "species_x": Value("string"),
39
+ "commonname_x": Value("string"),
40
+ "plantingda": Value("datetime"),
41
+ "diameterin_x": Value("float"),
42
+ "heightft_x": Value("float"),
43
+ "condition_x": Value("string"),
44
+ "contractwo": Value("string"),
45
+ "neighborho": Value("string"),
46
+ "program_x": Value("string"),
47
+ "plantingw_x": Value("string"),
48
+ "plantingco": Value("string"),
49
+ "underpwerl": Value("string"),
50
+ "matureheig": Value("float"),
51
+ "globalid_x": Value("string"),
52
+ "created_us": Value("string"),
53
+ "created_da": Value("datetime"),
54
+ "last_edite": Value("string"),
55
+ "last_edi_1": Value("datetime"),
56
+ "isoprene_x": Value("float"),
57
+ "monoterpen": Value("float"),
58
+ "vocs_x": Value("float"),
59
+ "coremoved_": Value("float"),
60
+ "coremove_1": Value("float"),
61
+ "o3removed_": Value("float"),
62
+ "o3remove_1": Value("float"),
63
+ "no2removed": Value("float"),
64
+ "no2remov_1": Value("float"),
65
+ "so2removed": Value("float"),
66
+ "so2remov_1": Value("float"),
67
+ "pm10remove": Value("float"),
68
+ "pm10remo_1": Value("float"),
69
+ "pm25remove": Value("float"),
70
+ "o2producti": Value("float"),
71
+ "replaceval": Value("float"),
72
+ "carbonstor": Value("float"),
73
+ "carbonst_1": Value("float"),
74
+ "grosscarse": Value("float"),
75
+ "grosscar_1": Value("float"),
76
+ "avoidrunof": Value("float"),
77
+ "avoidrun_1": Value("float"),
78
+ "polremoved": Value("float"),
79
+ "polremov_1": Value("float"),
80
+ "totannbene": Value("float"),
81
+ "leafarea_s": Value("float"),
82
+ "potevapotr": Value("float"),
83
+ "evaporatio": Value("float"),
84
+ "transpirat": Value("float"),
85
+ "h2ointerce": Value("float"),
86
+ "avoidrunva": Value("float"),
87
+ "avoidrun_2": Value("float"),
88
+ "carbonavoi": Value("float"),
89
+ "carbonav_1": Value("float"),
90
+ "heating_mb": Value("float"),
91
+ "heating_do": Value("float"),
92
+ "heating_kw": Value("float"),
93
+ "heating__1": Value("float"),
94
+ "cooling_kw": Value("float"),
95
+ "cooling_do": Value("float"),
96
+ "totalenerg": Value("float"),
97
+ "geometry_x": Value("string"),
98
+ "x": Value("float"),
99
+ "y": Value("float"),
100
+ "streetaddress_x": Value("string"),
101
+ "city_y": Value("string"),
102
+ "zipcode_y": Value("string"),
103
+ "facilityid_y": Value("string"),
104
+ "present_y": Value("string"),
105
+ "genus_y": Value("string"),
106
+ "species_y": Value("string"),
107
+ "commonname_y": Value("string"),
108
+ "plantingdate_x": Value("datetime"),
109
+ "diameterin_y": Value("float"),
110
+ "heightft_y": Value("float"),
111
+ "condition_y": Value("string"),
112
+ "contractwork_x": Value("string"),
113
+ "neighborhood_x": Value("string"),
114
+ "program_y": Value("string"),
115
+ "plantingw_y": Value("string"),
116
+ "plantingcond_x": Value("string"),
117
+ "underpwerlins_x": Value("string"),
118
+ "matureheight_x": Value("float"),
119
+ "globalid_y": Value("string"),
120
+ "created_user_x": Value("string"),
121
+ "created_date_x": Value("datetime"),
122
+ "last_edited_user_x": Value("string"),
123
+ "last_edited_date_x": Value("datetime"),
124
+ "isoprene_y": Value("float"),
125
+ "monoterpene_x": Value("float"),
126
+ "vocs_y": Value("float"),
127
+ "coremoved_ozperyr_x": Value("float"),
128
+ "coremoved_dolperyr_x": Value("float"),
129
+ "o3removed_ozperyr_x": Value("float"),
130
+ "o3removed_dolperyr_x": Value("float"),
131
+ "no2removed_ozperyr_x": Value("float"),
132
+ "no2removed_dolperyr_x": Value("float"),
133
+ "so2removed_ozperyr_x": Value("float"),
134
+ "so2removed_dolperyr_x": Value("float"),
135
+ "pm10removed_dolperyr_y":Value("float"),
136
+ "pm25removed_ozperyr_y":Value("float"),
137
+ "o2production_lbperyr_y":Value("float"),
138
+ "replacevalue_dol_y":Value("float"),
139
+ "carbonstorage_lb_y":Value("float"),
140
+ "carbonstorage_dol_y":Value("float"),
141
+ "grosscarseq_lbperyr_y":Value("float"),
142
+ "grosscarseq_dolperyr_y":Value("float"),
143
+ "avoidrunoff_ft2peryr":Value("float"),
144
+
145
+ }
146
+ ),
147
+ supervised_keys=None,
148
+ homepage="https://github.com/AuraMa111/Urban_Tree_Canopy_in_Durham",
149
+ citation="A citation or reference to the source of the dataset.",
150
+ )
151
+
152
+ # ... (include _info method here)
153
+
154
+ def _split_generators(self, dl_manager: DownloadManager):
155
+ def _split_generators(self, dl_manager: tfds.download.DownloadManager):
156
+ # Download the source data
157
+ downloaded_files = dl_manager.download_and_extract({
158
+ "csv": "https://raw.githubusercontent.com/AuraMa111/Urban_Tree_Canopy_in_Durham/main/Trees_%2526_Planting_Sites.csv",
159
+ "geojson_zip": "https://raw.githubusercontent.com/AuraMa111/Urban_Tree_Canopy_in_Durham/main/Trees_%2526_Planting_Sites.geojson.zip",
160
+ "zip": "https://raw.githubusercontent.com/AuraMa111/Urban_Tree_Canopy_in_Durham/main/TreesPlanting_Sites.zip"
161
+ })
162
+
163
+ # Return split generators
164
+ return [
165
+ tfds.core.SplitGenerator(
166
+ name=tfds.Split.TRAIN,
167
+ gen_kwargs={
168
+ "file_path_csv": downloaded_files["csv"],
169
+ "file_path_zip": downloaded_files["zip"],
170
+ "file_path_geojson_zip": downloaded_files["geojson_zip"],
171
+ },
172
+ ),
173
+ # Add other splits if necessary
174
+ ]
175
+
176
+ def _generate_examples(self, file_path_csv, file_path_zip, file_path_geojson_zip):
177
+ # Generate examples from CSV
178
+ csv_df = self.process_csv_file(file_path_csv)
179
+
180
+ # Generate examples from Shapefiles within ZIP
181
+ shp_gdf = self.process_zip_shapefiles(file_path_zip)
182
+
183
+ # Generate examples from GeoJSON within ZIP
184
+ geojson_gdf = self.process_zip_geojson(file_path_geojson_zip)
185
+
186
+ # Merge the DataFrames
187
+ combined_gdf = self.merge_dataframes(csv_df, shp_gdf, geojson_gdf)
188
+
189
+ # Generate final examples
190
+ for idx, example in self.generate_examples_from_merged_data(combined_gdf):
191
+ yield idx, example
192
+
193
+ def process_csv_file(self, file_path):
194
+ with open(file_path, 'r') as f:
195
+ csv_df = pd.read_csv(f)
196
+ csv_df.drop_duplicates(inplace=True)
197
+ csv_df.fillna(method='bfill', inplace=True)
198
+ csv_df.columns = csv_df.columns.str.lower().str.replace(' ', '_')
199
+ csv_df['objectid'] = csv_df['objectid'].astype(int)
200
+ return csv_df
201
+
202
+ def process_zip_shapefiles(self, file_path):
203
+ with zipfile.ZipFile(file_path, 'r') as z:
204
+ for file_name in z.namelist():
205
+ if file_name.endswith(".shp"):
206
+ with z.open(file_name) as file:
207
+ shp_gdf = gpd.read_file(file)
208
+ shp_gdf.columns = shp_gdf.columns.str.lower().str.replace(' ', '_')
209
+ shp_gdf['objectid'] = shp_gdf['objectid'].astype(int)
210
+ return shp_gdf
211
+
212
+ def process_zip_geojson(self, file_path):
213
+ with zipfile.ZipFile(file_path, 'r') as z:
214
+ for file_name in z.namelist():
215
+ if file_name.endswith(".geojson"):
216
+ with z.open(file_name) as file:
217
+ geojson_data = json.load(file)
218
+ geojson_gdf = gpd.GeoDataFrame.from_features(geojson_data['features'])
219
+ geojson_gdf.columns = geojson_gdf.columns.str.lower().str.replace(' ', '_')
220
+ geojson_gdf['objectid'] = geojson_gdf['objectid'].astype(int)
221
+ return geojson_gdf
222
+
223
+ def merge_dataframes(self, csv_df, shp_gdf, geojson_gdf):
224
+ combined_gdf = shp_gdf.merge(csv_df, on='objectid', how='inner')
225
+ combined_gdf = combined_gdf.merge(geojson_gdf, on='objectid', how='left')
226
+ return combined_gdf
227
+
228
+ def generate_examples_from_merged_data(self, combined_gdf):
229
+ for idx, row in combined_gdf.iterrows():
230
+ example = row.to_dict()
231
+
232
+ if 'geometry' in row and row['geometry'] is not None:
233
+ example['geometry'] = json.loads(gpd.GeoSeries([row['geometry']]).to_json())['features'][0]['geometry']
234
+
235
+ yield idx, example
236
+ def plot_spatial_distribution(self, gdf, lat_col='latitude', lon_col='longitude', color_col='species', hover_col='species'):
237
+ """
238
+ Visualize the spatial distribution of the data using Plotly.
239
+
240
+ Parameters:
241
+ - gdf: GeoDataFrame to be visualized.
242
+ - lat_col: String, name of the column with latitude values.
243
+ - lon_col: String, name of the column with longitude values.
244
+ - color_col: String, name of the column to determine the color of points.
245
+ - hover_col: String, name of the column to show when hovering over points.
246
+ """
247
+ center_lat = gdf[lat_col].mean()
248
+ center_lon = gdf[lon_col].mean()
249
+
250
+ fig = px.scatter_mapbox(gdf,
251
+ lat=lat_col,
252
+ lon=lon_col,
253
+ color=color_col,
254
+ hover_name=hover_col,
255
+ center={"lat": center_lat, "lon": center_lon},
256
+ zoom=10,
257
+ height=600,
258
+ width=800)
259
+
260
+ fig.update_layout(mapbox_style="open-street-map")
261
+ fig.show()
262
+ def plot_correlation_heatmap(self, gdf, columns, figsize=(10, 8), cmap='coolwarm'):
263
+ """
264
+ Plot a heatmap of the correlation matrix for selected columns in the GeoDataFrame.
265
+
266
+ Parameters:
267
+ - gdf: GeoDataFrame containing the data.
268
+ - columns: List of columns to include in the correlation matrix.
269
+ - figsize: Tuple of figure size dimensions (width, height).
270
+ - cmap: Colormap for the heatmap.
271
+ """
272
+ # Select only the columns with environmental data
273
+ env_data = gdf[columns]
274
+
275
+ # Compute the correlation matrix
276
+ corr = env_data.corr()
277
+
278
+ # Set up the matplotlib figure
279
+ plt.figure(figsize=figsize)
280
+
281
+ # Generate a heatmap
282
+ sns.heatmap(corr, annot=True, fmt=".2f", cmap=cmap, square=True, linewidths=.5, cbar_kws={"shrink": .5})
283
+
284
+ # Optional: Adjust the layout
285
+ plt.tight_layout()
286
+
287
+ # Show the plot
288
+ plt.show()
289
+ # Usage example:
290
+ # data_processor = DataProcessor()
291
+ # for key, example in data_processor._generate_examples(csv_path, zip_path, geojson_zip_path):
292
+ # # Do something with key and example
293
+ # Usage example:
294
+ # data_processor = DataProcessor()
295
+ # for key, example in data_processor._generate_examples(csv_path, zip_path, geojson_zip_path):
296
+ # # Do something with key and example
297
+ # combined_gdf = data_processor.merge_dataframes(csv_df, shp_gdf, geojson_gdf)
298
+ # data_processor.plot_spatial_distribution(combined_gdf, lat_col='y', lon_col='x', color_col='species_x', hover_col='species_x')