aboutsummaryrefslogtreecommitdiff
path: root/analysis/vis.livemd
blob: 0aa27113c40d203da9b5a4205456ca96261c45ab (plain)
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
<!-- livebook:{"app_settings":{"slug":"asdf"}} -->

# Dissertation Visualisations

```elixir
Mix.install([
  {:tucan, "~> 0.3.0"},
  {:kino_vega_lite, "~> 0.1.8"},
  {:json, "~> 1.4"},
  {:explorer, "~> 0.8.0"},
  {:kino_explorer, "~> 0.1.11"},
  {:math, "~> 0.7.0"}
])
```

## Variables

```elixir
require Explorer.DataFrame
require Explorer.Series
require VegaLite
alias Explorer.DataFrame, as: DF
alias Explorer.Series, as: SE
job_id = "current"
job_dir = Path.expand(~c"./" ++ job_id) |> Path.absname()
sections_dir = Path.join(job_dir, "sections")
cm_dir = Path.join([job_dir, "candelabra", "benchmark_results"])
criterion_dir = Path.join(job_dir, "criterion")
```

## Read cost model data

```elixir
{:ok, cost_model_files} = File.ls(cm_dir)

cost_model_files =
  cost_model_files
  |> Enum.map(fn fname -> Path.join(cm_dir, fname) |> Path.absname() end)

cost_model_files
```

<!-- livebook:{"reevaluate_automatically":true} -->

```elixir
# Parse cost model information
cost_models =
  cost_model_files
  |> Enum.map(fn fname ->
    impl = Path.basename(fname) |> String.replace("_", ":")
    contents = File.read!(fname)
    contents = JSON.decode!(contents)

    contents["model"]["by_op"]
    |> Enum.map(fn {op, %{"coeffs" => coeffs}} ->
      %{
        op: op,
        impl: impl,
        coeffs: coeffs
      }
    end)
    |> DF.new()
  end)
  |> DF.concat_rows()
```

```elixir
# Parse cost model information
cost_model_points =
  cost_model_files
  |> Enum.map(fn fname ->
    impl = Path.basename(fname) |> String.replace("_", ":")
    contents = File.read!(fname)
    contents = JSON.decode!(contents)

    contents["results"]["by_op"]
    |> Enum.flat_map(fn {op, results} ->
      Enum.map(results, fn [n, cost] ->
        %{
          op: op,
          impl: String.split(impl, "::") |> List.last(),
          n: n,
          t: cost
        }
      end)
    end)
    |> DF.new()
  end)
  |> DF.concat_rows()
```

```elixir
# Discard points outside one standard deviation, as we do when fitting
cost_model_points =
  cost_model_points
  |> DF.group_by(["impl", "op", "n"])
  |> DF.mutate(avg: mean(t), dev: standard_deviation(t))
  |> DF.filter(abs(t - avg) < dev)
  |> DF.discard(["avg", "dev"])
  |> DF.mutate(t: cast(t, {:duration, :nanosecond}))
```

## Cost model exploratory plots

