File size: 6,612 Bytes
5a1ff44
aea4fce
5a1ff44
a4feeb2
5a1ff44
 
760889f
5a1ff44
aea4fce
5a1ff44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
006a8c3
5a1ff44
9ea8ec2
5a1ff44
 
aea4fce
 
 
 
 
 
 
 
 
 
 
a4feeb2
 
 
 
 
 
 
 
aea4fce
 
a4feeb2
aea4fce
 
 
 
 
 
 
 
b611df6
aea4fce
 
5a1ff44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc0c6a0
 
f16b7aa
 
2dc2135
 
 
 
 
 
 
 
 
5a1ff44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc2135
5a1ff44
 
 
 
 
 
 
 
 
 
 
2dc2135
5a1ff44
 
a4feeb2
5a1ff44
 
 
59f8e2c
5a1ff44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc0c6a0
f16b7aa
5a1ff44
 
aea4fce
a4feeb2
 
 
5a1ff44
 
 
9ea8ec2
a4feeb2
5a1ff44
 
 
 
 
 
 
 
 
 
a4feeb2
5a1ff44
 
60fd94d
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
import os
import zipfile
import gradio as gr
import pandas as pd
import plotly.graph_objects as go

from geo_tools import (
    shapefile_to_latlong,
    mask_shapefile_to_grid_indices,
    points_to_shapefile,
    get_cached_grid_indices,
)

DATA_DIR = "data/"
MASK_PATH = os.path.join(DATA_DIR, "serp.shp")
HOSP_PATH = os.path.join(DATA_DIR, "hospitals.shp")
POLICE_PATH = os.path.join(DATA_DIR, "police.shp")
OUT_DIR = "out/"


