generated from JuliaPluto/static-export-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notebook.jl
2095 lines (1680 loc) · 58.8 KB
/
notebook.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.19.24
using Markdown
using InteractiveUtils
# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
quote
local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch; b -> missing; end
local el = $(esc(element))
global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el)
el
end
end
# ╔═╡ 1c8d2d00-b7d9-11eb-35c4-47f2a2aa1593
begin
import Pkg
ENV["JULIA_MARGO_LOAD_PYPLOT"] = "no thank you"
Pkg.activate(mktempdir())
Pkg.add([
Pkg.PackageSpec(name="Plots", version="1"),
Pkg.PackageSpec(name="ClimateMARGO", version=v"0.3.3"),
Pkg.PackageSpec(name="PlutoUI", version="0.7"),
Pkg.PackageSpec(name="HypertextLiteral", version="0.9"),
Pkg.PackageSpec(name="Underscores", version="2"),
])
using Plots
using Plots.Colors
using ClimateMARGO
using ClimateMARGO.Models
using ClimateMARGO.Optimization
using ClimateMARGO.Diagnostics
using PlutoUI
using HypertextLiteral
using Underscores
Plots.default(linewidth=5)
end;
# ╔═╡ 9a48a08e-7281-473c-8afc-7ad3e0771269
TableOfContents()
# ╔═╡ 94415ff2-32a2-4b0f-9911-3b93e202f548
const initial_1 = Dict("M" => [2090, 6]);
# ╔═╡ 50d24c91-61ae-4544-98fa-5749bafe3d41
# md"""
# ## Overview of the climate problem: from greenhouse gas emissions to climate suffering
# Human emissions of greenhouse gases, especially Carbon Dioxide (CO₂), increase the stock of greenhouse gases in the atmosphere. For every molecule of CO₂ emitted, about 50% are taken up by plants, soils, or the ocean within a few years, while the rest remains in the atmosphere. (The effects of other greenhouse gases, such as Methane and CFCs, and other forcing agents, can approximately be converted into the "CO₂-equivalent"– or CO₂ₑ– concentrations that would lead to the same climate forcing).
# Greenhouse gases get their name because they trap invisible heat radiation emitted by Earth's surface and atmosphere from escaping to space, much like greenhouses trap hot air from rising when it is warmed by the Sun. This "greenhouse effect" causes the temperature to rise globally, although some places warm *more* and *faster* than others. Warmer temperatures exacerbate both the frequency and intensity of "natural" disasters, such as heat waves, coastal flooding from major hurricanes, and inland flooding from torrential rain. These climate impacts lead to enhanced climate suffering, which economics typically attempt to quantify suffering in terms of lost money or welfare.
# In the interactive article below, we invite you to explore the benefits of emissions mitigation and carbon dioxide removal in reducing climate suffering, and the trade-offs with their costs.
# """
# ╔═╡ e810a90f-f964-4d7d-acdb-fc3a159dc12e
const initial_2 = Dict("M" => [2080, .7]);
# ╔═╡ a3422533-2b78-4bc2-92bd-737da3c8982d
const initial_3 = Dict("M" => [2080, .7]);
# ╔═╡ bb66d347-99be-4a95-8ba8-57dc9d33384b
const initial_4 = Dict(
"M" => [2080, 0.7],
"R" => [2120, 0.2],
);
# ╔═╡ 51037451-0fea-4021-8824-56911970b97b
const initial_x = Dict("G" => [2030, 1]);
# ╔═╡ 3094a9eb-074d-46c3-9c1e-0a9c94c6ad43
blob(el, color = "red") = @htl("""<div style="
background: $(color);
padding: 1em 1em 1em 1em;
border-radius: 2em;
">$(el)</div>""")
# ╔═╡ 0b31eac2-8efd-47cd-9571-a2053846343b
function infeasablewarning(x)
@htl("""
<margo-infeasible>
$(x)
<margo-infeasible-label>No solution found</margo-infeasible-label>
</margo-infeasible>
<style>
margo-infeasible > * {
opacity: .1;
}
margo-infeasible > margo-infeasible-label {
opacity: .7;
display: block;
position: absolute;
transform: translate(-50%, -50%);
font-family: "Vollkorn", system-ui;
font-style: italic;
font-size: 40px;
top: 50%;
left: 50%;
white-space: nowrap;
}
</style>
""")
end
# ╔═╡ ca104939-a6ca-4e70-a47a-1eb3c32db18f
status_ok(x) = x ∈ [
"OPTIMAL",
"LOCALLY_SOLVED",
"ALMOST_OPTIMAL",
"ALMOST_LOCALLY_SOLVED"
]
# ╔═╡ cf90139c-13d8-42a7-aba3-8c431e7854b8
feasibility_overlay(x) = status_ok(x.status) ? as_html : infeasablewarning
# ╔═╡ bd2bfa3c-a42e-4975-a543-84541f66b1c1
begin
hidecloack(name) = HTML("""
<style>
plj-cloack.$(name) {
opacity: 0;
display: block;
}
</style>
""")
"A trick to hide a cell without creating a variable dependency, to make it simpler for PlutoSliderServer.jl."
cloak(name) = x -> @htl("<plj-cloack class=$(name)>$(x)</plj-cloak>")
end
# ╔═╡ b81de514-2506-4243-8235-0b54dd4a7ec9
colors = (
baseline=colorant"#dddddd",
baseline_emissions=colorant"#dddddd",
baseline_concentrations=colorant"#dddddd",
baseline_temperature=colorant"#dddddd",
baseline_damages=colorant"#dddddd",
temperature=colorant"#edc949",
above_paris=colorant"#e1575910",
M=colorant"#4E79A7",
R=colorant"#F28E2C",
A=colorant"#59A14F",
G=colorant"#E15759",
T_max=colorant"#00000080",
controls=colorant"#af7aa1",
damages=colorant"#e15759",
avoided_damages=colorant"#e49734",
benefits=colorant"#7abf5e",
emissions=colorant"brown",
emissions_1=colorant"#4E79A7",
concentrations=colorant"brown",
)
# ╔═╡ 73e01bd8-f56b-4bb5-a9a2-85ad223c9e9b
names = (
baseline="Baseline",
baseline_emissions="Baseline",
baseline_concentrations="Baseline",
baseline_temperature="Baseline",
baseline_damages="Baseline",
temperature="Temperature",
above_paris="Above Paris",
M="Mitigation",
R="Removal",
A="Adaptation",
G="Geo-engineering",
T_max="Goal temperature",
controls="Controls",
damages="Damages",
avoided_damages="Avoided Damages",
benefits="Benefits",
emissions="Emissions",
emissions_1="Emissions",
concentrations="Concentrations",
)
# ╔═╡ ae92ba1f-5175-4704-8240-2de8432df752
@assert keys(colors) == keys(names)
# ╔═╡ 8ac04d55-9034-4c29-879b-3b10887a616d
begin
struct BondDefault
x
default
end
Base.get(bd::BondDefault) = bd.default
Base.show(io::IO, m::MIME"text/html", bd::BondDefault) = Base.show(io, m, bd.x)
BondDefault
end
# ╔═╡ e846c6e2-aa63-40db-8592-c9563bbbdd40
@bind which_graph_2 Select([
"Emissions"
"Concentrations"
"Temperature"
])
# ╔═╡ 9d603716-3069-4032-9416-cd8ab2e272c6
@bind which_graph_4 Select([
"Emissions"
"Concentrations"
"Temperature"
"Costs and benefits"
])
# ╔═╡ 70173466-c9b5-4227-8fba-6256fc1ecace
Tmax_9_slider = @bind Tmax_9 Slider(0:0.1:5; default=2);
# ╔═╡ 6bcb9b9e-e0ab-45d3-b9b9-3d7282f89df6
allow_overshoot_9_cb = @bind allow_overshoot_9 CheckBox();
# ╔═╡ b428e2d3-e1a9-4e4e-a64f-61048572102f
function multiplier(unit::Real, factor::Real=2, suffix::String="%")
h = @htl("""
<script>
const unit = $(unit)
const factor = $(factor)
const suffix = $(suffix)
const input = html`<input type=range min=-1 max=1 step=.01 value=0>`;
const output = html`<input disabled style="width: 1.8em; display: inline-block;overflow-x: hidden;"></input>`;
// const output = html``;
const left = Math.round(100 / factor) + "%";
const right = Math.round(100 * factor) + "%";
const reset = html`<a href="#" title="Reset" style='padding-left: .5em'><img width="14" src="https://cdn.jsdelivr.net/gh/ionic-team/[email protected]/src/svg/arrow-undo-sharp.svg"></img></a>`;
const span = html`<div style="margin-left: 2em;">\${left}\${input}\${right}\${reset}</div>`;
const on_slider = () => {
output.value = Math.round(100 * Math.pow(factor, input.value));
input.title = Math.round(100 * Math.pow(factor, input.value)) + "%";
reset.style.opacity = input.valueAsNumber == 0 ? "0" : "1";
};
input.oninput = on_slider;
on_slider();
// const on_box = () => {
// input.value = output.value;
// reset.style.opacity = input.valueAsNumber == 100 ? "0" : "1";
// };
// output.oninput = on_box;
reset.onclick = (e) => {
input.value = 0;
on_slider();
e.preventDefault()
span.dispatchEvent(new CustomEvent("input", {}));
};
Object.defineProperty(span, "value", {
get: () => unit * Math.pow(factor, input.value),
set: val => {
input.value = Math.log2(val / unit) / Math.log2(factor);
on_slider();
}
});
return span;
</script>
""")
BondDefault(h, unit)
end
# ╔═╡ 8cab3d28-a457-4ccc-b053-38cd003bf4d1
function Carousel(
elementsList;
wraparound::Bool=false,
peek::Bool=true,
)
@assert peek
carouselHTML = map(elementsList) do element
@htl("""<div class="carousel-slide">
$(element)
</div>""")
end
h = @htl("""
<div>
<style>
.carousel-box{
width: 100%;
overflow: hidden;
}
.carousel-container{
top: 0;
left: 0;
display: flex;
width: 100%;
flex-flow: row nowrap;
transform: translate(10%, 0px);
transition: transform 200ms ease-in-out;
}
.carousel-controls{
display: flex;
justify-content: center;
align-items: center;
}
.carousel-controls button{
margin: 8px;
width: 6em;
}
.carousel-slide {
min-width: 80%;
}
</style>
<script>
const div = currentScript.parentElement
const buttons = div.querySelectorAll("button")
const max = $(length(elementsList))
let count = 0
const mod = (n, m) => ((n % m) + m) % m
const clamp = (x, a, b) => Math.max(Math.min(x, b), a)
const update_ui = (count) => {
buttons[0].disabled = !$(wraparound) && count === 0
buttons[1].disabled = !$(wraparound) && count === max - 1
div.querySelector(".carousel-container").style = `transform: translate(\${10-count*80}%, 0px)`;
}
const onclick = (e) => {
const new_count = count + parseInt(e.target.dataset.value)
if($(wraparound)){
count = mod(new_count, max)
} else {
count = clamp(new_count, 0, max - 1)
}
div.value = count + 1
div.dispatchEvent(new CustomEvent("input"))
update_ui(div.value - 1)
e.preventDefault()
}
buttons.forEach(button => button.addEventListener("click", onclick))
div.value = count + 1
update_ui(div.value - 1)
</script>
<div class="carousel-box">
<div class="carousel-container">
$(carouselHTML)
</div>
</div>
<div class="carousel-controls">
<button data-value="-1">Previous</button>
<button data-value="1">Next</button>
</div>
</div>
""")
BondDefault(h,1)
end
# ╔═╡ c7cbc172-daed-406f-b24b-5da2cc234c29
preindustrial_concentrations = 280
# ╔═╡ b440cd13-36a9-4c54-9d80-ac3fa7c2900e
end_of_oil = 2150 # cannot mitigate when fossil fuels are depleted
# ╔═╡ ec760706-15ac-4a50-a67e-c338d70f3b0a
pp = (;
((k, (:color => c, :label => n))
for (k, c, n) in zip(keys(names), colors, names))...
);
# ╔═╡ bb4b25e4-0db5-414b-a384-0a27fe7efb66
gauss_stdev = 30
# ╔═╡ 013807a0-bddb-448b-9300-f7f559e48a45
begin
default_usage_error = :(error("Example usage:\n\n@intially [1,2] @bind x f(x)\n"))
macro initially(::Any)
default_usage_error
end
macro initially(default, bind_expr::Expr)
if bind_expr.head != :macrocall || bind_expr.args[1] != Symbol("@bind")
return default_usage_error
end
# warn if the first argument is a @bind
if default isa Expr && default.head == :macrocall && default.args[1] == Symbol("@bind")
return default_usage_error
end
esc(intially_function(default, bind_expr))
end
function intially_function(default, bind_expr)
sym = bind_expr.args[3]
@gensym setval bond
quote
if !@isdefined($sym)
$sym = $default
end
$setval = $sym
$bond = @bind $sym $(bind_expr.args[4])
PlutoRunner.Bond
if $sym isa Missing
$sym = $setval
end
$bond
end
end
end
# ╔═╡ 4e91fb48-fc5e-409e-9a7e-bf846f1d211d
html"""
<style>
margo-knob {
display: block;
cursor: pointer;
width: 32px;
height: 32px;
transform: translate(-8px, -16px);
background: red;
border-radius: 100%;
border-width: 5px;
border-style: solid;
border-color: rgb(255 255 255 / 43%);
border-opacity: .2;
position: absolute;
top: 0px;
left: 0px;
}
margo-knob-label {
transform: translate(32px, -8px);
display: block;
position: absolute;
left: 0;
top: 0;
white-space: nowrap;
background: #d6eccb;
font-family: system-ui;
padding: .4em;
border-radius: 11px;
font-weight: 600;
pointer-events: none;
opacity: 0;
}
.wiggle margo-knob {
animation: wiggle-margo-knob 5s ease-in-out;
animation-delay: 600ms;
}
.wiggle margo-knob-label {
animation: fadeout 1s ease-in-out;
animation-delay: 3s;
animation-fill-mode: both;
}
@keyframes fadeout {
from {
opacity: 1;
}
to {
opactiy: 0;
}
}
@keyframes wiggle-margo-knob {
0% {
transform: translate(-8px, -16px);
}
2% {
transform: translate(8px, -16px);
}
5% {
transform: translate(-24px, -16px);
}
10% {
transform: translate(-8px, -16px);
}
/* 15% {
transform: translate(-8px, -16px);
}
17% {
transform: translate(-8px, 0px);
}
20% {
transform: translate(-8px, -32px);
}
25% {
transform: translate(-8px, -16px);
}*/
}
</style>
"""
# ╔═╡ 3c7271ab-ece5-4ae2-a8dd-dc3670f300f7
# initial_mrga_1 = Dict(
# "M" => [2070, 0.7],
# "R" => [2100, 0.4],
# "G" => [2170, 0.3],
# "A" => [2110, 0.1],
# )
# ╔═╡ dcf265c1-f09b-483e-a361-d54c6c7500c1
# @initially initial_mrga_1 @bind input_8 begin
# controls_8 = MRGA(
# gaussish(input_8["M"]...),
# gaussish(input_8["R"]...),
# gaussish(input_8["G"]...),
# gaussish(input_8["A"]...),
# )
# plotclicktracker2(
# plot_controls(controls_8),
# initial_mrga_1,
# )
# end
# ╔═╡ 10c015ec-780c-4453-83cb-12dd0f09f358
function plotclicktracker(p::Plots.Plot; draggable::Bool=false)
# we need to render the plot before its dimensions are available:
# plot_render = repr(MIME"image/svg+xml"(), p)
plot_render = repr(MIME"image/svg+xml"(), p)
# these are the _bounding boxes_ of our plot
big = bbox(p.layout)
small = plotarea(p[1])
# the axis limits
xl = xlims(p)
yl = ylims(p)
# with this information, we can form the linear transformation from
# screen coordinate -> plot coordinate
# this is done on the JS side, to avoid one step in the Julia side
# we send the linear coefficients:
r = (
x_offset = xl[1] - (xl[2] - xl[1]) * small.x0[1] / small.a[1],
x_scale = (big.a[1] / small.a[1]) * (xl[2] - xl[1]),
y_offset = (yl[2] - yl[1]) + (small.x0[2] / small.a[2]) * (yl[2] - yl[1]) + yl[1],
y_scale = -(big.a[2]/ small.a[2]) * (yl[2] - yl[1]),
x_min = xl[1], # TODO: add margin
x_max = xl[2],
y_min = yl[1],
y_max = yl[2],
)
HTML("""<script id="hello">
const body = $(PlutoRunner.publish_to_js(plot_render))
const mime = "image/svg+xml"
const img = this ?? document.createElement("img")
let url = URL.createObjectURL(new Blob([body], { type: mime }))
img.type = mime
img.src = url
img.draggable = false
img.style.cursor = "pointer"
const clamp = (x,a,b) => Math.min(Math.max(x, a), b)
img.transform = f => [
clamp(f[0] * $(r.x_scale) + $(r.x_offset), $(r.x_min), $(r.x_max)),
clamp(f[1] * $(r.y_scale) + $(r.y_offset), $(r.y_min), $(r.y_max)),
]
img.fired = false
const val = {current: undefined }
if(this == null) {
Object.defineProperty(img, "value", {
get: () => val.current,
set: () => {},
})
const handle_mouse = (e) => {
const svgrect = img.getBoundingClientRect()
const f = [
(e.clientX - svgrect.left) / svgrect.width,
(e.clientY - svgrect.top) / svgrect.height
]
if(img.fired === false){
img.fired = true
val.current = img.transform(f)
img.dispatchEvent(new CustomEvent("input"), {})
}
}
img.addEventListener("click", onclick)
img.addEventListener("pointerdown", e => {
if($(draggable)){
img.addEventListener("pointermove", handle_mouse);
}
handle_mouse(e);
});
const mouseup = e => {
img.removeEventListener("pointermove", handle_mouse);
};
document.addEventListener("pointerup", mouseup);
document.addEventListener("pointerleave", mouseup);
}
return img
</script>""")
end
# ╔═╡ 7e540eaf-8700-4176-a96c-77ee2e4c384b
years = 2020:12.0:2200
# ╔═╡ 646591c4-cb60-41cd-beb9-506807ce17d2
function gaussish(mean, magnitude)
my_stdev = gauss_stdev * (1 + magnitude);
map(years) do t
clamp(
(1.5 *
magnitude *
(-0.4 +
exp(
(-1 * ((t - mean) * (t - mean))) / (2 * my_stdev * my_stdev)
))) /
(1.0 - 0.4),
0.0,
1.0
)
end
end
# ╔═╡ 6fb77b13-7a54-4d1d-9985-4735318680e1
function expcontrol(mean, magnitude)
sulfur_fraction = 0.33
initial_value = sulfur_fraction
map(years) do t
sulfur_fraction + (magnitude-sulfur_fraction)*(1-exp(-(t-2020)/((mean-2020))))
end
end
# ╔═╡ 8fa94ec9-1fab-41b9-a7e6-1917e975e4ff
function default_parameters()::ClimateModelParameters
result = deepcopy(ClimateMARGO.IO.included_configurations["default"])
result.domain = years isa Domain ? years : Domain(step(years), first(years), last(years))
result.economics.baseline_emissions = ramp_emissions(result.domain)
result.economics.extra_CO₂ = zeros(size(result.economics.baseline_emissions))
return result
end
# ╔═╡ 785c428d-d4f7-431e-94d7-039b0708a78a
function opt_controls_temp(model_parameters = default_parameters(); opt_parameters...)
model = ClimateModel(model_parameters)
model_optimizer = optimize_controls!(model; opt_parameters..., print_raw_status=false)
(
result=model,
status=ClimateMARGO.Optimization.JuMP.termination_status(model_optimizer) |> string,
)
# return Dict(
# :model_parameters => model_parameters,
# model_results(model)...
# )
end
# ╔═╡ 2dcd5669-c725-40b9-84c4-f8399f6e924b
bigbreak = html"""
<div style="height: 10em;"></div>
""";
# ╔═╡ b8f9efec-63ac-4e58-93cf-9f7199b78451
function setfieldconvert!(value, name::Symbol, x)
setfield!(value, name, convert(typeof(getfield(value, name)), x))
end
# ╔═╡ 371991c7-13dd-46f6-a730-ad89f43c6f0e
function enforce_maxslope!(controls;
dt=step(years),
max_slope=Dict("mitigate"=>1. /40., "remove"=>1. /40., "geoeng"=>1. /80., "adapt"=> 0.)
)
controls.mitigate[1] = 0.0
controls.remove[1] = 0.0
controls.geoeng[1] = 0.0
# controls.adapt[1] = 0.0
for i in 2:length(controls.mitigate)
controls.mitigate[i] = clamp(
controls.mitigate[i],
controls.mitigate[i-1] - max_slope["mitigate"]*dt,
controls.mitigate[i-1] + max_slope["mitigate"]*dt
)
controls.remove[i] = clamp(
controls.remove[i],
controls.remove[i-1] - max_slope["remove"]*dt,
controls.remove[i-1] + max_slope["remove"]*dt
)
controls.geoeng[i] = clamp(
controls.geoeng[i],
controls.geoeng[i-1] - max_slope["geoeng"]*dt,
controls.geoeng[i-1] + max_slope["geoeng"]*dt
)
controls.adapt[i] = clamp(
controls.adapt[i],
controls.adapt[i-1] - max_slope["adapt"]*dt,
controls.adapt[i-1] + max_slope["adapt"]*dt
)
end
end
# ╔═╡ e815d175-1c47-4aef-bd89-e7fdc3e4912e
function enforce_maxslope!2(controls;
dt=step(years),
max_slope=Dict("mitigate"=>1. /40., "remove"=>1. /40., "geoeng"=>1. /80., "adapt"=> 0.)
)
controls.mitigate[1] = 0.0
controls.remove[1] = 0.0
controls.geoeng[1] = 0.0
# controls.adapt[1] = 0.0
for i in 2:length(controls.mitigate)
controls.mitigate[i] = clamp(
controls.mitigate[i],
controls.mitigate[i-1] - max_slope["mitigate"]*dt,
controls.mitigate[i-1] + max_slope["mitigate"]*dt
)
controls.remove[i] = clamp(
controls.remove[i],
controls.remove[i-1] - max_slope["remove"]*dt,
controls.remove[i-1] + max_slope["remove"]*dt
)
# controls.geoeng[i] = clamp(
# controls.geoeng[i],
# controls.geoeng[i-1] - max_slope["geoeng"]*dt,
# controls.geoeng[i-1] + max_slope["geoeng"]*dt
# )
controls.adapt[i] = clamp(
controls.adapt[i],
controls.adapt[i-1] - max_slope["adapt"]*dt,
controls.adapt[i-1] + max_slope["adapt"]*dt
)
end
end
# ╔═╡ b7ca316b-6fa6-4c2e-b43b-cddb08aaabbb
function costs_dict(costs, model)
Dict(
:discounted => costs,
:total_discounted => sum(costs .* model.domain.dt),
)
end
# ╔═╡ 0a3be2ea-6af6-43c0-b8fb-e453bc2b703b
model_results(model::ClimateModel) = Dict(
:controls => model.controls,
:computed => Dict(
:temperatures => Dict(
:baseline => T_adapt(model),
:M => T_adapt(model; M=true),
:MR => T_adapt(model; M=true, R=true),
:MRG => T_adapt(model; M=true, R=true, G=true),
:MRGA => T_adapt(model; M=true, R=true, G=true, A=true),
),
:emissions => Dict(
:baseline => effective_emissions(model),
:M => effective_emissions(model; M=true),
:MRGA => effective_emissions(model; M=true, R=true),
),
:concentrations => Dict(
:baseline => c(model),
:M => c(model; M=true),
:MRGA => c(model; M=true, R=true),
),
:damages => Dict(
:baseline => costs_dict(damage(model; discounting=true), model),
:MRGA => costs_dict(damage(model; M=true, R=true, G=true, A=true, discounting=true), model),
),
:costs => Dict(
:M => costs_dict(cost(model; M=true, discounting=true), model),
:R => costs_dict(cost(model; R=true, discounting=true), model),
:G => costs_dict(cost(model; G=true, discounting=true), model),
:A => costs_dict(cost(model; A=true, discounting=true), model),
:MRGA => costs_dict(cost(model; M=true, R=true, G=true, A=true, discounting=true), model),
),
),
)
# ╔═╡ eb0c961d-42cf-4219-a36e-cd492fa31f6b
const cost_bars_scale = 70
# ╔═╡ ec5d87a6-354b-4f1d-bb73-b3db08589d9b
total_discounted(costs, model) = sum(costs .* model.domain.dt)
# ╔═╡ 70f01a4d-0aa3-4cd5-ad71-452c490c61ac
colors_js = Dict((k,string("#", hex(v))) for (k,v) in pairs(colors));
# ╔═╡ ac779b93-e19e-41de-94cb-6a2a919bcd2e
names_js = Dict(pairs(names));
# ╔═╡ 5c484595-4646-484f-9e75-a4a3b4c2af9b
function plotclicktracker2(p::Plots.Plot, initial::Dict; draggable::Bool=true)
# we need to render the plot before its dimensions are available:
# plot_render = repr(MIME"image/svg+xml"(), p)
plot_render = repr(MIME"image/svg+xml"(), p)
# these are the _bounding boxes_ of our plot
big = bbox(p.layout)
small = plotarea(p[1])
# the axis limits
xl = xlims(p)
yl = ylims(p)
# with this information, we can form the linear transformation from
# screen coordinate -> plot coordinate
# this is done on the JS side, to avoid one step in the Julia side
# we send the linear coefficients:
r = (
x_offset = xl[1] - (xl[2] - xl[1]) * small.x0[1] / small.a[1],
x_scale = (big.a[1] / small.a[1]) * (xl[2] - xl[1]),
y_offset = (yl[2] - yl[1]) + (small.x0[2] / small.a[2]) * (yl[2] - yl[1]) + yl[1],
y_scale = -(big.a[2]/ small.a[2]) * (yl[2] - yl[1]),
x_min = xl[1], # TODO: add margin
x_max = xl[2],
y_min = yl[1],
y_max = yl[2],
aspect_ratio = big.a[1] / big.a[2],
)
@htl("""<script id="hello">
const initial = $(initial)
const colors = $(colors_js)
const names = $(names_js)
const body = $(PlutoRunner.publish_to_js(plot_render))
const mime = "image/svg+xml"
const knob = (name) => {
const k = html`<margo-knob id=\${name}><margo-knob-label>👈 Move me!</margo-knob-label></margo-knob>`
k.style.backgroundColor = colors[name]
return k
}
const aspect_ratio = $(r.aspect_ratio)
const wrapper = this ?? html`
<div style='touch-action: none;'>
<img style='width: 100%; aspect-ratio: \${aspect_ratio}; background: white;'>
\${Object.keys(initial).map(knob)}
</div>
`
const img = wrapper.firstElementChild
let url = URL.createObjectURL(new Blob([body], { type: mime }))
invalidation.then(() => {
URL.revokeObjectURL(url)
})
// Call `fetch` on the URL to trigger the browser to make it ready.
let fetch_promise = fetch(url)
Promise.race([
fetch_promise,
invalidation.then(x => null)
]).then((r) => {
if(r != null) {
img.type = mime
img.src = url
img.draggable = false
}
})
const clamp = (x,a,b) => Math.min(Math.max(x, a), b)
wrapper.transform = f => [
clamp(f[0] * $(r.x_scale) + $(r.x_offset), $(r.x_min), $(r.x_max)),
clamp(f[1] * $(r.y_scale) + $(r.y_offset), $(r.y_min), $(r.y_max)),
]
wrapper.inversetransform = f => [
(f[0] - $(r.x_offset)) / $(r.x_scale),
(f[1] - $(r.y_offset)) / $(r.y_scale),
]
const set_knob_coord = (k, coord) => {
const svgrect = img.getBoundingClientRect()
const r = wrapper.inversetransform(coord)
k.style.left = `\${r[0] * svgrect.width}px`
k.style.top = `\${r[1] * svgrect.height}px`
}
wrapper.fired_already = false
wrapper.last_render_time = Date.now()
// If running for the first time
if(this == null) {
console.log("Creating new plotclicktracker...")
// will contain the currently dragging HTMLElement
const dragging = { current: undefined }
const value = {...initial}
Object.defineProperty(wrapper, "value", {
get: () => value,
set: (x) => {
/* console.log("old", value, "new", x)
Object.assign(value, x)
Object.entries(value).forEach(([k,v]) => {
set_knob_coord(
wrapper.querySelector(`margo-knob#\${k}`),
v
)
}) */
},
})
////
// Event listener for pointer move
const allow_only_one_event_per_render = false
const on_pointer_move = (e) => {
if(Object.keys(initial).includes(dragging.current.id)){
const svgrect = img.getBoundingClientRect()
const f = [
(e.clientX - svgrect.left) / svgrect.width,
(e.clientY - svgrect.top) / svgrect.height
]
if(!allow_only_one_event_per_render || wrapper.fired_already === false){
const new_coord = wrapper.transform(f)
value[dragging.current.id] = new_coord
set_knob_coord(dragging.current, new_coord)
wrapper.classList.toggle("wiggle", false)
wrapper.fired_already = true
wrapper.dispatchEvent(new CustomEvent("input"), {})
}
}
}
////
// Add the listeners
wrapper.addEventListener("pointerdown", e => {