```elixir
defmodule CostModel do
  @defaults %{y_domain: nil, ns: 1..60_000//100, draw_points: true}
  @all_impls Enum.sort([
               "SortedVec",
               "SortedVecSet",
               "SortedVecMap",
               "Vec",
               "VecSet",
               "VecMap",
               "BTreeSet",
               "BTreeMap",
               "HashSet",
               "HashMap",
               "LinkedList"
             ])

  def friendly_impl_name(impl) do
    String.split(impl, "::") |> List.last()
  end

  def points_for(cost_models, ns, impl, op) do
    %{"coeffs" => [coeffs]} =
      DF.filter(cost_models, impl == ^impl and op == ^op)
      |> DF.to_columns()

    Enum.map(ns, fn n ->
      t =
        (coeffs
         |> Enum.take(3)
         |> Enum.with_index()
         |> Enum.map(fn {coeff, idx} -> coeff * n ** idx end)
         |> Enum.sum()) + Enum.at(coeffs, 3) * Math.log2(n)

      %{
        impl: friendly_impl_name(impl),
        op: op,
        n: n,
        t: max(t, 0)
      }
    end)
    |> DF.new()
  end

  def plot(cost_models, cost_model_points, impls, op, opts \\ []) do
    %{y_domain: y_domain, ns: ns, draw_points: draw_points} = Enum.into(opts, @defaults)

    plot =
      Tucan.layers(
        [
          cost_models
          |> DF.filter(op == ^op)
          |> DF.distinct(["impl"])
          |> DF.to_rows()
          |> Enum.map(fn %{"impl" => impl} -> points_for(cost_models, ns, impl, op) end)
          |> DF.concat_rows()
          |> DF.filter(impl in ^impls)
          |> DF.sort_by(impl)
          |> Tucan.lineplot("n", "t", color_by: "impl", clip: true)
        ] ++
          if(draw_points,
            do: [
              cost_model_points
              |> DF.filter(op == ^op and impl in ^impls)
              |> DF.group_by(["impl", "n"])
              |> DF.sort_by(impl)
              |> DF.mutate(t: cast(t, :f32))
              |> Tucan.scatter(
                "n",
                "t",
                color_by: "impl",
                clip: true
              )
            ],
            else: []
          )
      )

    plot =
      plot
      |> Tucan.Axes.set_y_title("Estimated cost")
      |> Tucan.Axes.set_x_title("Size of container (n)")
      |> Tucan.set_size(500, 250)
      |> Tucan.Legend.set_title(:color, "Implementation")
      |> Tucan.Scale.set_x_domain(ns.first, ns.last)

    case y_domain do
      [lo, hi] -> Tucan.Scale.set_y_domain(plot, lo, hi)
      _ -> plot
    end
  end

  def split_plot(cost_models, cost_model_points, impl_splits, op) do
    @all_impls = List.flatten(impl_splits) |> Enum.sort()

    Enum.map(impl_splits, &plot(cost_models, cost_model_points, &1, op))
    |> Tucan.vconcat()
    |> VegaLite.resolve(:scale, color: :independent)
  end
end
```

<!-- livebook:{"reevaluate_automatically":true} -->

```elixir
graph =
  CostModel.split_plot(
    cost_models,
    cost_model_points,
    [
      ["Vec", "LinkedList"],
      ["SortedVec", "SortedVecSet", "SortedVecMap", "VecSet", "VecMap"],
      ["BTreeSet", "BTreeMap", "HashSet", "HashMap"]
    ],
    "insert"
  )

VegaLite.Export.save!(graph, "../thesis/assets/insert.json")

graph
```

<!-- livebook:{"reevaluate_automatically":true} -->

```elixir
graph =
  CostModel.plot(
    cost_models,
    cost_model_points,
    ["VecSet", "SortedVecSet", "HashSet", "BTreeSet"],
    "insert",
    ns: 1..3000//10,
    y_domain: [0, 200],
    draw_points: false
  )

VegaLite.Export.save!(graph, "../thesis/assets/insert_small_n.json")

graph
```

```elixir
graph =
  CostModel.split_plot(
    cost_models,
    cost_model_points,
    [
      ["SortedVec", "SortedVecSet", "SortedVecMap"],
      [
        "Vec",
        "LinkedList",
        "VecMap",
        "VecSet"
      ],
      ["BTreeSet", "BTreeMap", "HashSet", "HashMap"]
    ],
    "contains"
  )

VegaLite.Export.save!(graph, "../thesis/assets/contains.json")

graph
```

## Read benchmark data

```elixir
# Read in the results of every individual criterion benchmark
raw_benchmarks =
  File.ls!(criterion_dir)
  |> Enum.map(fn name ->
    File.ls!(Path.join(criterion_dir, name))
    |> Enum.map(fn p -> %{bench: name, subbench: p} end)
  end)
  |> List.flatten()
  |> Enum.map(fn %{bench: bench, subbench: subbench} ->
    File.ls!(Path.join([criterion_dir, bench, subbench]))
    |> Enum.filter(fn x -> String.contains?(x, "Mapping2D") end)
    |> Enum.map(fn x -> Path.join([criterion_dir, bench, subbench, x]) end)
    |> Enum.map(fn dir ->
      raw_results =
        Path.join(dir, "estimates.json")
        |> File.read!()
        |> JSON.decode!()

      %{
        bench_id: bench <> "/" <> subbench,
        proj: String.split(bench, "-") |> hd,
        using:
          Regex.scan(~r/\"(\w*)\", ([^)]*)/, Path.basename(dir))
          |> Enum.map(fn [_, ctn, impl] -> %{ctn: ctn, impl: impl} end),
        mean: raw_results["mean"]["point_estimate"],
        stderr: raw_results["mean"]["standard_error"]
      }
    end)
  end)
  |> List.flatten()
  |> DF.new()
  |> DF.mutate(
    mean: cast(mean, {:duration, :nanosecond}),
    stderr: cast(stderr, {:duration, :nanosecond})
  )
```

