-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRainMakerChallengeNotebook.jl
1964 lines (1616 loc) · 66.7 KB
/
RainMakerChallengeNotebook.jl
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### A Pluto.jl notebook ###
# v0.20.4
using Markdown
using InteractiveUtils
# ╔═╡ 97a4183e-f670-47b6-a318-4254f34cac32
begin
using JLSO
using Flux
using Distributions
using PlutoPlotly
using BenchmarkTools
using DataFrames
end
# ╔═╡ a9c6cecd-0013-42b5-b7cc-0362bdb4a663
md"""
# Introduction
"""
# ╔═╡ 7e34c342-91dd-4c15-8a4c-0d6a61093371
md"""
# Loading Packages
- `JLSO` will be used to deserialise data to train the surrogate
- `Flux` is a ML library that will let us train the network and do the downstream task
- `Distributions` give us functionality to create nice initializations for our model
- `PlutoPlotly` for beautiful plots to visualize and debug our surrogate's performance
- `BenchmarkTools` to benchmark the speed of the surrogate and simulation
- `DataFrames` used to conveniently organise data for the parallel coordinate plot
"""
# ╔═╡ 62dba600-c90b-11ef-009f-07f05e9e18cc
md"""
# Loading Data
Data was generated using RainMaker.jl and SpeedyWeather.jl. The procedure can be summarised as follows:
1. Specify upper and lower bounds, including number of samples
2. Use a Quasi Monte Carlo scheme such as `LatinHypercubeSample` to sample this space
3. Simulate each sample in parallel and return a tuple that is (params,output)
4. Serialise the data for safe keeping (optional)
The code used has been provided as markdown for convenience but for this workshop, we are going to be using a dataset already generated in the interest of time.
```julia
using Distributed
addprocs(64)
using QuasiMonteCarlo
@everywhere using RainMaker
@everywhere using SpeedyWeather
include("utils.jl") #where max_precipitation lives
@everywhere const PARAMETER_KEYS = (
:orography_scale, # [1], default: 1, scale of global orography
:mountain_height, # [m], default: 0, height of an additional azores mountain
:mountain_size, # [˚], default: 1, horizontal size of an additional azores mountain
:mountain_lon, # [˚E], default: -27.25, longitude of an additional azores mountain
:mountain_lat, # [˚N], default: 38.7, latitude of an additional azores mountain
:temperature_equator, # [K], default: 300, sea surface temperature at the equator
:temperature_pole, # [K], default: 273, sea surfaec temperature at the poles
:temperature_atlantic, # [K], default: 0, sea surface temperature anomaly in the atlantic
:temperature_azores, # [K], default: 0, sea surface temperature anomaly at the azores
:zonal_wind, # [m/s], default: 35, zonal wind speed
)
n = 10000
lb = [0, -2000, 0, -180, -90, 270, 270, -5, -5, 5]
ub = [2, 5000, 30, 180, 90, 300, 300, 5, 5, 50]
s = QuasiMonteCarlo.sample(n, lb, ub, LatinHypercubeSample())
sols = pmap(eachcol(s)) do sample
# Attempt the simulation
sol = try
max_precipitation(sample)
catch e
# If there's an error, store a fallback (e.g., NaN),
# or do some logging if you wish:
@warn "Error in max_precipitation($sample): $e"
NaN
end
return (sample, sol)
end
sampled_params = reduce(hcat,first.(sols))
sampled_outputs = last.(sols)
#save the data
using JLSO
JLSO.save("10kdata.jlso", Dict(:d=>(inputs = sampled_params, outputs = sampled_outputs)))
```
"""
# ╔═╡ a26dfb20-2644-4657-b5b5-864a32ac3053
begin
data = JLSO.load("10kdata.jlso")[:d]
input_data = data.inputs
output_data = reshape(data.outputs, (1,:))
nothing
end
# ╔═╡ af87db2b-31af-4aa9-b1a9-9d335bcde0e8
md"""
## Let's explore the 10k dataset
"""
# ╔═╡ 0c685bdf-edaf-4116-8f05-7e11383e3200
begin
hist_plot = histogram(
x = vec(output_data),
name = "Distribution"
)
hist_layout = Layout(
title = attr(
text = "Total Precipitation - 10k LHC",
x = 0.5, # Moves the title to the horizontal center
xanchor = "center"
),
xaxis = attr(title = "(mm)")
)
plot(hist_plot, hist_layout)
end
# ╔═╡ 08523ab9-5c66-4ceb-9c12-96ad1e5e9c01
extrema(output_data)
# ╔═╡ c13793fa-30ea-43e7-a416-7651877c140b
mean(output_data)
# ╔═╡ f1ee0a37-cae6-4223-a5b0-aea809fca768
var(output_data)
# ╔═╡ e57ee8db-fa0f-422f-8c0a-7ee612cc732a
md"""
## Discussion points:
- Data appears to have a lot of variability according to the mean and variance
- Histogram shows we have a heavy tail indicating we have behaviours that are under represented
- Strong indications already that this dataset won't be the final one before we have a full fledged surrogate.
"""
# ╔═╡ 106e4cd3-e376-4c5b-b0eb-90952d79c760
md"""
# Preparing Data for Surrogate Training
1. Normalize inputs and outputs to be between 0 and 1
2. Split the data into `train` and `validation`
3. Package data to be in batches and place on the gpu
"""
# ╔═╡ b5b681a6-f020-41c3-a690-51a9f730515b
md"""
# Initialise `surrogate` Model
Choose Neural Network architecture (we defer to a simple Resnet for now) and specify hyperparameters (activation functions, hidden sizes etc..)
![Simple Resnet] (https://upload.wikimedia.org/wikipedia/commons/b/ba/ResBlock.png)
"""
# ╔═╡ 31e025b7-8b08-4adb-bc55-c4ebd72a931b
md"""
# Configure Training Hyperparameters
1. Use a basic schedule to decay learning rate over time
2. Decide on epochs per learning rate decrement
3. Choose the optimiser
4. track parameters for L2 regularization
"""
# ╔═╡ 22dad96e-c4c8-4ff8-a4d7-f83accb02b72
md"""
# Train the model!
1. Run the model through the loop
2. Sprinkle some standard logging (we look at the normalised training loss and the denormalised - original scale - validation loss)
"""
# ╔═╡ 70bfa951-27b3-4688-83c2-dd5be03ff244
xvals = collect(0:100:100*500)[1:end-1]
# ╔═╡ 607321b9-fd3f-41bf-91d0-2e7d099afc6c
md"""
### Parallel Coordinate Plot for Training Data
"""
# ╔═╡ df9b4742-f68e-4ff3-b501-ecbe3199d300
md"""
### Parallel Coordinate Plot for Valdation Data
"""
# ╔═╡ ca4456ab-dc1c-402c-98e1-07b7665bf86d
md"""
## Discussion Points
This particular part of the surrogate training shows how you can diagnose how well the model performs. Each line goes through a number for each parameter representing a sample. The end of the line is the mae for its prediction, and you can interact with the plot by dragging over the axis to select samples. Using this plot, one can then perform active learning to generate more samples by examining where the model is performing poorly. We didn't train the model for that long so it's performance isn't very good. However, another model was trained in advanced that used a hidden size of 128, and trained for much longer which is provided in case compute isn't available for those trying this notebook and can't train something like that. As can be seen in it's parallel coordinate plots, we do much better on training and validation.
"""
# ╔═╡ 10e14cb4-ab21-4eda-b106-bc785c4ea859
pretrained_model = JLSO.load("128h-10k-2L-resnet.jlso")[:d]
# ╔═╡ 8b7d5e71-d10b-493e-addf-6df24971e385
md"""
### Parallel Coordinate Plot for Training Data: Pretrained
"""
# ╔═╡ 60770e3b-83a4-4a8a-a631-b92b0e0242d7
md"""
### Parallel Coordinate Plot for Validation Data: Pretrained
"""
# ╔═╡ 7c27f6c2-4869-4cee-9f49-b8530dde3c6f
md"""
# Downstream Optimization
Key idea here is to demonstrate the power of having a surrogate that is incredibly fast, is fully differentiable, and is batchable . Therefore we can do the following:
1. Randomly sample a series of parameters from the parameter space as starting points
2. Specify the objective of finding the parameters that result in the most total precipitation, and that the parameters stay in the bounds the network was trained on
3. Perform gradient descent to update the input parameters into the network that minimize this objective.
4. Choose from the sampled parameters that gave the largest output
5. Simulate it with the simulator to verify!
"""
# ╔═╡ f0441313-65d5-4a75-8499-2f17db7668a7
function input_objective(surr, X; λ=100.0)
y_pred = surr(X)
obj = -sum(y_pred) #since we have to minimize the objective, the -sum will work here
# Heavy differentiable penalty if X < 0 or X > 1
lower_violation = @. max(0.0f0, -X)
upper_violation = @. max(0.0f0, X - 1.0f0)
penalty = sum(lower_violation.^2) + sum(upper_violation.^2)
return obj + λ * penalty
end
# ╔═╡ 796e1216-fc68-41f0-b47b-1d638dff6bf4
begin
X_candidate = rand(10,5)
total_steps = 10000
opt_in = Flux.Adam(1e-4)
local st_opt = Flux.setup(opt_in, X_candidate)
for step in 1:total_steps
gs = gradient(X_candidate) do guesses
input_objective(pretrained_model,guesses)
end
st_opt, X_candidate = Optimisers.update(st_opt, X_candidate, gs...)
# Print progress occasionally
if step % 200 == 0
@info "Step $step, objective() = $(input_objective(pretrained_model,X_candidate))"
end
end
end
# ╔═╡ 199c8bf6-4ef7-43ee-8a44-d168dbf94304
md"""
### Verify!
```julia
julia> max_precipitation(best_param_sample)
[ Info: RainGauge{Float32, AnvilInterpolator{Float32, OctahedralGaussianGrid}} callback added with key callback_xVEB
Weather is speedy: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████| Time: 0:00:04 (961.28 years/day)
229.42801f0
```
"""
# ╔═╡ 1f154133-62d4-47f6-8232-b5a35f927378
md"""
# Benchmarking Single Simulation vs `surrogate`
```julia
julia> @benchmark max_precipitation(best_inputs_orig)
BenchmarkTools.Trial: 2 samples with 1 evaluation.
Range (min … max): 4.982 s … 4.990 s ┊ GC (min … max): 0.93% … 1.52%
Time (median): 4.986 s ┊ GC (median): 1.23%
Time (mean ± σ): 4.986 s ± 5.726 ms ┊ GC (mean ± σ): 1.23% ± 0.42%
█ █
█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█ ▁
4.98 s Histogram: frequency by time 4.99 s <
Memory estimate: 806.23 MiB, allocs estimate: 8323135.
julia> @benchmark surrogate(best_inputs_norm[:,1:1])
BenchmarkTools.Trial: 10000 samples with 1 evaluation.
Range (min … max): 19.671 μs … 447.771 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 24.760 μs ┊ GC (median): 0.00%
Time (mean ± σ): 25.069 μs ± 8.258 μs ┊ GC (mean ± σ): 0.00% ± 0.00%
▄▇█▄▂
▁▁▁▁▁▁▁▁▁▁▁▁▁▂▄▅▄▃▂▂▁▁▁▁▁▂▄▇█████▇▇▆▄▃▃▃▃▃▃▂▂▂▂▂▁▁▁▁▁▁▁▁▁▁▁▁ ▂
19.7 μs Histogram: frequency by time 29.6 μs <
Memory estimate: 7.69 KiB, allocs estimate: 12.
```
With speedups like this you could probably sample 1000s or 10s of 1000s of parameters during the downstream optimization unlocking some serious throughput for the procedure
"""
# ╔═╡ cae4b323-475f-44f4-8586-d3b41e1ae8b1
md"""
## Discussion points
With speedups like this you could probably sample 1000s or 10s of 1000s of parameters during the downstream optimization with half decent hardware unlocking some serious throughput for the procedure
"""
# ╔═╡ 29dd72ce-1145-436d-892c-c3b5d8693d69
md"""
Congratulations, you've gone through your first pass of generating and validating a surrogate! This is only the beginning of the journey, so many things to try to bring the surrogate's performance on the validation up to par with it's performance on training.
Things to try:
1. Sample much more data. This is the easiest and usually the first thing to try (think 100k - 1million samples)
2. Change the architecture. Add more layers, use different activation functions, play with regularisation
3. Sample data adaptively using active learning
Feel free to try non-deep learning methods as well
- XGBoost.jl
- MLJ.jl
- LIBSVM.jl
"""
# ╔═╡ 5b4c9729-aafe-4231-9429-a11ada56baf1
md"""
# Convenience Functions
"""
# ╔═╡ 18aeca69-12d4-4414-932e-f87ba42f79a6
normalise(x,min,max) = @. (x-min) / (max-min)
# ╔═╡ 77e3c694-1731-4e14-98e8-b09cfbaa9f94
begin
# Normalise inputs (parameters), take bounds from earlier
inputs_lb = [0, -2000, 0, -180, -90, 270, 270, -5, -5, 5]
inputs_ub = [2, 5000, 30, 180, 90, 300, 300, 5, 5, 50]
input_data_norm = normalise(input_data, inputs_lb, inputs_ub)
nothing
end
# ╔═╡ 2c0b78e5-817f-4eea-b0e1-41d5cfcc8cc3
extrema(input_data_norm,dims=2) #show input data is in between 0 and 1
# ╔═╡ f52bba40-fd7d-4646-82d3-cc6420219916
begin
# Normalise outputs
outputs_lb, outputs_ub = extrema(output_data)
output_data_norm = normalise(output_data, outputs_lb, outputs_ub)
nothing
end
# ╔═╡ 73ae3f0f-7bbf-44d5-8522-acce0c9afc3a
extrema(output_data_norm,dims=2) #show output data is in between 0 and 1
# ╔═╡ 67b71def-156a-4ed3-85d3-e7bfd47ffc39
begin
# Split data, train on 9000 validate on 1000
tsplit = 9000
input_data_norm_train = input_data_norm[:, 1:tsplit]
input_data_norm_valid = input_data_norm[:, tsplit+1:end]
output_data_norm_train = output_data_norm[:, 1:tsplit]
output_data_norm_valid = output_data_norm[:, tsplit+1:end]
nothing
end
# ╔═╡ d562d616-2b98-43fe-b3a3-845177ac3298
begin
#Loading data into dataloader so we can train on batches at a time
bs = 512*4
dataloader = Flux.DataLoader(
(input_data = input_data_norm_train,
output_data = output_data_norm_train);
batchsize = bs
)
end
# ╔═╡ 38b07258-616b-4ba8-8c2f-dcc2f100a9c5
denormalise(x,min,max) = @. x * (max-min) + min
# ╔═╡ db449505-6d40-4f3b-a9ce-f76ea2a49c06
begin
#After we optimise the parameters, pick the greatest predicted output
idx = argmax(pretrained_model(X_candidate))
best_param_sample = denormalise(X_candidate, inputs_lb, inputs_ub)[:,idx[2]]
inputs_lb .< best_param_sample .< inputs_ub
end
# ╔═╡ f0c3290f-4533-4070-beee-eabfc8abfff8
best_param_sample
# ╔═╡ 9fb68279-d110-4cf6-ac9f-d68972371b4b
begin
# If you want to see the predicted output for these solutions:
pred_vals = denormalise(pretrained_model(X_candidate), outputs_lb, outputs_ub)[idx]
end
# ╔═╡ 1cb8c920-4271-4625-abce-76f9baf8be0d
function NNLayer(in_size, out_size, act = identity; bias = false)
d = Uniform(-1.0 / sqrt(in_size), 1.0 / sqrt(in_size))
Dense(in_size, out_size, init = (x,y)->rand(d,x,y), act, bias = bias)
end
# ╔═╡ 4605e496-70f9-4e71-8eba-3db00e434145
begin
act = gelu
HSIZE = 64
INSIZE = length(inputs_lb)
OUTSIZE = length(outputs_lb)
surrogate = Chain(
NNLayer(INSIZE, HSIZE, act),
SkipConnection(Chain(NNLayer(HSIZE, HSIZE, act),
NNLayer(HSIZE, HSIZE, act)), +),
SkipConnection(Chain(NNLayer(HSIZE, HSIZE, act),
NNLayer(HSIZE, HSIZE, act)), +),
NNLayer(HSIZE, OUTSIZE)
)
end
# ╔═╡ 17524f16-3397-4bad-9293-be5a935e73f9
begin
opt = OptimiserChain(Adam())
lrs = [1e-3, 5e-4, 3e-4, 1e-4, 5e-5]
epochs = [100 for i in 1:length(lrs)]
st = Optimisers.setup(opt, surrogate)
ps = Flux.params(surrogate) # to use for L2 reg
lambda_reg = 1e-4
end
# ╔═╡ fc8172cc-9e66-430a-98d0-a4baa37a4c61
begin
loss_t = []
loss_v = []
# Training Loop
for (e, lr) in zip(epochs, lrs)
for epoch in 1:e
Optimisers.adjust!(st, lr)
for batch in dataloader
x, y = batch.input_data, batch.output_data
gs = gradient(surrogate) do model
Flux.mae(model(x), y) + lambda_reg * sum(x_ -> sum(abs2, x_), ps) #l2 reg
end
st, surrogate = Optimisers.update(st, surrogate, gs...)
end
if epoch % 100 == 0
surrogate_cpu = surrogate
l_t = Flux.mae(surrogate_cpu(input_data_norm_train), output_data_norm_train)
surr_v_pred = denormalise(surrogate_cpu(input_data_norm_valid), outputs_lb, outputs_ub)
gt_v = denormalise(output_data_norm_valid, outputs_lb, outputs_ub)
l_v = Flux.mae(surr_v_pred, gt_v)
push!(loss_t,l_t)
push!(loss_v,l_v)
@info "Epoch $epoch lr:$lr Training Loss: $l_t Validation Loss:$l_v"
end
end
end
end
# ╔═╡ a2232f58-e65c-4953-a94d-c37d4a27680a
p1 = plot(
scatter(
x = xvals,
y = loss_t,
name = "Training Loss"
),
Layout(
title = "Normalized MAE Loss"
)
)
# ╔═╡ aaf90e64-3748-4302-a75d-00f8c0a8f067
p2 = plot(
scatter(
x = xvals,
y = loss_v,
name = "Validation Loss"
),
Layout(
title = "Denormalized MAE Loss",
xaxis = attr(title = "Epochs")
)
)
# ╔═╡ 6fdcaeeb-dc4f-4127-86e1-e54ad2141615
"""
parallel_coords_plot(params, preds, actual; short_param_labels, colorscale)
Construct a parallel coordinates plot (using PlotlyJS) for `params` (p×N),
`preds` (1×N), and `actual` (1×N). Colors each line by its MAE value.
Parameters
----------
- `params::AbstractMatrix`: A p×N matrix whose columns represent examples.
- `preds::AbstractMatrix`: A 1×N matrix of model predictions (or shape-compatible vector).
- `actual::AbstractMatrix`: A 1×N matrix of ground‐truth values (or shape-compatible vector).
- `short_param_labels::Vector{String}` (optional): Labels for the `p` parameters
(default: ["param1", "param2", ..., "paramp"]).
- `colorscale`: Plotly colorscale for the lines (default: `[(0,"blue"), (1,"red")]`).
Returns
-------
A PlotlyJS.Plot object, which you can display or save via `PlotlyJS.savefig`.
"""
function parallel_coords_plot(params::AbstractMatrix,
preds::AbstractMatrix,
actual::AbstractMatrix;
short_param_labels::Vector{String} = String[],
colorscale = [(0.0, "blue"), (1.0, "red")])
# 1) Basic checks
p, N = size(params)
@assert size(preds, 2) == N "preds must have the same number of columns as params"
@assert size(actual, 2) == N "actual must have the same number of columns as params"
@assert size(preds, 1) == 1 "preds should be (1×N) or reshape your data"
@assert size(actual, 1) == 1 "actual should be (1×N) or reshape your data"
# If user didn't supply custom labels, create default: "param1", "param2", ...
if isempty(short_param_labels)
short_param_labels = ["param$(i)" for i in 1:p]
else
@assert length(short_param_labels) == p "short_param_labels must match p (# of rows in params)"
end
# 2) Compute MAE for each column
# mae_data is a length‐N vector of per‐example MAEs
mae_data = Float64[]
for j in 1:N
push!(mae_data, Flux.mae(preds[:, j], actual[:, j]))
end
# 3) Build a DataFrame of all parameters + mae
df = DataFrame()
for i in 1:p
df[!, Symbol("param$(i)")] = params[i, :] # columns "param1".."paramN"
end
df[!, :MAE] = mae_data
# 4) Construct the "dimensions" array for parcoords
dimensions_list = Any[]
# a) Each param dimension
for i in 1:p
param_range = (minimum(df[!, i]), maximum(df[!, i]))
push!(dimensions_list,
attr(
range = param_range,
label = short_param_labels[i],
values = df[!, i]
)
)
end
# b) The final dimension: MAE
mae_range = (minimum(mae_data), maximum(mae_data))
push!(dimensions_list,
attr(
range = mae_range,
label = "MAE",
values = df[!, :MAE]
)
)
# 5) Create the parallel coordinates trace
mytrace = parcoords(
line = attr(
color = df[!, :MAE],
colorscale = colorscale
),
dimensions = dimensions_list
)
myplot = plot(mytrace)
return myplot
end
# ╔═╡ 29142a15-5acd-41d0-a273-2437ff805f59
begin
params_train = denormalise(input_data_norm_train, inputs_lb, inputs_ub) # shape (p, N)
preds_train = denormalise(surrogate(input_data_norm_train), outputs_lb, outputs_ub) # shape (1, N)
actual_train = output_data[:, 1:9000] # shape (1, N) grab first 9000
labels = ["OroScale", "MtHeight", "MtSize", "MtLon", "MtLat",
"TempEqu", "TempPol", "TempAtl","TempAzo","ZWind"]
parallel_coords_plot(params_train, preds_train, actual_train; short_param_labels=labels)
end
# ╔═╡ 0f0a8b66-e312-4f7a-92fd-a1edcf3f343c
begin
params_valid = denormalise(input_data_norm_valid, inputs_lb, inputs_ub) # shape (p, N)
preds_valid = denormalise(surrogate(input_data_norm_valid), outputs_lb, outputs_ub) # shape (1, N)
actual_valid = output_data[:, 9000+1:end] # shape (1, N) grab first 9000
parallel_coords_plot(params_valid, preds_valid, actual_valid; short_param_labels=labels)
end
# ╔═╡ edc5ea7a-207b-471d-a835-dc6f6db8a63f
begin
pretrained_preds_train = denormalise(pretrained_model(input_data_norm_train), outputs_lb, outputs_ub)
parallel_coords_plot(params_train, pretrained_preds_train, actual_train; short_param_labels=labels)
end
# ╔═╡ 39f1fe53-43a1-4e18-b081-654c1c3a3508
begin
pretrained_preds_valid = denormalise(pretrained_model(input_data_norm_valid), outputs_lb, outputs_ub)
parallel_coords_plot(params_valid, pretrained_preds_valid, actual_valid; short_param_labels=labels)
end
# ╔═╡ e07a3f26-7da0-4dfa-bac3-85a156398e51
function max_precipitation(parameters::AbstractVector)
parameter_tuple = NamedTuple{PARAMETER_KEYS}(parameters)
return max_precipitation(parameter_tuple)
end
# ╔═╡ b91ea1a7-b1fa-4988-b8d2-97e9b4b978f9
function max_precipitation(parameters::NamedTuple)
# define resolution. Use trunc=42, 63, 85, 127, ... for higher resolution, cubically slower
spectral_grid = SpectralGrid(trunc=31, nlayers=8)
# Define AquaPlanet ocean, for idealised sea surface temperatures
# but don't change land-sea mask = retain real ocean basins
ocean = AquaPlanet(spectral_grid,
temp_equator=parameters.temperature_equator,
temp_poles=parameters.temperature_pole)
initial_conditions = InitialConditions(
vordiv = ZonalWind(u₀=parameters.zonal_wind),
temp = JablonowskiTemperature(u₀=parameters.zonal_wind),
pres = PressureOnOrography(),
humid = ConstantRelativeHumidity())
orography = EarthOrography(spectral_grid, scale=parameters.orography_scale)
# construct model
model = PrimitiveWetModel(spectral_grid; ocean, initial_conditions, orography)
# Add rain gauge, locate on Terceira Island
rain_gauge = RainGauge(spectral_grid, lond=-27.25, latd=38.7)
add!(model, rain_gauge)
# Initialize
simulation = initialize!(model, time=DateTime(2025, 1, 10))
# Add additional mountain
H = parameters.mountain_height
λ₀, φ₀, σ = parameters.mountain_lon, parameters.mountain_lat, parameters.mountain_size
set!(model, orography=(λ,φ) -> H*exp(-spherical_distance((λ,φ), (λ₀,φ₀), radius=360/2π)^2/2σ^2), add=true)
# set sea surface temperature anomalies
# 1. Atlantic
set!(simulation, sea_surface_temperature=
(λ, φ) -> (30 < φ < 60) && (270 < λ < 360) ? parameters.temperature_atlantic : 0, add=true)
# 2. Azores
A = parameters.temperature_azores
λ_az, φ_az, σ_az = -27.25, 38.7, 4 # location [˚], size [˚] of Azores
set!(simulation, sea_surface_temperature=
(λ, φ) -> A*exp(-spherical_distance((λ,φ), (λ_az,φ_az), radius=360/2π)^2/2σ_az^2), add=true)
# Run simulation for 20 days, maybe longer for more stable statistics? Could be increased to 30, 40, ... days ?
run!(simulation, period=Day(20))
# skip first 5 days, as is done in the RainMaker challenge
RainMaker.skip!(rain_gauge, Day(5))
# evaluate rain gauge
lsc = rain_gauge.accumulated_rain_large_scale
conv = rain_gauge.accumulated_rain_convection
total_precip = maximum(lsc) + maximum(conv)
return total_precip
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
Distributions = "31c24e10-a181-5473-b8eb-7969acd0382f"
Flux = "587475ba-b771-5e3f-ad9e-33799f191a9c"
JLSO = "9da8a3cd-07a3-59c0-a743-3fdc52c30d11"
PlutoPlotly = "8e989ff0-3d88-8e9f-f020-2b208a939ff0"
[compat]
BenchmarkTools = "~1.5.0"
DataFrames = "~1.7.0"
Distributions = "~0.25.115"
Flux = "~0.16.0"
JLSO = "~2.7.0"
PlutoPlotly = "~0.6.2"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.10.4"
manifest_format = "2.0"
project_hash = "1a1e320eab240ec9dcb85e6cd37d13a1e866e8f0"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
weakdeps = ["ChainRulesCore", "Test"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "6e1d2a35f2f90a4bc7c2ed98079b2ba09c35b83a"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.3.2"
[[deps.Accessors]]
deps = ["CompositionsBase", "ConstructionBase", "InverseFunctions", "LinearAlgebra", "MacroTools", "Markdown"]
git-tree-sha1 = "96bed9b1b57cf750cca50c311a197e306816a1cc"
uuid = "7d9f7c33-5ae7-4f3b-8dc6-eff91059b697"
version = "0.1.39"
[deps.Accessors.extensions]
AccessorsAxisKeysExt = "AxisKeys"
AccessorsDatesExt = "Dates"
AccessorsIntervalSetsExt = "IntervalSets"
AccessorsStaticArraysExt = "StaticArrays"
AccessorsStructArraysExt = "StructArrays"
AccessorsTestExt = "Test"
AccessorsUnitfulExt = "Unitful"
[deps.Accessors.weakdeps]
AxisKeys = "94b1ba4f-4ee9-5380-92f1-94cde586c3c5"
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
Requires = "ae029012-a4dd-5104-9daa-d747884805df"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
Unitful = "1986cc42-f94f-5a68-af5c-568840ba703d"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "50c3c56a52972d78e8be9fd135bfb91c9574c140"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "4.1.1"
weakdeps = ["StaticArrays"]
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[[deps.AliasTables]]
deps = ["PtrArrays", "Random"]
git-tree-sha1 = "9876e1e164b144ca45e9e3198d0b689cadfed9ff"
uuid = "66dad0bd-aa9a-41b7-9441-69ab47430ed8"
version = "1.1.3"
[[deps.ArgCheck]]
git-tree-sha1 = "680b3b8759bd4c54052ada14e52355ab69e07876"
uuid = "dce04be8-c92d-5529-be00-80e4d2c0e197"
version = "2.4.0"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Atomix]]
deps = ["UnsafeAtomics"]
git-tree-sha1 = "c3b238aa28c1bebd4b5ea4988bebf27e9a01b72b"
uuid = "a9b6321e-bd34-4604-b9c9-b65b8de01458"
version = "1.0.1"
[deps.Atomix.extensions]
AtomixCUDAExt = "CUDA"
AtomixMetalExt = "Metal"
AtomixoneAPIExt = "oneAPI"
[deps.Atomix.weakdeps]
CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba"
Metal = "dde4c033-4e86-420c-a63e-0dd931031962"
oneAPI = "8f75cd03-7ff8-4ecb-9b8f-daf728133b1b"
[[deps.BSON]]
git-tree-sha1 = "4c3e506685c527ac6a54ccc0c8c76fd6f91b42fb"
uuid = "fbb218c0-5317-5bc6-957e-2ee96dd4b1f0"
version = "0.3.9"
[[deps.BangBang]]
deps = ["Accessors", "ConstructionBase", "InitialValues", "LinearAlgebra", "Requires"]
git-tree-sha1 = "e2144b631226d9eeab2d746ca8880b7ccff504ae"
uuid = "198e06fe-97b7-11e9-32a5-e1d131e6ad66"
version = "0.4.3"
[deps.BangBang.extensions]
BangBangChainRulesCoreExt = "ChainRulesCore"
BangBangDataFramesExt = "DataFrames"
BangBangStaticArraysExt = "StaticArrays"
BangBangStructArraysExt = "StructArrays"
BangBangTablesExt = "Tables"
BangBangTypedTablesExt = "TypedTables"
[deps.BangBang.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
StructArrays = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
Tables = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
TypedTables = "9d95f2ec-7b3d-5a63-8d20-e2491e220bb9"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.Baselet]]
git-tree-sha1 = "aebf55e6d7795e02ca500a689d326ac979aaf89e"
uuid = "9718e550-a3fa-408a-8086-8db961cd8217"
version = "0.1.1"
[[deps.BenchmarkTools]]
deps = ["JSON", "Logging", "Printf", "Profile", "Statistics", "UUIDs"]
git-tree-sha1 = "f1dff6729bc61f4d49e140da1af55dcd1ac97b2f"
uuid = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
version = "1.5.0"
[[deps.CEnum]]
git-tree-sha1 = "389ad5c84de1ae7cf0e28e381131c98ea87d54fc"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.5.0"
[[deps.ChainRules]]
deps = ["Adapt", "ChainRulesCore", "Compat", "Distributed", "GPUArraysCore", "IrrationalConstants", "LinearAlgebra", "Random", "RealDot", "SparseArrays", "SparseInverseSubset", "Statistics", "StructArrays", "SuiteSparse"]
git-tree-sha1 = "4312d7869590fab4a4f789e97bd82f0a04eaaa05"
uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2"
version = "1.72.2"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra"]
git-tree-sha1 = "3e4b134270b372f2ed4d4d0e936aabaefc1802bc"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.25.0"
weakdeps = ["SparseArrays"]
[deps.ChainRulesCore.extensions]
ChainRulesCoreSparseArraysExt = "SparseArrays"
[[deps.CodecZlib]]
deps = ["TranscodingStreams", "Zlib_jll"]
git-tree-sha1 = "bce6804e5e6044c6daab27bb533d1295e4a2e759"
uuid = "944b1d66-785c-5afd-91f1-9de20f533193"
version = "0.7.6"
[[deps.ColorSchemes]]
deps = ["ColorTypes", "ColorVectorSpace", "Colors", "FixedPointNumbers", "PrecompileTools", "Random"]
git-tree-sha1 = "c785dfb1b3bfddd1da557e861b919819b82bbe5b"
uuid = "35d6a980-a343-548e-a6ea-1d62b119f2f4"
version = "3.27.1"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "b10d0b65641d57b8b4d5e234446582de5047050d"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.5"
[[deps.ColorVectorSpace]]
deps = ["ColorTypes", "FixedPointNumbers", "LinearAlgebra", "Requires", "Statistics", "TensorCore"]
git-tree-sha1 = "a1f44953f2382ebb937d60dafbe2deea4bd23249"
uuid = "c3611d14-8923-5661-9e6a-0046d554d3a4"
version = "0.10.0"
weakdeps = ["SpecialFunctions"]
[deps.ColorVectorSpace.extensions]
SpecialFunctionsExt = "SpecialFunctions"
[[deps.Colors]]
deps = ["ColorTypes", "FixedPointNumbers", "Reexport"]
git-tree-sha1 = "362a287c3aa50601b0bc359053d5c2468f0e7ce0"
uuid = "5ae59095-9a9b-59fe-a467-6f913c188581"
version = "0.12.11"
[[deps.CommonSubexpressions]]
deps = ["MacroTools"]
git-tree-sha1 = "cda2cfaebb4be89c9084adaca7dd7333369715c5"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.1"
[[deps.Compat]]
deps = ["TOML", "UUIDs"]
git-tree-sha1 = "8ae8d32e09f0dcf42a36b90d4e17f5dd2e4c4215"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.16.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.1.1+0"
[[deps.CompositionsBase]]
git-tree-sha1 = "802bb88cd69dfd1509f6670416bd4434015693ad"
uuid = "a33af91c-f02d-484b-be07-31d278c5ca2b"
version = "0.1.2"
weakdeps = ["InverseFunctions"]
[deps.CompositionsBase.extensions]
CompositionsBaseInverseFunctionsExt = "InverseFunctions"
[[deps.ConstructionBase]]
git-tree-sha1 = "76219f1ed5771adbb096743bff43fb5fdd4c1157"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.8"
[deps.ConstructionBase.extensions]
ConstructionBaseIntervalSetsExt = "IntervalSets"
ConstructionBaseLinearAlgebraExt = "LinearAlgebra"
ConstructionBaseStaticArraysExt = "StaticArrays"
[deps.ConstructionBase.weakdeps]
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.ContextVariablesX]]
deps = ["Compat", "Logging", "UUIDs"]
git-tree-sha1 = "25cc3803f1030ab855e383129dcd3dc294e322cc"
uuid = "6add18c4-b38d-439d-96f6-d6bc489c04c5"
version = "0.1.3"
[[deps.Crayons]]
git-tree-sha1 = "249fe38abf76d48563e2f4556bebd215aa317e15"
uuid = "a8cc5b0e-0ffa-5ad4-8c14-923d3ee1735f"
version = "4.1.1"
[[deps.DataAPI]]
git-tree-sha1 = "abe83f3a2f1b857aac70ef8b269080af17764bbe"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.16.0"
[[deps.DataFrames]]
deps = ["Compat", "DataAPI", "DataStructures", "Future", "InlineStrings", "InvertedIndices", "IteratorInterfaceExtensions", "LinearAlgebra", "Markdown", "Missings", "PooledArrays", "PrecompileTools", "PrettyTables", "Printf", "Random", "Reexport", "SentinelArrays", "SortingAlgorithms", "Statistics", "TableTraits", "Tables", "Unicode"]
git-tree-sha1 = "fb61b4812c49343d7ef0b533ba982c46021938a6"
uuid = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
version = "1.7.0"
[[deps.DataStructures]]
deps = ["Compat", "InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "1d0a14036acb104d9e89698bd408f63ab58cdc82"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.18.20"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DefineSingletons]]
git-tree-sha1 = "0fba8b706d0178b4dc7fd44a96a92382c9065c2c"
uuid = "244e2a9f-e319-4986-a169-4d1fe445cd52"
version = "0.1.2"
[[deps.DelimitedFiles]]
deps = ["Mmap"]
git-tree-sha1 = "9e2f36d3c96a820c678f2f1f1782582fcf685bae"
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
version = "1.9.1"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "23163d55f885173722d1e4cf0f6110cdbaf7e272"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.15.1"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.Distributions]]
deps = ["AliasTables", "FillArrays", "LinearAlgebra", "PDMats", "Printf", "QuadGK", "Random", "SpecialFunctions", "Statistics", "StatsAPI", "StatsBase", "StatsFuns"]