romero61 commited on
Commit
a2e48e3
·
1 Parent(s): 72e0094

working on instructions

Browse files
pages/01-main.py CHANGED
@@ -71,7 +71,7 @@ from data_vizui import EarthEngineDataVizUI
71
  from map_visuals import MapVizUI
72
  from export_ui import ExportUI
73
  from ee_cnn import CNN
74
-
75
  running = solara.reactive(False)
76
  status_message = solara.reactive("Ready to start.")
77
  timer_value = solara.reactive(0)
@@ -223,8 +223,7 @@ def CombinedThread(running, timer_value,t1, elapsed_time, status_message, availa
223
  result = solara.use_thread(thread_function, dependencies=[running.value])
224
 
225
 
226
-
227
-
228
 
229
 
230
  @solara.component
@@ -251,7 +250,7 @@ def Page():
251
  ]),
252
  v.ExpansionPanel(children=[
253
  v.ExpansionPanelHeader(children=['How To Duplicate Space']),
254
- v.ExpansionPanelContent(children=[' How to Duplicate and run on huggingface or git clone and run local. Earth Engine Account Requirements and Creating a Service Key.'])
255
  ]),
256
  v.ExpansionPanel(children=[
257
  v.ExpansionPanelHeader(children=['References']),
@@ -338,7 +337,7 @@ Adjustable x-axis and categories''')
338
  'cursor': 'pointer',
339
  'transition': 'background-color 0.3s ease'
340
  })
341
- solara.Warning('Caution the option "Earth Engine Imagery" for A WORLD Region takes approx. 4 Min and blocks any other functionality until completed.')
342
  map_vis = MapVizUI(model_data.value, data_flag.value, coordinates=vis_coordinates.value,country=vis_country.value)
343
 
344
 
 
71
  from map_visuals import MapVizUI
72
  from export_ui import ExportUI
73
  from ee_cnn import CNN
74
+ import instructions
75
  running = solara.reactive(False)
76
  status_message = solara.reactive("Ready to start.")
77
  timer_value = solara.reactive(0)
 
223
  result = solara.use_thread(thread_function, dependencies=[running.value])
224
 
225
 
226
+
 
227
 
228
 
229
  @solara.component
 
250
  ]),
251
  v.ExpansionPanel(children=[
252
  v.ExpansionPanelHeader(children=['How To Duplicate Space']),
253
+ v.ExpansionPanelContent(children=[instructions.EEInstructions(), instructions.HFInstructions(), instructions.AltInstructions()])
254
  ]),
255
  v.ExpansionPanel(children=[
256
  v.ExpansionPanelHeader(children=['References']),
 
337
  'cursor': 'pointer',
338
  'transition': 'background-color 0.3s ease'
339
  })
340
+ solara.Warning('Caution the option "Earth Engine Image" for A WORLD Region takes approx. 4 Min and blocks any other functionality until completed.')
341
  map_vis = MapVizUI(model_data.value, data_flag.value, coordinates=vis_coordinates.value,country=vis_country.value)
342
 
343
 
public/dots.png ADDED
public/dup_space.png ADDED
public/instructions.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import reacton.ipyvuetify as v
2
+ import solara
3
+
4
+ image1 = solara.Image('public\dots.png')
5
+ image2 = solara.Image('public\dup_space.png')
6
+ image3 = solara.Image('public\secrets.png')
7
+
8
+ @solara.component
9
+ def EEInstructions():
10
+ Text = solara.Markdown('''
11
+ Adapted from: <a href="https://developers.google.com/earth-engine/guides/service_account#create-a-service-account" target="_blank">https://developers.google.com/earth-engine/guides/service_account#create-a-service-account</a>
12
+ ### 1. Register a Google account with Earth Engine here:
13
+
14
+ <a href="https://code.earthengine.google.com/register" target="_blank">https://code.earthengine.google.com/register</a>
15
+
16
+ ### 2. Create a service account:
17
+ First, <a href="https://developers.google.com/earth-engine/cloud/earthengine_cloud_project_setup#create-a-cloud-project" target="_blank">create a Google Cloud project</a> if you have not already done so.
18
+
19
+ You can manage the service accounts for your Cloud project by going to the Cloud Console menu (blue square w/ three stacked white bars) and selecting IAM & Admin > <a href="https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts?supportedpurview=project" target="_blank">Service accounts</a>. (Choose the project if prompted.)
20
+
21
+ To create a new service account, click the<a href="https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts/create?supportedpurview=project" target="_blank">+ CREATE SERVICE ACCOUNT</a> link.
22
+
23
+ ### 3. Create a private key for the service account:
24
+ Once you have a service account, click the menu for that account (three dots stacked), then Create key > JSON. Download the JSON key file.
25
+
26
+ ''')
27
+ v.ExpansionPanels(children=[
28
+ v.ExpansionPanel(children=[
29
+ v.ExpansionPanelHeader(children=['Earth Engine Requirements']),
30
+ v.ExpansionPanelContent(children=[Text
31
+ ])
32
+ ])])
33
+
34
+ @solara.component
35
+ def HFInstructions():
36
+
37
+ Text = solara.Markdown(f'### 1. First Click on the the three dots:{image1}2. Second Click on Duplicate Space{image2}3. Input Secrets - You should have your Earth Engine json details ready, a word of caution when copying and pasting check that the spacing is correct and has only one tab space{image3}')
38
+
39
+
40
+
41
+ v.ExpansionPanels(children=[
42
+ v.ExpansionPanel(children=[
43
+ v.ExpansionPanelHeader(children=['Hugging Face Requirements']),
44
+ v.ExpansionPanelContent(children=[Text
45
+ ])
46
+ ])])
47
+ @solara.component
48
+ def AltInstructions():
49
+ Text = solara.Markdown('''
50
+ ### 1. Earth Engine
51
+ Explain still need EE account, can modify code to accept authenticate instead
52
+
53
+ ### 2. pip install
54
+ ### 3. Colab Notebook
55
+ ''')
56
+ v.ExpansionPanels(children=[
57
+ v.ExpansionPanel(children=[
58
+ v.ExpansionPanelHeader(children=['Alternatives to Hugging Face']),
59
+ v.ExpansionPanelContent(children=[Text
60
+ ])
61
+ ])])
public/map_visuals.py CHANGED
@@ -14,8 +14,9 @@ from matplotlib.figure import Figure
14
  from datasets import load_dataset
15
  from matplotlib.colors import ListedColormap, BoundaryNorm
16
  import ipywidgets as widgets
17
-
18
  import solara
 
19
 
20
  class MapVizUI:
21
  def __init__(self, dataframe, data_flag, coordinates=None, country=None):
@@ -321,8 +322,7 @@ class MapVizUI:
321
 
322
 
323
  elif viz_type == 'Earth Engine Image':
324
- print(viz_type)
325
- print(selected_option)
326
  if selected_option == 'All Days' or selected_option == 'Date Range':
327
  # Group by latitude and longitude and calculate the mean for each group
328
  filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
@@ -511,150 +511,153 @@ class MapVizUI:
511
  ax.set_title('Contour Plot of PM2.5 values', fontdict= {'fontsize':40,'fontweight': 'bold'})
512
 
513
  display(solara.FigureMatplotlib(fig, dependencies= None, format= 'svg'))
 
 
 
514
 
515
- @solara.component
516
- def MapVizUILayout(self):
517
 
518
- with solara.Column() as main:
519
 
520
- self.DateDropdown(self)
521
- self.StartDateDropdown(self)
522
- self.EndDateDropdown(self)
523
- self.VizTypeDropdown(self)
524
- self.ValueTypeDropdown(self)
525
- self.HourDropdown(self)
526
- self.GeneratePlotButton(self)
527
- display(self.output)
528
 
529
-
530
- return main
531
 
532
- def display(self):
533
- return self.MapVizUILayout(self)
 
 
 
 
 
 
 
 
 
534
 
535
- '''def update_data(self):
536
- selected_option = self.selected_date.value
537
- viz_type = self.selected_viz_type.value
538
-
539
 
540
- # Filter the dataframe based on user's selection
541
- if selected_option == 'All Days':
542
- filtered_df = self.dataframe
543
- set_filtered_data(filtered_df)
544
-
545
- elif selected_option == 'Date Range':
546
- start_date = pd.to_datetime(self.startday_options.value)
547
- end_date = pd.to_datetime(self.endday_options.value)
548
- mask = (self.dataframe.index.date >= start_date) & (self.dataframe.index.date <= end_date)
549
- filtered_df = self.dataframe[mask]
550
- set_filtered_data(filtered_df)
551
-
552
- elif selected_option == 'Single Day':
553
- selected_date = pd.to_datetime(self.endday_options.value)
554
- filtered_df = self.dataframe[self.dataframe.index.date == selected_date]
555
- set_filtered_data(filtered_df)
556
-
557
-
558
- if viz_type == ' Contour Map':
559
- if selected_option in ['All Days', 'Date Range']:
560
- if self.selected_vtype.value == '24 Hour Average':
561
- # Group by latitude and longitude and calculate the mean for each group
562
- filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
563
- set_filtered_data(filtered_df)
564
-
565
- else:
566
- hour = int(self.self.hour_options.value[:2]) # Extract the hour value from the string
567
- filtered_df = filtered_df[filtered_df.index.hour == hour]
568
- set_filtered_data(filtered_df)
569
-
570
 
571
- elif selected_option == 'Single Day':
572
- if self.selected_vtype.value == '24 Hour Average':
 
 
 
 
 
 
 
 
 
573
  # Group by latitude and longitude and calculate the mean for the whole day
574
  filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
575
- set_filtered_data(filtered_df)
576
 
577
- else:
578
- hour = int(self.self.hour_options.value[:2]) # Extract the hour value from the string
579
- filtered_df = filtered_df[filtered_df.index.hour == hour]
580
- set_filtered_data(filtered_df)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
581
 
 
 
 
 
 
 
 
582
 
 
583
 
584
- elif viz_type == 'Heat map':
585
- if selected_option in ['All Days', 'Date Range']:
586
- # Group by latitude and longitude and calculate the mean for each group
587
- filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
588
- set_filtered_data(filtered_df)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
 
590
- elif selected_option == 'Single Day':
591
- if self.selected_vtype.value != '24 Hour Average':
592
- hour = int(self.self.hour_options.value[:2]) # Extract the hour value from the string
593
- filtered_df = filtered_df[filtered_df.index.hour == hour]
594
- set_filtered_data(filtered_df)
595
-
596
- else:
597
- # Group by latitude and longitude and calculate the mean for the whole day
598
- filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
599
- set_filtered_data(filtered_df)
600
-
601
- filtered_data, set_filtered_data = solara.use_state(self.dataframe) # Initially, it's the whole dataframe
602
- flag = solara.use_reactive(False)
603
- filtered_df.rename(columns={"PM2.5": "PM25"}, inplace=True)
604
- set_filtered_data(filtered_df)
605
- with solara.Card('Maps'):
606
- with solara.Row():
607
- with solara.lab.Tabs():
608
- with solara.lab.Tab('Contour Plot'):
609
- with solara.Card(elevation=10, margin= 10):
610
-
611
-
612
-
613
- # Extract lats, lons, and values AFTER filtering
614
- lats = filtered_data['lat'].values
615
- lons = filtered_data['lon'].values
616
- values = filtered_data['PM2.5'].values
617
- # Custom color palette and breakpoints
618
- palette = ['green', 'yellow', 'orange', 'red', 'purple', 'maroon', 'maroon']
619
- aqi_breakpoints = [0, 50, 100, 150, 200, 300, 500]
620
- plt.rcParams['font.size'] = 30
621
- # Create a colormap and normalization based on your palette and breakpoints
622
- cmap = ListedColormap(palette)
623
- norm = BoundaryNorm(aqi_breakpoints, cmap.N)
624
-
625
-
626
- # Create a figure and axis using the object-oriented interface
627
- fig = Figure(figsize=(20, 10), dpi= 500, edgecolor='black', linewidth = 1, frameon= True)
628
-
629
- ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
630
-
631
- # Set the extent
632
- ax.set_extent(self.get_map_extent())
633
-
634
- # Add features to the map
635
- ax.add_feature(cfeature.COASTLINE)
636
- ax.add_feature(cfeature.BORDERS, linestyle=':')
637
- ax.gridlines(draw_labels=True)
638
-
639
- # Create the contour plot
640
- contour = ax.tricontourf(lons, lats, values, transform=ccrs.PlateCarree(), cmap=cmap, norm = norm)
641
-
642
- # Add a colorbar
643
- cbar = fig.colorbar(contour, ax=ax, orientation='vertical', pad = 0.1, ticks=aqi_breakpoints)
644
- cbar.set_label('PM2.5 Value')
645
-
646
- # Set the title
647
- ax.set_title('Contour Plot of PM2.5 values', fontdict= {'fontsize':40,'fontweight': 'bold'})
648
-
649
- solara.FigureMatplotlib(fig, dependencies= [filtered_data, flag.value])
650
-
651
- with solara.lab.Tab('Heat Map'):
652
- with solara.Card(elevation=10, margin= 10):
653
- # Initialize a geemap Map
654
-
655
- self.Map.add_basemap('CartoDB.Voyager')
656
- self.Map.set_zoom(1)
657
- self.Map.add_heatmap(filtered_data, latitude= 'lat', longitude='lon', value= 'PM2.5', radius= 10)
658
- #Map.layer_opacity("Heat map", opacity = .75)
659
-
660
- display(self.Map) '''
 
14
  from datasets import load_dataset
15
  from matplotlib.colors import ListedColormap, BoundaryNorm
16
  import ipywidgets as widgets
17
+ import requests
18
  import solara
19
+ import geedim as gd
20
 
21
  class MapVizUI:
22
  def __init__(self, dataframe, data_flag, coordinates=None, country=None):
 
322
 
323
 
324
  elif viz_type == 'Earth Engine Image':
325
+ solara.SpinnerSolara(size="100px")
 
326
  if selected_option == 'All Days' or selected_option == 'Date Range':
327
  # Group by latitude and longitude and calculate the mean for each group
328
  filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
 
511
  ax.set_title('Contour Plot of PM2.5 values', fontdict= {'fontsize':40,'fontweight': 'bold'})
512
 
513
  display(solara.FigureMatplotlib(fig, dependencies= None, format= 'svg'))
514
+
515
+
516
+
517
 
 
 
518
 
 
519
 
520
+ def csv_download(self):
521
+ compression_opts = dict(method='zip', archive_name='model_results.csv')
522
+ model_results = self.dataframe.to_csv('model_results.csv',index = True, compression=compression_opts)
523
+ solara.FileDownload(model_results, mime_type="application/zip")
524
+
525
+ '''def tiff_download(self):
 
 
526
 
 
 
527
 
528
+ # Filter the dataframe based on user's selection
529
+ if self.selected_date.value == 'All Days':
530
+ filtered_df = self.dataframe
531
+ elif self.selected_date.value == 'Date Range':
532
+ start_date = pd.to_datetime(self.startday_options.value)
533
+ end_date = pd.to_datetime(self.endday_options.value)
534
+ mask = (self.dataframe.index.date >= start_date) & (self.dataframe.index.date <= end_date)
535
+ filtered_df = self.dataframe[mask]
536
+ elif self.selected_date.value == 'Single Day':
537
+ selected_date = pd.to_datetime(self.endday_options.value)
538
+ filtered_df = self.dataframe[self.dataframe.index.date == selected_date.date()]
539
 
 
 
 
 
540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
541
 
542
+
543
+ if self.selected_date.value == 'All Days' or self.selected_date.value == 'Date Range':
544
+ # Group by latitude and longitude and calculate the mean for each group
545
+ filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
546
+ elif self.selected_date.value == 'Single Day':
547
+ if self.selected_vtype.value != '24 Hour Average':
548
+ hour_minute = self.hour_options.value.split(':') # This will give ['17', '30'] for '17:30'
549
+ hour = int(hour_minute[0]) # Extract the hour value
550
+ minute = int(hour_minute[1]) # Extract the minute value
551
+ filtered_df = filtered_df[(filtered_df.index.hour == hour) & (filtered_df.index.minute == minute)]
552
+ else:
553
  # Group by latitude and longitude and calculate the mean for the whole day
554
  filtered_df = filtered_df.groupby(['lat', 'lon'])['PM2.5'].mean().reset_index()
555
+
556
 
557
+ # Check if filtered_df is empty
558
+ if filtered_df.empty:
559
+ print("No data available for the selected criteria.")
560
+ return
561
+
562
+ filtered_df.rename(columns={"PM2.5": "PM25"}, inplace=True)
563
+ if 'Hour' in filtered_df.columns:
564
+ filtered_df = filtered_df.drop(columns=['Hour'])
565
+
566
+
567
+
568
+
569
+ # Calculate the extent of the data
570
+ min_lat, max_lat = filtered_df['lat'].min(), filtered_df['lat'].max()
571
+ min_lon, max_lon = filtered_df['lon'].min(), filtered_df['lon'].max()
572
+ # Predefined latitude and longitude bands
573
+ lat_bands = [[-90, 0], [0, 90]]
574
+ lon_bands = [[-180, -108], [-108, -36], [-36, 36], [36, 108], [108, 180]]
575
+
576
+ # Create subsets based on the predefined bands
577
+ subsets = []
578
+ for lat_band in lat_bands:
579
+ for lon_band in lon_bands:
580
+ subset = filtered_df[
581
+ (filtered_df['lat'] >= lat_band[0]) & (filtered_df['lat'] <= lat_band[1]) &
582
+ (filtered_df['lon'] >= lon_band[0]) & (filtered_df['lon'] <= lon_band[1])
583
+ ]
584
+ subsets.append(subset)
585
+
586
+
587
+
588
+ # Initialize an empty ImageCollection
589
+ image_collection = ee.ImageCollection([])
590
+
591
+ # Process each subset
592
+ for idx, subset in enumerate(subsets):
593
+
594
+ print(f'Processing subset {idx+1}...')
595
+
596
+ if not subset.empty:
597
+ # Convert the DataFrame subset to an Earth Engine FeatureCollection
598
+ ee_fc = geemap.df_to_ee(subset, latitude='lat', longitude='lon')
599
+ # Convert the FeatureCollection to an Image for V8
600
+ v8_image = ee.Image(ee_fc.reduceToImage(['PM25'], ee.Reducer.first()))
601
+
602
+
603
+ # Define a crsTransform for the desired pixel size
604
+ pixel_size = .63
605
+ crs_transform = [pixel_size, 0, min_lon, 0, -pixel_size, max_lat]
606
 
607
+ # Reproject the image
608
+ v8_image_pixels = v8_image.reproject(crs='EPSG:4326', crsTransform=crs_transform)
609
+
610
+ # Add the image to the ImageCollection
611
+ image_collection = image_collection.merge(ee.ImageCollection([v8_image_pixels]))
612
+
613
+
614
 
615
+
616
 
617
+ if not self.world:
618
+ # Reduce the ImageCollection to a single image
619
+ combined_image = image_collection.mosaic()
620
+ # Define a custom region of interest (as an example)
621
+ region = ee.Geometry.Rectangle([min_lon, min_lat, max_lon, max_lat])
622
+
623
+ geemap.download_ee_image(
624
+ image=combined_image,
625
+ filename='model_result.tiff',
626
+ overwrite=True,
627
+ crs='EPSG:4326',
628
+ crs_transform=crs_transform,
629
+ region=region,
630
+ scale=30
631
+ )
632
+
633
+ else:
634
+
635
+ # Generate a download URL
636
+ geemap.download_ee_image_collection(
637
+ collection=image_collection,
638
+ out_dir='C:/Users/bsf31/Documents/post-meds/huggingface/USRA-STI/public',
639
+ overwrite=True
640
+ )'''
641
+
642
+
643
+ @solara.component
644
+ def MapVizUILayout(self):
645
+
646
+ with solara.Column() as main:
647
+ self.DateDropdown(self)
648
+ self.StartDateDropdown(self)
649
+ self.EndDateDropdown(self)
650
+ self.VizTypeDropdown(self)
651
+ self.ValueTypeDropdown(self)
652
+ self.HourDropdown(self)
653
+ self.GeneratePlotButton(self)
654
+ display(self.output)
655
+ with solara.Row():
656
 
657
+ solara.Button( 'Download CSV',on_click=self.csv_download, icon_name="mdi-cloud-download-outline", color="orange")
658
+ #solara.Button('Download TIFF', on_click=self.tiff_download, outlined =True, icon_name="mdi-cloud-download-outline", color="orange")
659
+
660
+ return main
661
+
662
+ def display(self):
663
+ return self.MapVizUILayout(self)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
public/secrets.png ADDED
requirements.txt CHANGED
@@ -21,3 +21,4 @@ solara
21
  pydantic
22
  leafmap
23
  datasets
 
 
21
  pydantic
22
  leafmap
23
  datasets
24
+ geedim