```elixir
# `using` is a list of structs, but we aren't gonna make use of this mostly
# and we want to be able to group by that column, so add a new column that's just a nice
# string representation
# also parse out the n value, which all of our benchmarks have
display_using = fn using ->
  using
  |> Enum.map(fn %{"ctn" => ctn, "impl" => impl} -> ctn <> "=" <> impl end)
  |> Enum.join(", ")
end
```

```elixir
# Aggregate benchmark results by project, since we can only do assignments by project
# Unfortunately we can't group by lists, so we need to do some weird shit.
# This is basically equivalent to:
# benchmarks = raw_benchmarks
# |> DF.group_by(["proj", "using"])
# |> DF.summarise(time: sum(mean))

# Build list of using values to index into
usings =
  raw_benchmarks["using"]
  |> SE.to_list()
  |> Enum.uniq()

benchmarks =
  raw_benchmarks
  # Make a column corresponding to using that isn't a list
  |> DF.put(
    "using_idx",
    raw_benchmarks["using"]
    |> SE.to_list()
    |> Enum.map(fn using -> Enum.find_index(usings, &(&1 == using)) end)
  )
  # Get the total benchmark time for each project and assignment
  |> DF.group_by(["proj", "using_idx"])
  |> DF.summarise(time: sum(cast(mean, :f32)))
  # Convert using_idx back to original using values
  |> DF.to_rows()
  |> Enum.map(fn row = %{"using_idx" => using_idx} ->
    Map.put(row, "using", Enum.at(usings, using_idx))
  end)
  |> DF.new()
  |> DF.select(["proj", "time", "using"])
```

## Read cost estimate data

```elixir
# Cost estimates by project, ctn, and implementation
projs = SE.distinct(benchmarks["proj"])

cost_estimates =
  SE.transform(projs, fn proj_name ->
    [_, table | _] =
      Path.join(sections_dir, "compare-" <> proj_name)
      |> File.read!()
      |> String.split("& file \\\\\n\\hline\n")

    table
    |> String.split("\n\\end{tabular}")
    |> hd
    |> String.split("\n")
    |> Enum.map(fn x -> String.split(x, " & ") end)
    |> Enum.map(fn [ctn, impl, cost | _] ->
      %{
        proj: proj_name,
        ctn: ctn,
        impl:
          impl
          |> String.replace("\\_", "_"),
        cost:
          if String.contains?(cost, ".") do
            String.to_float(cost)
          else
            String.to_integer(cost)
          end
      }
    end)
  end)
  |> SE.to_list()
  |> List.flatten()
  |> DF.new()
```

```elixir
# Double-check that we have all of the cost estimates for everything mentioned in the assignments
estimate_impls = SE.distinct(cost_estimates["impl"])

true =
  (raw_benchmarks
   |> DF.explode("using")
   |> DF.unnest("using"))["impl"]
  |> SE.distinct()
  |> SE.to_list()
  |> Enum.all?(&SE.any?(SE.equal(estimate_impls, &1)))
```

```elixir
# Gets the cost of assignment from cost estimates
cost_of_assignment = fn proj, assignment ->
  assignment
  |> Enum.map(fn %{"ctn" => ctn, "impl" => impl} ->
    DF.filter(cost_estimates, proj == ^proj and ctn == ^ctn and impl == ^impl)["cost"][0]
  end)
  |> Enum.sum()
end

cost_of_assignment.("example_stack", [%{"ctn" => "StackCon", "impl" => "std::vec::Vec"}])
```

```elixir
# For each benchmarked assignment, estimate the cost.
estimated_costs =
  benchmarks
  |> DF.to_rows_stream()
  |> Enum.map(fn %{"proj" => proj, "using" => using} ->
    %{
      proj: proj,
      using: using,
      estimated_cost: cost_of_assignment.(proj, using)
    }
  end)
  |> DF.new()
```

## Estimates vs results (ignoring adaptive containers)

```elixir
# Don't worry about adaptive containers for now
singular_estimated_costs =
  estimated_costs
  |> DF.to_rows_stream()
  |> Enum.filter(fn %{"using" => using} ->
    Enum.all?(using, fn %{"impl" => impl} -> !String.contains?(impl, "until") end)
  end)
  |> DF.new()

singular_benchmarks =
  benchmarks
  |> DF.to_rows_stream()
  |> Enum.filter(fn %{"using" => using} ->
    Enum.all?(using, fn %{"impl" => impl} -> !String.contains?(impl, "until") end)
  end)
  |> DF.new()

DF.n_rows(singular_benchmarks)
```

