-
Notifications
You must be signed in to change notification settings - Fork 0
/
som.Rmd
421 lines (334 loc) · 17.2 KB
/
som.Rmd
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
---
title: "Self-organising map (SOM) analysis"
author: "Robert Schlegel"
date: "2019-06-04"
output: workflowr::wflow_html
editor_options:
chunk_output_type: console
csl: FMars.csl
bibliography: MHWNWA.bib
---
```{r global_options, include = FALSE}
knitr::opts_chunk$set(fig.width = 8, fig.align = 'center',
echo = TRUE, warning = FALSE, message = FALSE,
eval = TRUE, tidy = FALSE)
```
## Introduction
This vignette contains the code used to perform the self-organising map (SOM) analysis on the mean synoptic states created in the [Variable preparation](https://robwschlegel.github.io/MHWNWA/var-prep.html) vignette. We'll start by creating custom packets that meet certain experimental criteria before then feeding them into a SOM. We will finish up by creating some cursory visuals of the results. The full summary of the results may be seen in the [Node summary vignette](https://robwschlegel.github.io/MHWNWA/node-summary.html).
```{r libraries}
# Insatll from GitHub
# .libPaths(c("~/R-packages", .libPaths()))
# devtools::install_github("fabrice-rossi/yasomi")
# Packages used in this vignette
library(jsonlite, lib.loc = "../R-packages/")
library(tidyverse) # Base suite of functions
library(ncdf4) # For opening and working with NetCDF files
library(lubridate) # For convenient date manipulation
# library(scales) # For scaling data before running SOM
library(yasomi, lib.loc = "../R-packages/") # The SOM package of choice due to PCI compliance
library(data.table) # For working with massive dataframes
# Set number of cores
doMC::registerDoMC(cores = 50)
# Disable scientific notation for numeric values
# I just find it annoying
options(scipen = 999)
# Set number of cores
doMC::registerDoMC(cores = 50)
# Disable scientific notation for numeric values
# I just find it annoying
options(scipen = 999)
# Individual regions
NWA_coords <- readRDS("data/NWA_coords_cabot.Rda")
# The NAPA variables
NAPA_vars <- readRDS("data/NAPA_vars.Rda")
# Corners of the study area
NWA_corners <- readRDS("data/NWA_corners.Rda")
# Create smaller corners to use less RAM
# This also better matches the previous South African work
# The Tasmania work had corners of roughly 2 degrees greater than the study area
# NWA_corners_sub <- c(NWA_corners[1]+8, NWA_corners[2]-8, NWA_corners[3]+8, NWA_corners[4]-8)
# The base map
map_base <- ggplot2::fortify(maps::map(fill = TRUE, col = "grey80", plot = FALSE)) %>%
dplyr::rename(lon = long) %>%
mutate(group = ifelse(lon > 180, group+9999, group),
lon = ifelse(lon > 180, lon-360, lon)) %>%
select(-region, -subregion)
# The grid that will convert the tri-polar coordinates to cartesian
# NB: This file was created in the 'tikoraluk' project
# load("data/lon_lat_NAPA_OISST.Rdata")
# Change to fit with this project
# lon_lat_NAPA_OISST <- lon_lat_NAPA_OISST %>%
# dplyr::select(-lon, -lat, -dist, -nav_lon_corrected) %>%
# dplyr::rename(lon = nav_lon, lat = nav_lat) %>%
# mutate(lon = round(lon, 4),
# lat = round(lat, 4)) %>%
# mutate(lon_O = ifelse(lon_O > 180, lon_O-360, lon_O))
```
## Tailored data packets
In this last stage before running our SOM analyses we will create data packets that can be fed directly into the SOM algorithm. These data packets will vary based on the exclusion of certain regions in the study area. In the first run of this analysis on the NAPA model data it was found that the inclusion of the Labrador Sea complicated the results quite a bit. It is also unclear whether or not the Gulf of St Lawrence region should be included in the analysis. While creating whatever packets we desire we will also be converting them into the super-wide matrix format that the SOM model desires.
### Unnest synoptic state packets
Up first we must simply load and unnest the synoptic state packets made previously.
```{r unnest-packets, eval=FALSE}
# Load the synoptic states data packet
system.time(
synoptic_states <- readRDS("data/synoptic_states.Rda")
) # 3 seconds
# Unnest the synoptic data
system.time(
synoptic_states_unnest <- synoptic_states %>%
select(region, event_no, synoptic) %>%
unnest()
) # 8 seconds
```
### Custom packets
With all of our data ready we may now trim them as we see fit before saving them for the SOM.
```{r create-SOM-packet, eval=FALSE}
# The study area size when the Labrador region is excluded
NWA_coords_nolab <- NWA_coords %>%
filter(region != "ls")
# The study area size when the Labrador and GSL regions are excluded
NWA_coords_nolabgsl <- NWA_coords %>%
filter(!region %in% c("ls", "gsl"))
# Test visuals of reduced study areas
synoptic_states[1,] %>%
unnest() %>%
filter(lat <= round(max(NWA_coords_nolabgsl$lat))+0.5) %>%
ggplot(aes(x = lon, y = lat)) +
geom_raster(aes(fill = sst_anom)) +
geom_polygon(data = NWA_coords_nolabgsl, aes(colour = region), fill = NA)
# Function for casting wide the custom packets
create_packet <- function(df){
# Cast the data to a single row
res <- data.table::data.table(df) %>%
reshape2::melt(id = c("region", "event_no", "lon", "lat"),
measure = c(colnames(.)[-c(1:4)]),
variable.name = "var", value.name = "val") %>%
dplyr::arrange(var, lon, lat) %>%
unite(coords, c(lon, lat, var), sep = "BBB") %>%
unite(event_ID, c(region, event_no), sep = "BBB") %>%
reshape2::dcast(event_ID ~ coords, value.var = "val")
# Remove columns (pixels) with missing data
res_fix <- res[,colSums(is.na(res))<1]
return(res_fix)
}
# Packet for entire study region
system.time(
packet_all <- create_packet(synoptic_states_unnest)
) # xxx seconds
saveRDS(packet_all, "data/packet_all.Rda")
# Exclude Labrador region
system.time(
packet_nolab <- synoptic_states_unnest %>%
filter(region != "ls",
lat <= round(max(NWA_coords_nolab$lat))+0.5) %>%
create_packet()
) # 128 seconds
saveRDS(packet_nolab, "data/packet_nolab.Rda")
# Exclude Labrador and Gulf of St Lawrence regions
system.time(
packet_nolabgsl <- synoptic_states_unnest %>%
filter(!region %in% c("ls", "gsl"),
lat <= round(max(NWA_coords_nolabgsl$lat))+0.5) %>%
create_packet()
) # xxx seconds
saveRDS(packet_nolabgsl, "data/packet_nolabgsl.Rda")
```
## Run SOM models
Now that we have our data packets to feed the SOM, we need a function that will ingest them and produce results for us.
```{r som-func}
# Function for calculating SOMs using PCI
# NB: 4x4 produced one empty cell and one cell with only one event
# So the default size has been reduced to 4x3
som_model_PCI <- function(data_packet, xdim = 4, ydim = 3){
# Create a scaled matrix for the SOM
# Cancel out first column as this is the reference ID of the event per row
data_packet_matrix <- as.matrix(scale(data_packet[,-1]))
# Create the grid that the SOM will use to determine the number of nodes
som_grid <- somgrid(xdim = xdim, ydim = ydim, topo = "hexagonal")
# Run the SOM with PCI
som_model <- batchsom(data_packet_matrix,
somgrid = som_grid,
init = "pca",
max.iter = 100)
return(som_model)
}
```
With the function sorted, we now feed the data.
```{r som-run, eval=FALSE}
# The SOM on the entire study area
# NB: Not running for some reason...
# Possibly due to a column with no range in values
# Not too worried about it as this one isn't being used
# packet_all <- readRDS("data/packet_all.Rda")
# system.time(som_all <- som_model_PCI(packet_all)) # 201 seconds
# saveRDS(som_all, file = "data/som_all.Rda")
# The SOM excluding the Labrador Sea region
packet_nolab <- readRDS("data/packet_nolab.Rda")
system.time(som_nolab <- som_model_PCI(packet_nolab)) # 78 seconds
saveRDS(som_nolab, file = "data/som_nolab.Rda")
# The SOM excluding the Labrador Sea and Gulf of St Lawrence regions
packet_nolabgsl <- readRDS("data/packet_nolabgsl.Rda")
system.time(som_nolabgsl <- som_model_PCI(packet_nolabgsl)) # 75 seconds
saveRDS(som_nolabgsl, file = "data/som_nolabgsl.Rda")
# A 9 node SOM
# A 16 node SOM
system.time(som_nolab <- som_model_PCI(packet_nolab)) # 78 seconds
saveRDS(som_nolab, file = "data/som_nolab.Rda")
# A SOM without moderate events
```
## Unpack SOM results
We will create two functions below that will be useful for unpacking the SOM results.
```{r som-unpack-func}
# Function for determining node indexes
# testers...
# data_packet <- all_anom; som_output <- som_all_anom
event_node_index <- function(data_packet, som_output){
# Count the number of events per node
node_count <- as.data.frame(table(som_output$classif)) %>%
dplyr::rename(node = Var1,
count = Freq) %>%
mutate(node = as.numeric(as.character(node)))
# Create a more complete data.frame of info
event_node <- data.frame(event_ID = data_packet[,"event_ID"],
node = som_output$classif) %>%
separate(event_ID, into = c("region", "event_no"), sep = "BBB") %>%
left_join(node_count, by = "node")
# NB: This is potentially where the season of the event would be inserted
return(event_node)
}
# Function for unpacking som results and creating
# mean results from initial data frame based on node clustering
# testers...
# data_packet <- packet_nolab; som_output <- som_nolab
som_unpack_mean <- function(data_packet, som_output){
# Determine which event goes in which node and melt
data_packet_long <- data.frame(event_ID = data_packet[,"event_ID"],
node = som_output$classif) %>%
separate(event_ID, into = c("region", "event_no"), sep = "BBB") %>%
cbind(data_packet[,-1]) %>%
data.table() %>%
reshape2::melt(id = c("region", "event_no", "node"),
measure = c(colnames(.)[-c(1:3)]),
variable.name = "variable", value.name = "value")
# Create the mean values that serve as the unscaled results from the SOM
var_unscaled <- data_packet_long[, .(val = mean(value, na.rm = TRUE)),
by = .(node, variable)] %>%
separate(variable, into = c("lon", "lat", "var"), sep = "BBB") %>%
dplyr::arrange(node, var, lon, lat) %>%
mutate(lon = as.numeric(lon),
lat = as.numeric(lat))
return(var_unscaled)
}
```
And now we unpack the SOM results.
```{r som-unpack, eval=TRUE}
# Load data packets
# packet_all <- readRDS("data/packet_all.Rda")
packet_nolab <- readRDS("data/packet_nolab.Rda")
packet_nolabgsl <- readRDS("data/packet_nolabgsl.Rda")
# Load SOM packets
# som_all <- readRDS("data/som_all.Rda")
som_nolab <- readRDS("data/som_nolab.Rda")
som_nolabgsl <- readRDS("data/som_nolabgsl.Rda")
# Determine node index
# node_index_all <- event_node_index(packet_all, som_all)
node_index_nolab <- event_node_index(packet_nolab, som_nolab)
node_index_nolabgsl <- event_node_index(packet_nolabgsl, som_nolabgsl)
## Create and save mean synoptic states per node
# All
# node_mean_all <- som_unpack_mean(packet_all, som_all)
# saveRDS(node_mean_all, "data/node_mean_all.Rda")
# No Labrador Sea
node_mean_nolab <- som_unpack_mean(packet_nolab, som_nolab)
# saveRDS(node_mean_nolab, "data/node_mean_nolab.Rda")
# No Labrador Sea or Gulf of St Lawrence
node_mean_nolabgsl <- som_unpack_mean(packet_nolabgsl, som_nolabgsl)
# saveRDS(node_mean_nolabgsl, "data/node_mean_nolabgsl.Rda")
```
## Visualise SOM results
First up the functions for visualising the unpacked results.
```{r som-visualise-func}
# Ease of life function
som_node_visualise <- function(sub_var = "sst_anom",
node_data = node_mean_nolab,
node_index = node_index_nolab){
# Subset data
node_data_sub <- node_data %>%
filter(var == sub_var)
# Create plot
som_panel_plot <- ggplot(node_data_sub, aes(x = lon, y = lat)) +
# geom_point(aes(colour = val)) +
geom_raster(aes(fill = val)) +
geom_polygon(data = map_base, aes(group = group), show.legend = F) +
geom_label(data = node_index, aes(x = -60, y = 35, label = paste0("n = ",count))) +
# geom_polygon(data = NWA_coords, aes(group = region, fill = region, colour = region), alpha = 0.1) +
coord_cartesian(xlim = c(max(node_data$lon), min(node_data$lon)),
ylim = c(max(node_data$lat), min(node_data$lat)),
expand = F) +
scale_fill_gradient2(low = "blue", high = "red") +
# scale_colour_viridis_c(option = viridis_option) +
labs(x = NULL, y = NULL, fill = sub_var) +
facet_wrap(~node, ncol = 4) +
theme(legend.position = "bottom")
return(som_panel_plot)
}
```
And now we create a PDF for each of the 12 nodes for each variable individually.
```{r som-visualise, eval=FALSE}
# SST
# NB: Comparing the SST anomaly results from the two restricted study areas
plot_sst_anom <- som_node_visualise()
plot_sst_anom_nogsl <- som_node_visualise(node_data = node_mean_nolabgsl,
node_index = node_index_nolabgsl)
# plot_sst_anom
# plot_sst_anom_nogsl
ggsave(plot_sst_anom, filename = "output/som_plot_sst_anom.pdf", height = 9, width = 13)
ggsave(plot_sst_anom, filename = "output/som_plot_sst_anom.png", height = 9, width = 13)
ggsave(plot_sst_anom_nogsl, filename = "output/som_plot_sst_anom_nogsl.pdf", height = 9, width = 13)
# Air temperature (t2m)
plot_t2m_anom <- som_node_visualise("t2m_anom")
# plot_t2m_anom
ggsave(plot_t2m_anom, filename = "output/som_plot_t2m_anom.pdf", height = 9, width = 13)
# Net downward heat flux (qnet)
plot_qnet_anom <- som_node_visualise("qnet_anom")
# plot_qnet_anom
ggsave(plot_qnet_anom, filename = "output/som_plot_qnet_anom.pdf", height = 9, width = 13)
# Surface wind U (u10)
plot_u10_anom <- som_node_visualise("u10_anom")
# plot_u10_anom
ggsave(plot_u10_anom, filename = "output/som_plot_u10_anom.pdf", height = 9, width = 13)
# Surface wind V (v10)
plot_v10_anom <- som_node_visualise("v10_anom")
# plot_v10_anom
ggsave(plot_v10_anom, filename = "output/som_plot_v10_anom.pdf", height = 9, width = 13)
# Ocean current U (u)
plot_u_anom <- som_node_visualise("u_anom")
# plot_uoce_anom
ggsave(plot_u_anom, filename = "output/som_plot_u_anom.pdf", height = 9, width = 13)
# Ocean current V (v)
plot_v_anom <- som_node_visualise("v_anom")
# plot_v_anom
ggsave(plot_v_anom, filename = "output/som_plot_v_anom.pdf", height = 9, width = 13)
# Mixed Layer Depth (mld)
plot_mld_anom <- som_node_visualise("mld_anom")
# plot_mld_anom
ggsave(plot_mld_anom, filename = "output/som_plot_mld_anom.pdf", height = 9, width = 13)
```
Juggling back and forth between the SST anomaly photos with and without the Gulf of St Lawrence it first appears that they are very different, but this is mostly due to the top and bottom rows of nodes being flipped. The actual differences are much more muted and the patterns tend to hold. The patterns appear more crisp in the larger study extent (no Labrador). This is likely because the inclusion of the shallow GSL gives more power. to the atmospheric variables to compete with the Gulf Stream. For this reason we are going to proceed with the inclusion of the Gulf of St Lawrence.
See the files in the `output/` folder in the GitHub repo for this project. They aren't all shown here because they take a bit too long to render. But the following shows what the SST anomaly nodes look like.
```{r plot-sst-anom}
plot_sst_anom <- som_node_visualise("sst_anom")
plot_sst_anom
```
Up next in the [Node summary vignette](https://robwschlegel.github.io/MHWNWA/node-summary.html) we will show the results in more depth. The code used to create the summary figures may be found in the [Figures vignette](https://robwschlegel.github.io/MHWNWA/node-summary.html).
## Musings
### Possible mechanisms
"Finally, Shearman and Lentz (2010) showed that century-long ocean warming trends observed along the entire northeast U.S. coast are not related to local atmospheric forcing but driven by atmospheric warming of source waters in the Labrador Sea and the Arctic, which are advected into the region." [@Richaud2016]
Downwelling
Net heatflux (OAFlux) doesn't line up perfectly with seasonal SST signal, but is very close, with heat flux tending to lead SST by 2 -- 3 months [@Richaud2016]. It is therefore likely one of the primary drivers of SST and should therefore be strongly considered when constructing SOMs.
There is almost no seasonal cycle for slope waters in any of the regions [@Richaud2016].
### More ideas
It would be interesting to see if the SOM outputs differ in any meaningful ways when only data from the first half of the study time period are used compared against the second half.
The output of the SOMs could likely be more meaningfully conveyed from the point of view of the regions. What I mean by this is to take the summary of the nodes, convey them into a table, and then use that table to inform a series of information bits that is focused around each region. Some sort of interactive visual may be useful for this. Showing the percentage that each region has in each node would be a good start. This would allow for a more meaningful further explanation for which drivers affect which regions during which seasons and over which years.
Once this summary is worked out it would then follow that the same analysis be run 1, 2, 3 etc. months in the past and see what the same information format provides w.r.t. a sort of predictive capacity. All of this can then be used to check other data products with a more focused lens in order to maximise the utility of the output.
## References