File size: 6,977 Bytes
ed27e2b
c2a1e5b
abb3582
e0df861
b15dfab
 
 
abb3582
 
e0df861
abb3582
e0df861
abb3582
b15dfab
c2a1e5b
e0df861
 
 
 
 
98b6564
1367bbc
 
c2a1e5b
92a8f8c
b761c8c
98b6564
e6fc859
e0df861
 
 
 
e6fc859
98b6564
 
e0df861
 
 
 
 
 
 
 
 
 
98b6564
179db2b
 
 
 
98b6564
 
 
 
 
 
92a8f8c
 
 
98b6564
2b73487
92a8f8c
b15dfab
92a8f8c
 
b15dfab
 
92a8f8c
 
 
b15dfab
 
92a8f8c
 
 
b15dfab
 
92a8f8c
e6fc859
 
e0df861
e6fc859
2b73487
1367bbc
98b6564
 
0dde66d
98b6564
 
c91fb35
 
 
 
 
2b73487
92a8f8c
98b6564
2b73487
 
92a8f8c
abb3582
 
 
2b73487
e0df861
 
 
 
ed27e2b
92a8f8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abb3582
 
1367bbc
c2a1e5b
e0df861
 
 
 
 
 
 
 
 
 
0dde66d
abb3582
c2a1e5b
b15dfab
2b73487
 
60f152e
2b73487
92a8f8c
 
2b73487
e0df861
 
 
 
 
 
b15dfab
e0df861
 
 
2b73487
abb3582
e0df861
179db2b
e0df861
 
 
 
 
abb3582
e0df861
abb3582
e0df861
 
60f152e
 
 
 
 
179db2b
 
 
e0df861
0dde66d
2b73487
 
abb3582
 
2b73487
1367bbc
abb3582
1367bbc
 
 
 
 
92a8f8c
1367bbc
 
 
 
 
 
 
 
 
 
2b73487
1367bbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92a8f8c
1367bbc
abb3582
1367bbc
0dde66d
1367bbc
 
 
0dde66d
1367bbc
 
2b73487
 
1367bbc
 
ed27e2b
 
 
1367bbc
 
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
library(shiny)
library(bslib)
library(htmltools)
#library(markdown)
library(fontawesome)
library(bsicons)
library(gt)
library(glue)
library(ggplot2)
library(readr)
library(dplyr)
library(mapgl)
library(duckdbfs)
duckdbfs::load_spatial()

css <-
  HTML(paste0("<link rel='stylesheet' type='text/css' ",
              "href='https://demos.creative-tim.com/",
              "material-dashboard/assets/css/",
              "material-dashboard.min.css?v=3.2.0'>"))


# Define the UI
ui <- page_sidebar(
  fillable = FALSE, # do not squeeze to vertical screen space
  tags$head(css),
  titlePanel("Demo App"),

  "
  This is a proof-of-principle for a simple chat-driven interface
  to dynamically explore geospatial data.
  ",

  card(
    layout_columns(
      textInput("chat",
        label = NULL,
        "Which counties in California have the highest average social vulnerability?",
        width = "100%"),
      div(
      actionButton("user_msg", "", icon = icon("paper-plane"),
                   class = "btn-primary btn-sm align-bottom"),
      class = "align-text-bottom"),
      col_widths = c(11, 1)),
      fill = FALSE
  ),

  textOutput("agent"),


  layout_columns(
    card(maplibreOutput("map")),
    card(includeMarkdown("## Plot"),
         plotOutput("chart1"),
         plotOutput("chart2"),
         ),
    col_widths = c(8, 4),
    row_heights = c("600px"),
    max_height = "700px"
  ),

  gt_output("table"),

  card(fill = TRUE,
    card_header(fa("robot")),
    accordion(
      open = FALSE,
      accordion_panel(
        title = "show sql",
        icon = fa("terminal"),
        verbatimTextOutput("sql_code"),
      ),
      accordion_panel(
        title = "explain",
        icon = fa("user", prefer_type="solid"),
        textOutput("explanation"),
      )
    ),
    card(
      card_header("Errata"),
      shiny::markdown(readr::read_file("footer.md")),
    )
  ),

  sidebar = sidebar(
    input_switch("redlines", "Redlined Areas", value = FALSE),
    input_switch("svi", "Social Vulnerability", value = TRUE),
    input_switch("richness", "Biodiversity Richness", value = FALSE),
    input_switch("rsr", "Biodiversity Range Size Rarity", value = FALSE),

    card(
      card_header(bs_icon("github"), "Source code:"),
      a(href = "https://github.com/boettiger-lab/geo-llm-r",
        "https://github.com/boettiger-lab/geo-llm-r"))
  ),

  theme = bs_theme(version = "5")
)