def gr_generate_map(
    side_len: str,
    show_hospitals: bool = True,
    show_police: bool = True,
    region: str = "None",
):
    token = "pk.eyJ1IjoiZGlsaXRoIiwiYSI6ImNsaTZ3b3I4MjF6MmczZG80cXBmeTgyaGsifQ.JmrU3qbp2jlK_9Yl2il8pw"
    side_len = float(side_len)
    show_mask = False

    scattermaps = []
    grid_path = MASK_PATH[: -len(".shp")] + f"-gap={side_len}.shp"
    prefix = ".".join(grid_path.split(".")[:-1])
    if not os.path.exists(grid_path):
        indices, labels = mask_shapefile_to_grid_indices(MASK_PATH, side_len)
        points_to_shapefile(indices, labels, grid_path)

        file_list = [prefix + ext for ext in (".shp", ".shx", ".prj", ".dbf", ".cpg")]
        with zipfile.ZipFile(prefix + ".zip", "w") as fp:
            for file in file_list:
                fp.write(file, compress_type=zipfile.ZIP_DEFLATED)

        grid_point_df = pd.DataFrame(
            data=[
                [labels[i], f"{indices[i][1]}, {indices[i][0]}"]
                for i in range(len(indices))
            ],
            columns=["Name", "Coordinates"],
        )
        grid_point_df.to_csv(prefix + ".csv", index=False)
    else:
        indices, labels = get_cached_grid_indices(grid_path)
        grid_point_df = pd.read_csv(prefix + ".csv")
    box = go.Scattermapbox(
        lat=indices[:, 1],
        lon=indices[:, 0],
        mode="markers+text",
        text=labels,
        marker=go.scattermapbox.Marker(size=6),
    )
    box.name = "Grids"
    box.textfont.update({"color": "White"})
    scattermaps.append(box)

    if show_mask:
        contours = shapefile_to_latlong(MASK_PATH)
        for contour in contours:
            lons = contour[:, 0]
            lats = contour[:, 1]
            scattermaps.append(
                go.Scattermapbox(
                    fill="toself",
                    lat=lats,
                    lon=lons,
                    mode="markers",
                    marker=go.scattermapbox.Marker(size=6),
                )
            )

    if show_hospitals:
        indices, labels = get_cached_grid_indices(HOSP_PATH)
        box = go.Scattermapbox(
            lat=indices[:, 1],
            lon=indices[:, 0],
            mode="markers+text",
            text=labels,
            marker=go.scattermapbox.Marker(size=10),
        )
        box.name = "Hospitals"
        box.textfont.update({"color": "White"})
        scattermaps.append(box)

    if show_police:
        indices, labels = get_cached_grid_indices(POLICE_PATH)
        box = go.Scattermapbox(
            lat=indices[:, 1],
            lon=indices[:, 0],
            mode="markers+text",
            text=labels,
            marker=go.scattermapbox.Marker(size=10),
        )
        box.name = "Police Stations"
        box.textfont.update({"color": "White"})
        scattermaps.append(box)

    fig = go.Figure(scattermaps)

    center = (7.753769, 80.691730)
    if region == "Ussangoda":
        center = (6.0994295, 80.9860763)
    elif region == "Indikolapelessa":
        center = (6.3602253, 80.9371957)
    elif region == "Ginigalpelessa":
        center = (6.3846744, 80.8868755)
    elif region == "Yudhaganawa":
        center = (7.665643, 80.9529867)
    elif region == "Seruwila":
        center = (8.335057, 81.320460)
    elif region == "Rupaha":
        center = (7.0401336625287, 80.89709495963253)
    modebar_icons = [
        "lasso",
        "select",
        "pan",
        "zoomin",
        "zoomout",
        "toImage",
        "resetview",
    ]
    if token:
        fig.update_layout(
            mapbox=dict(
                style="satellite-streets",
                accesstoken=token,
                center=go.layout.mapbox.Center(lat=center[0], lon=center[1]),
                pitch=0,
                zoom=6 if region == "None" else 13,
            ),
            mapbox_layers=[
                {
                    # "below": "traces",
                    "sourcetype": "raster",
                    "sourceattribution": "United States Geological Survey",
                    "source": [
                        "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
                    ],
                }
            ],
            modebar_remove=modebar_icons,
        )
    else:
        fig.update_layout(
            mapbox_style="open-street-map",
            hovermode="closest",
            mapbox=dict(
                bearing=0,
                center=go.layout.mapbox.Center(lat=center[0], lon=center[1]),
                pitch=0,
                zoom=6 if region == "None" else 13,
            ),
            modebar_remove=modebar_icons,
        )

    return fig, prefix + ".zip", prefix + ".csv", grid_point_df


with gr.Blocks() as demo:
    gr.Markdown("""# Serpentinite Sampling Grid Generator""")

    with gr.Tab("Sampling"):
        grid_side_len = gr.Textbox(value="100", label="Sampling Gap (m)")

        grid_show_hosp = gr.Checkbox(True, label="Show Hospitals")
        grid_show_police = gr.Checkbox(True, label="Show Police Stations")

        grid_button = gr.Button("Generate Grid")

        grid_map = gr.Plot(label="Plot")

        grid_region = gr.Radio(
            label="Zoom to Region",
            choices=[
                "None",
                "Ussangoda",
                "Indikolapelessa",
                "Ginigalpelessa",
                "Yudhaganawa",
                "Seruwila",
                "Rupaha",
            ],
        )
        grid_shapefile = gr.File(label="Grid Shapefile")
        grid_point_info = gr.File(label="Grid Point Info")

        grid_point_table = gr.Dataframe(label="Grid Point Info Table")

    grid_button.click(
        gr_generate_map,
        inputs=[grid_side_len],
        outputs=[grid_map, grid_shapefile, grid_point_info, grid_point_table],
    )

    grid_region.change(
        gr_generate_map,
        inputs=[
            grid_side_len,
            grid_show_hosp,
            grid_show_police,
            grid_region,
        ],
        outputs=[grid_map, grid_shapefile, grid_point_info, grid_point_table],
    )

demo.queue(concurrency_count=10).launch(debug=True)