```elixir
# Best and predicted best implementation for each container type
selection_comparison =
  singular_benchmarks
  |> DF.explode("using")
  |> DF.unnest("using")
  |> DF.group_by(["proj"])
  |> DF.filter(time == min(time))
  |> DF.join(
    cost_estimates
    |> DF.filter(not contains(impl, "until"))
    |> DF.group_by(["proj", "ctn"])
    |> DF.filter(cost == min(cost))
    |> DF.rename(%{"impl" => "predicted_impl"})
  )
  |> DF.select(["proj", "ctn", "impl", "predicted_impl"])
  |> DF.rename(%{"impl" => "best_impl"})
```

```elixir
# Tools for printing out latex
defmodule Latex do
  def escape_latex(str) do
    String.replace(str, ~r/(\\|{|}|_|\^|#|&|\$|%|~)/, "\\\\\\1")
  end

  def table(df) do
    cols = DF.names(df)

    "\\begin{tabular}{|" <>
      String.duplicate("c|", length(cols)) <>
      "}\n" <>
      Enum.join(Enum.map(cols, &escape_latex/1), " & ") <>
      " \\\\\n\\hline\n" <>
      (DF.to_rows(df)
       |> Enum.map(fn row ->
         cols
         |> Enum.map(&escape_latex(Kernel.to_string(row[&1])))
         |> Enum.join(" & ")
       end)
       |> Enum.join(" \\\\\n")) <>
      " \\\\\n\\end{tabular}"
  end
end

Latex.table(selection_comparison)

selection_comparison
|> DF.put(
  "best_impl",
  SE.transform(selection_comparison["best_impl"], &CostModel.friendly_impl_name/1)
)
|> DF.put(
  "predicted_impl",
  SE.transform(selection_comparison["predicted_impl"], &CostModel.friendly_impl_name/1)
)
|> DF.put(
  "mark",
  SE.not_equal(selection_comparison["best_impl"], selection_comparison["predicted_impl"])
  |> SE.transform(&if &1, do: "*", else: "")
)
|> DF.rename(%{
  "mark" => " ",
  "proj" => "Project",
  "ctn" => "Container Type",
  "best_impl" => "Best implementation",
  "predicted_impl" => "Predicted best"
})
|> Latex.table()
|> IO.puts()
```

## Adaptive Containers

```elixir
# Projects where an adaptive container was suggested
adaptive_projs =
  (estimated_costs
   |> DF.to_rows()
   |> Enum.filter(fn %{"using" => using} ->
     using
     |> Enum.map(fn %{"impl" => impl} -> String.contains?(impl, "until") end)
     |> Enum.any?()
   end)
   |> DF.new()
   |> DF.distinct(["proj"]))["proj"]
```

```elixir
adaptive_estimated_costs = estimated_costs |> DF.filter(proj in ^adaptive_projs)

adaptive_raw_benchmarks =
  raw_benchmarks
  |> DF.filter(proj in ^adaptive_projs)

display_using = fn using ->
  using
  |> Enum.map(fn %{"ctn" => ctn, "impl" => impl} -> ctn <> "=" <> impl end)
  |> Enum.join(", ")
end

adaptive_raw_benchmarks =
  adaptive_raw_benchmarks
  |> DF.put(
    "n",
    adaptive_raw_benchmarks["bench_id"]
    |> SE.split("/")
    |> SE.transform(&Enum.at(&1, 1))
  )
  |> DF.put(
    "using",
    adaptive_raw_benchmarks["using"]
    |> SE.transform(display_using)
  )
```

```elixir
best_usings =
  adaptive_raw_benchmarks
  # get best set of assignments for each project
  |> DF.group_by(["proj", "using"])
  |> DF.filter(not contains(using, "until"))
  |> DF.summarise(total: sum(cast(mean, :f32)))
  |> DF.group_by(["proj"])
  |> DF.filter(total == min(total))
  |> DF.discard("total")
  |> DF.rename(%{"using" => "best_using"})
  # select adaptive container and the best assignment for each project
  |> DF.join(adaptive_raw_benchmarks)
  |> DF.filter(using == best_using or contains(using, "until"))
  # summary data point
  |> DF.mutate(value: cast(mean, :string) <> " +/- " <> cast(stderr, :string))
  |> DF.select(["proj", "using", "n", "value"])
```

```elixir
best_usings
|> DF.filter(proj == "aoc_2022_09")
|> DF.pivot_wider("n", "value")
```