dcascade-app / pages /01_dcascade_OLD.py
Kelbec
WIP missing highlights on selection
092753f
import os
from pathlib import Path
import shutil
from typing import Callable, Optional, Union, cast
# import leafmap
import textwrap
import leafmap.kepler as leafmap
import solara
from leafmap.toolbar import change_basemap
from solara.components.file_drop import FileInfo
from dcascade_py import dcascade_py
zoom = solara.reactive(2)
center = solara.reactive((20, 0))
config = {'version': 'v1',
'config': {'visState': {'filters': [{'dataId': ['Discharge'],
'id': '58woufh3',
'name': ['ts'],
'type': 'range',
'value': [0, 1.68], ###time change here
'enlarged': False,
'plotType': 'histogram',
'animationWindow': 'free',
'yAxis': None,
'speed': 1}],
'layers': [{'id': 'lqz57i8',
'type': 'geojson',
'config': {'dataId': 'Discharge',
'label': 'Discharge',
'color': [18, 147, 154],
'highlightColor': [252, 242, 26, 255],
'columns': {'geojson': '_geojson'},
'isVisible': True,
'visConfig': {'opacity': 0.8,
'strokeOpacity': 0.3,
'thickness': 1,
'strokeColor': [210, 0, 0],
'colorRange': {'name': 'Global Warming',
'type': 'sequential',
'category': 'Uber',
'colors': ['#5A1846',
'#900C3F',
'#C70039',
'#E3611C',
'#F1920E',
'#FFC300']},
'strokeColorRange': {'name': 'Ice And Fire',
'type': 'diverging',
'category': 'Uber',
'colors': ['#0198BD',
'#49E3CE',
'#E8FEB5',
'#FEEDB1',
'#FEAD54',
'#D50255']},
'radius': 10,
'sizeRange': [0, 10],
'radiusRange': [0, 50],
'heightRange': [0, 500],
'elevationScale': 5,
'enableElevationZoomFactor': True,
'stroked': True,
'filled': False,
'enable3d': False,
'wireframe': False},
'hidden': False,
'textLabel': [{'field': None,
'color': [255, 255, 255],
'size': 18,
'offset': [0, 0],
'anchor': 'start',
'alignment': 'center'}]},
'visualChannels': {'colorField': None,
'colorScale': 'quantile',
'strokeColorField': {'name': 'Discharge', 'type': 'real'},
'strokeColorScale': 'quantize',
'sizeField': None,
'sizeScale': 'linear',
'heightField': None,
'heightScale': 'linear',
'radiusField': None,
'radiusScale': 'linear'}}],
'interactionConfig': {'tooltip': {'fieldsToShow': {'Discharge': [{'name': 'ts',
'format': None},
{'name': 'Discharge', 'format': None}]},
'compareMode': False,
'compareType': 'absolute',
'enabled': True},
'brush': {'size': 0.5, 'enabled': False},
'geocoder': {'enabled': False},
'coordinate': {'enabled': False}},
'layerBlending': 'additive',
'splitMaps': [],
'animationConfig': {'currentTime': None, 'speed': 1}},
'mapState': {'bearing': 0,
'dragRotate': False,
'latitude': 40.24060796334474,
'longitude': 20.565835594966174,
'pitch': 0,
'zoom': 8.776177236597563,
'isSplit': False},
'mapStyle': {'styleType': 'dark',
'topLayerGroups': {},
'visibleLayerGroups': {'label': True,
'road': True,
'border': False,
'building': True,
'water': True,
'land': True,
'3d building': False},
'threeDBuildingColor': [9.665468314072013,
17.18305478057247,
31.1442867897876],
'mapStyles': {}}}}
class Map(leafmap.Map):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.updateMap()
# Add what you want below
# self.add_basemap("OpenTopoMap")
# change_basemap(self)
# self.add_shp()
def updateMap(self):
self.add_shp("public/deposito.shp", "Discharge")
self.config = config
# self.add_basemap("OpenTopoMap")
# change_basemap(self)
@solara.component
def MapComponent():
m = Map()
m.element( # type: ignore
zoom=zoom.value,
on_zoom=zoom.set,
center=center.value,
on_center=center.set,
scroll_wheel_zoom=True,
toolbar_ctrl=False,
data_ctrl=False,
)
m.config = config
@solara.component
def Page():
with solara.Column(style={"min-width": "500px"}):
content, set_content = solara.use_state(b"")
uploaded, set_uploaded = solara.use_state(b"")
filename, set_filename = solara.use_state("")
river_filename, set_river_filename = solara.use_state("")
q_filename, set_q_filename = solara.use_state("")
error_select_csv, set_error_select_csv = solara.use_state("")
error_select_shp, set_error_select_shp = solara.use_state("")
no_file_selected, set_no_file_selected = solara.use_state("")
# removed_data, set_removed = solara.use_state("")
size, set_size = solara.use_state(0)
file_browser, set_file_browser = solara.use_state(cast(Optional[Path], None))
map_loaded, set_map_loaded = solara.use_state(False)
formulas = ["Parker and Klingeman 1982", "Wilkock and Crowe 2003", "Engelund and Hansen 1967", "Yang formula 1989", "Wong and Parker 2006", "Ackers and White formula 1973"]
formula = solara.reactive("Engelund and Hansen 1967")
partitionings = ["Direct", "Bed material fraction (BMF)", "Transport capacity function (TCF)", "Shear stress correction approach"]
partitioning = solara.reactive("Shear stress correction approach")
timescale = solara.reactive("20")
sed_range = solara.reactive("-8,4")
class_size = solara.reactive(2.5)
deposit = solara.reactive(50.0)
continuous_update = solara.reactive(True)
def on_file(file: FileInfo):
set_filename(file["name"])
set_size(file["size"])
f = file["file_obj"]
set_content(f.read())
set_uploaded(False)
def upload_file():
if content:
file_path = os.path.join("public",filename)
with open(file_path,"wb") as file:
file.write(content)
if filename.endswith(".zip"):
shutil.unpack_archive(os.getcwd()+"/public/"+filename,os.getcwd()+"/public")
os.remove(os.getcwd()+"/public/"+filename)
set_uploaded(True)
def open_river_file():
if file_browser:
file_path = os.path.join(os.getcwd(),file_browser)
if file_path.endswith(".shp"):
set_river_filename(file_path)
set_error_select_shp(False)
set_no_file_selected(False)
else:
set_error_select_shp(True)
else:
set_error_select_shp(True)
def open_q_file():
if file_browser:
file_path = os.path.join(os.getcwd(),file_browser)
if file_path.endswith(".csv"):
set_q_filename(file_path)
set_error_select_csv(False)
else:
set_error_select_csv(True)
else:
set_error_select_csv(True)
def remove_data():
for file in os.listdir(os.getcwd()+"/public"):
os.remove(os.getcwd()+"/public/"+file)
def run_dcascade():
if (river_filename == "" or q_filename == ""):
set_no_file_selected(True)
else:
set_no_file_selected(False)
sel_form = formulas.index(str(formula).replace("'",""))+1
sel_part = partitionings.index(str(partitioning).replace("'",""))+1
sel_timescale = int(str(timescale).replace("'",""))
set_map_loaded(False)
river = river_filename
q = q_filename
out = os.getcwd()+"/public/deposito"
out_shp = out+".shp"
out_prj = out+".prj"
shutil.copyfile(river,out_prj)
print("Calling dcascade_py with parameters: river: ", river, " q: ", q, " sed_range: ", sed_range.value, " class_size: ", class_size.value, " deposit: ", deposit.value, " timescale: ", sel_timescale, " formula: ", sel_form, " partitioning: ", sel_part, " out: ", out_shp)
dcascade_py(river, q, sed_range=sed_range.value, class_size=class_size.value, deposit=deposit.value, timescale=sel_timescale, formula=sel_form, partitioning=sel_part, out=out_shp, version=False, verbose=False, debug=False, credits=False)
set_map_loaded(True)
with solara.Div() as main:
with solara.Card("Dcascade"):
if map_loaded:
MapComponent()
with solara.Card("Upload files"):
solara.Markdown("Required \*.shp, \*.shx, \*.dbf and \*.prj files for **river** file and \*.csv for **q** file. Upload files one at the time or compressed in a *zip* archive.")
with solara.ColumnsResponsive(1, large=6):
solara.FileDrop(
label="Drag and drop a file here ",
on_file=on_file,
lazy=True,
)
solara.Button("Upload file",
color="primary",
on_click=upload_file)
if content and not uploaded:
solara.Info(f"File {filename} has total length: {size}\n",
text=True,
dense=True,
icon=True,
)
# solara.Preformatted("\n".join(textwrap.wrap(repr(content))))
# solara.Preformatted("\n".join(textwrap.wrap(repr(filename))))
elif uploaded:
solara.Success(
f"{filename} uploaded",
text=True,
dense=True,
icon=True,
)
with solara.Card("Select parameters"):
with solara.ColumnsResponsive(3, large=4):
solara.InputText("Timescale (days)", value=timescale, continuous_update=continuous_update.value)
solara.Select(label="Formula", value=formula, values=formulas)
# solara.Markdown(f"**Selected**: {formula.value}")
solara.Select(label="Partitioning ", value=partitioning, values=partitionings)
# solara.Markdown(f"**Selected**: {partitioning.value}")
solara.InputText(label="Sed range ", value=sed_range)
solara.InputFloat(label="Class size ", value=class_size)
solara.InputFloat(label="Deposit ", value=deposit)
with solara.Card("Select files"):
solara.Markdown("Select **river** and **q** files from file explorer below, the uploaded files can be found in /public folder. To select files click on the explorer the click on *SELECT RIVER FILE* or *SELECT Q FILE* based on the file selected.")
with solara.ColumnsResponsive(3, large=6):
solara.Markdown(f"**River file**: {river_filename}")
solara.Button("Select river file",
color="primary",
on_click=open_river_file)
with solara.ColumnsResponsive(3, large=6):
solara.Markdown(f"**Q file**: {q_filename}")
solara.Button("Select Q file",
color="primary",
on_click=open_q_file)
if error_select_csv:
solara.Warning(f"Q file must be csv",
text=True,
dense=True,
icon=True,
)
if error_select_shp:
solara.Warning(f"River file must be shp",
text=True,
dense=True,
icon=True,
)
solara.FileBrowser(
can_select=False,
on_file_open=set_file_browser,
directory="./public"
)
with solara.Card("Run model"):
with solara.ColumnsResponsive(3, large=6):
solara.Markdown("Click on DCASCADE button to run the model and generate the output map")
solara.Button("DCASCADE",
color="primary",
on_click=run_dcascade)
if no_file_selected:
solara.Warning(f"Select both River and Q files",
text=True,
dense=True,
icon=True,
)
# solara.Button("REMOVE DATA",
# color="secondary",
# on_click=remove_data)
# solara.Info(f"You are in directory: {directory}")
# solara.Info(f"You selected path: {path}")
# solara.Info(f"You opened file: {file}")
# if removed_data:
# solara.Success(
# f"Removed data",
# text=True,
# dense=True,
# icon=True,
# )