repo <- "https://data.source.coop/cboettig/social-vulnerability"
pmtiles <- glue("{repo}/svi2020_us_tract.pmtiles")
parquet <- glue("{repo}/svi2020_us_tract.parquet")
con <- duckdbfs::cached_connection()
svi <- open_dataset(parquet, tblname = "svi") |> filter(RPL_THEMES > 0)
schema <- read_file("schema.yml")
system_prompt <- glue::glue(readr::read_file("system-prompt.md"),
                            .open = "<", .close = ">")

chat <- ellmer::chat_vllm(
  base_url = "https://llm.nrp-nautilus.io/",
  model = "llama3",
  api_key = Sys.getenv("NRP_API_KEY"),
  system_prompt = system_prompt,
  api_args = list(temperature = 0)
)

# helper utilities
# faster/more scalable to pass maplibre the ids to refilter pmtiles,
# than to pass it the full geospatial/sf object
filter_column <- function(full_data, filtered_data, id_col = "FIPS") {
  if (nrow(filtered_data) < 1) return(NULL)
  values <- full_data |>
    inner_join(filtered_data, copy = TRUE) |>
    pull(id_col)
  # maplibre syntax for the filter of PMTiles  
  list("in", list("get", id_col), list("literal", values))
}



# Define the server
server <- function(input, output, session) {

  chart1_data <- svi |>
    group_by(COUNTY) |>
    summarise(mean_svi = mean(RPL_THEMES)) |>
    collect()

  chart1 <- chart1_data |>
    ggplot(aes(mean_svi)) + geom_density(fill="darkred") +
    ggtitle("County-level vulnerability nation-wide")

  data <- reactiveValues(df = tibble())
  output$chart1 <- renderPlot(chart1)

  observeEvent(input$user_msg, {
    stream <- chat$chat(input$chat)



    # Parse response
    response <- jsonlite::fromJSON(stream)

    if ("query" %in% names(response)) {
      output$sql_code <- renderText(stringr::str_wrap(response$query, width = 60))
      output$explanation <- renderText(response$explanation)

      # Actually execute the SQL query generated:
      df <- DBI::dbGetQuery(con, response$query)

      # don't display shape column in render
      df <- df |> select(-any_of("Shape"))
      output$table <- render_gt(df, height = 300)


      y_axis <- colnames(df)[!colnames(df) %in% colnames(svi)]
      chart2 <- df |>
        rename(social_vulnerability = y_axis) |>
        ggplot(aes(social_vulnerability)) +
        geom_density(fill = "darkred")  +
        xlim(c(0, 1)) +
        ggtitle("Vulnerability of selected areas")

      output$chart2 <- renderPlot(chart2)

      # We need to somehow trigger this df to update the map.
      data$df <- df

    # Note: ellmer will preserve full chat history automatically.
    # this can confuse the agent and mess up behavior, so we reset:
    chat$set_turns(NULL)

    } else {
      output$agent <- renderText(response$agent)

    }

  })



  output$map <- renderMaplibre({

    m <- maplibre(center = c(-92.9, 41.3), zoom = 3, height = "400")
    if (input$redlines) {
      m <- m |>
        add_fill_layer(
          id = "redlines",
          source = list(type = "vector",
                        url = paste0("pmtiles://", "https://data.source.coop/cboettig/us-boundaries/mappinginequality.pmtiles")),
          source_layer = "mappinginequality",
          fill_color = list("get", "fill")
        )
    }
    if (input$richness) {
      m <- m |>
        add_raster_source(id = "richness",
                          tiles = "https://data.source.coop/cboettig/mobi/tiles/red/species-richness-all/{z}/{x}/{y}.png",
                          maxzoom = 11
                          ) |>
        add_raster_layer(id = "richness-layer",
                         source = "richness")

    }

     if (input$rsr) {
      m <- m |>
        add_raster_source(id = "rsr",
                          tiles = "https://data.source.coop/cboettig/mobi/tiles/green/range-size-rarity-all/{z}/{x}/{y}.png",
                          maxzoom = 11
                          ) |>
        add_raster_layer(id = "richness-layer",
                         source = "rsr")

    }
    if (input$svi) {
      m <- m |>
        add_fill_layer(
          id = "svi_layer",
          source = list(type = "vector",
                        url = paste0("pmtiles://", pmtiles)),
          source_layer = "SVI2000_US_tract",
          filter = filter_column(svi, data$df, "FIPS"),
          fill_opacity = 0.5,
          fill_color = interpolate(column = "RPL_THEMES",
                                  values = c(0, 1),
                                  stops = c("lightpink", "darkred"),
                                  na_color = "lightgrey")
        )
    }
  m})



}

# Run the app
shinyApp(ui = ui, server = server)