File size: 14,258 Bytes
092753f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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,
                    #         )