-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
1549 lines (1247 loc) · 44.8 KB
/
plot.py
File metadata and controls
1549 lines (1247 loc) · 44.8 KB
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
from __future__ import annotations
import argparse
import dataclasses
from pathlib import Path
import sys
from types import ModuleType
import plotly.express as px
import plotly.subplots
import plotly.graph_objects as go
import polars as pl
import polars.selectors as cs
def add_prefix(df: pl.DataFrame, prefix: str, dot: str = ".") -> pl.DataFrame:
"""Add the given prefix on all columns without a dot of the dataframe.
Example:
id, name, age, friend.id -> p.id, p.name, p.age, friend.id
"""
return df.rename({
column: prefix + dot + column
for column in df.columns
if dot not in column
})
def cast_duration(df: pl.DataFrame) -> pl.DataFrame:
"""Cast duration to i64 number of microseconds.
This is a fix for `timedelta is not JSON serializable`."""
return df.with_columns(
pl.col(pl.Duration).dt.total_microseconds(),
)
@dataclasses.dataclass
class Database:
"""Collection of dataframes."""
raw_df: pl.DataFrame
problem_df: pl.DataFrame
flatzinc_df: pl.DataFrame
run_df: pl.DataFrame
configuration_df: pl.DataFrame
event_df: pl.DataFrame
# Mapping from problem type to arrow
PROBLEM_TYPE_ARROW = {
"maximize": "↑",
"minimize": "↓",
}
@staticmethod
def read(results_dir: Path, improve: bool = True) -> Database:
"""Read all CSV files within results directory and return a new Database object."""
raw_df = Database.read_raw_df(results_dir)
problem_df = Database.make_problem_df(raw_df)
flatzinc_df = Database.make_flatzinc_df(raw_df, problem_df)
configuration_df = Database.make_configuration_df(raw_df)
run_df = Database.make_run_df(raw_df, problem_df, flatzinc_df, configuration_df)
event_df = Database.make_event_df(raw_df, problem_df, flatzinc_df, configuration_df, run_df)
db = Database(
raw_df=raw_df,
problem_df=problem_df,
flatzinc_df=flatzinc_df,
configuration_df=configuration_df,
run_df=run_df,
event_df=event_df,
)
if improve:
db.improve()
return db
@staticmethod
def read_raw_df(results_dir: Path) -> pl.DataFrame:
"""Read all CSV files within results directory and return a raw dataframe."""
sub_dfs = []
# Read
for configuration in results_dir.iterdir():
if not configuration.is_dir():
continue
csv_file = configuration / "results.csv"
sub_df = pl.read_csv(csv_file)
sub_df.insert_column(
index = 0,
column = pl.lit(configuration.name).alias("configuration"),
)
sub_dfs.append(sub_df)
# Gather all dataframes in one
df: pl.DataFrame = pl.concat(sub_dfs, rechunk=True)
# Convert time to duration
df = df.with_columns(
pl.duration(microseconds=pl.col("time")).alias("time"),
)
schema = {
"configuration": pl.Categorical(ordering="lexical"),
"problem": pl.Categorical(ordering="lexical"),
"flatzinc": pl.Categorical(ordering="lexical"),
"type": pl.Enum(categories=["start", "new_solution"]),
"num_solutions": pl.UInt64,
"objective": pl.Int64,
"time": pl.Duration(time_unit="us"),
"num_decisions": pl.UInt64,
"num_conflicts": pl.UInt64,
"num_dom_updates": pl.UInt64,
"num_restarts": pl.UInt64,
}
# Verify the columns fit the schema
expected_columns = list(schema.keys())
if df.columns != expected_columns:
print(f"expected columns for raw dataframe: {expected_columns}", file=sys.stderr)
print(f" actual columns for raw dataframe: {df.columns}", file=sys.stderr)
assert df.columns == expected_columns
# Cast columns
df = df.cast(schema)
return df
@staticmethod
def make_problem_df(raw_df: pl.DataFrame) -> pl.DataFrame:
"""Make problem dataframe from raw dataframe."""
df = raw_df.select("problem").unique()
df = df.rename({"problem": "name"})
df = df.sort("name")
df = df.with_row_index("id")
# Problem name must be unique
assert df.get_column("name").is_unique().all()
return df
@staticmethod
def make_flatzinc_df(raw_df: pl.DataFrame, problem_df: pl.DataFrame) -> pl.DataFrame:
"""Make flatzinc dataframe from raw and problem dataframes."""
df = raw_df.select("problem", "flatzinc").unique()
# Join on problem names
df = df.join(
problem_df.select("name", "id"),
left_on="problem",
right_on="name",
how="left"
)
# Drop problem name
df = df.drop("problem")
# Rename columns
df = df.rename({
"flatzinc": "name",
"id": "problem.id",
})
# Sort on problem then name
df = df.sort("problem.id", "name")
# The pair (name, problem.id) must be unique
assert df.select("name", "problem.id").is_unique().all()
df = df.with_row_index("id")
return df
@staticmethod
def make_configuration_df(raw_df: pl.DataFrame) -> pl.DataFrame:
"""Make configuration dataframe from raw dataframe."""
df = raw_df.select("configuration").unique()
# Extract variable order, value order and restart policy from the name
df = df.with_columns(
pl.col("configuration").cast(pl.String)
.str.split_exact("_", 2)
.struct.rename_fields(["var_order", "value_order", "restart"])
.alias("fields"),
).unnest("fields")
# Cast heuristic columns to categorical
df = df.cast({
"var_order": pl.Categorical(ordering="lexical"),
"value_order": pl.Categorical(ordering="lexical"),
"restart": pl.Categorical(ordering="lexical"),
})
df_nulls = df.filter(pl.col("restart").is_null())
# Print error messages for wrong configuration name
for configuration in df_nulls.get_column("configuration"):
print(f"configuration '{configuration}' is not of the form varorder_valueorder_restart", file=sys.stderr)
assert df_nulls.is_empty(), "a configuration is not of the form varorder_valueorder_restart"
df = df.rename({
"configuration": "name",
})
# Sort on name
df = df.sort("name")
df = df.with_row_index("id")
return df
@staticmethod
def make_run_df(
raw_df: pl.DataFrame,
problem_df: pl.DataFrame,
flatzinc_df: pl.DataFrame,
configuration_df: pl.DataFrame
) -> pl.DataFrame:
"""Make configuration dataframe from raw, problem, flatzinc and configuration dataframes."""
fzn_df = flatzinc_df.join(
problem_df.select("id", "name"),
left_on="problem.id",
right_on="id"
).rename({
"name_right": "problem.name",
"name": "flatzinc.name",
"id": "flatzinc.id",
})
df = raw_df.select("configuration", "problem", "flatzinc").unique()
# Join for flatzinc id
df = df.join(
fzn_df,
left_on=("problem", "flatzinc"),
right_on=("problem.name", "flatzinc.name"),
)
# Join for configuration id
df = df.join(
configuration_df.select("name", "id"),
left_on="configuration",
right_on="name",
)
df = df.rename({
"id": "configuration.id",
})
df = df.select("flatzinc.id", "configuration.id")
# Pair (flatzinc.id, configuration.id) should be unique
assert df.is_unique().all()
# Sort on flatzinc then configuration
df = df.sort("flatzinc.id", "configuration.id")
df = df.with_row_index("id")
return df
@staticmethod
def make_event_df(
raw_df: pl.DataFrame,
problem_df: pl.DataFrame,
flatzinc_df: pl.DataFrame,
configuration_df: pl.DataFrame,
run_df: pl.DataFrame,
) -> pl.DataFrame:
"""Make configuration dataframe from raw, problem, flatzinc and configuration dataframes."""
fzn_df = flatzinc_df.join(
problem_df.select("id", "name"),
left_on="problem.id",
right_on="id"
).rename({
"name_right": "problem.name",
"name": "flatzinc.name",
"id": "flatzinc.id",
})
id_df = run_df.join(
fzn_df,
on="flatzinc.id",
how="left",
).join(
configuration_df.select("id", "name"),
left_on="configuration.id",
right_on="id",
how="left",
).rename({
"id": "run.id",
"name": "configuration.name",
})
df = raw_df.join(
id_df,
left_on=("configuration", "problem", "flatzinc"),
right_on=("configuration.name", "problem.name", "flatzinc.name"),
how="left"
)
# Keep all columns but configuration, problem, flatzinc
columns = raw_df.columns[3:]
columns.insert(0, "run.id")
df = df.select(columns)
# Sort by run then time
df = df.sort("run.id", "time")
df = df.with_row_index("id")
return df
def add_problem_type(self) -> None:
"""Add problem type depending on objective variations."""
# Check if a run is increasing and/or decreasing
df = self.event_df.group_by("run.id").agg(
(pl.col("objective") - pl.col("objective").shift() > 0).any().alias("increase"),
(pl.col("objective") - pl.col("objective").shift() < 0).any().alias("decrease"),
)
# A run is monotonic iff objective is not decreasing and increasing
df = df.with_columns(
(pl.col("increase").not_() | pl.col("decrease").not_()).alias("monotonic"),
)
# Collect configuration, flatzinc and problem names for debug output
df_not_monotonic = df.filter(pl.col("monotonic").not_()).join(
add_prefix(self.run_df, "run"),
on="run.id",
).join(
add_prefix(self.configuration_df, "configuration"),
on="configuration.id",
).join(
add_prefix(self.flatzinc_df, "flatzinc"),
on="flatzinc.id",
).join(
add_prefix(self.problem_df, "problem"),
on="problem.id",
).select("problem.name", "flatzinc.name", "configuration.name")
# Print error messages for non-monotonic runs
for row in df_not_monotonic.iter_rows():
problem, flatzinc, configuration = row
print(
f"objective value of '{flatzinc}' from '{problem}' runned with '{configuration}' is not monotonic",
file=sys.stderr
)
assert df_not_monotonic.is_empty(), "there is a run with non-monotonic objective"
df = df.join(
add_prefix(self.run_df, "run"),
on="run.id",
).join(
add_prefix(self.flatzinc_df, "flatzinc"),
on="flatzinc.id",
).join(
add_prefix(self.problem_df, "problem"),
on="problem.id",
)
# Check monotonicity for a problem
df = df.group_by("problem.id", "problem.name").agg(
pl.col("increase").any(),
pl.col("increase").sum().alias("num_increase"),
pl.col("decrease").sum().alias("num_decrease"),
)
# Get problems with both increasing and decreasing runs
df_both = df.filter(
(pl.col("num_decrease") != 0) & (pl.col("num_increase") != 0)
).select("problem.id", "num_decrease", "num_increase")
# Print error messages for each non monotonic problem
for row in df_both.iter_rows():
problem, num_decrease, num_increase = row
print(f"problem '{problem}' has {num_decrease} decreasing runs and {num_increase} increasing", file=sys.stderr)
assert df_both.is_empty(), "there is a problem with both increasing and decreasing flatzinc"
# Problem is maximise iff increase
df = df.with_columns(
pl.when("increase").then(pl.lit("maximize")).otherwise(pl.lit("minimize")).alias("type"),
)
# Make enum for problem type
df = df.cast({
"type": pl.Enum(categories=["minimize", "maximize"]),
})
df = df.rename({
"problem.id": "id",
"problem.name": "name",
})
df = df.select("id", "name", "type")
df = df.sort("id")
assert df.get_column("name").is_sorted()
# Overwrite problem dataframe
self.problem_df = df
def propagate_type_to_flatzinc(self) -> None:
"""Propagate the problem type to flatzinc dataframe."""
df = self.flatzinc_df.join(
self.problem_df.select("id", "type"),
left_on="problem.id",
right_on="id",
how="left",
)
df = df.rename({
"type": "problem.type",
})
self.flatzinc_df = df
def add_objective_bounds(self) -> None:
"""Add objective bounds to run and flatzinc dataframes."""
# Compute objective lower and upper bounds
df = self.event_df.group_by("run.id").agg(
pl.min("objective").alias("objective_lb"),
pl.max("objective").alias("objective_ub"),
)
# Join run, event, flatzinc and problem dataframes
df = self.run_df.join(
df,
left_on="id",
right_on="run.id",
how="left",
).join(
self.flatzinc_df.select("id", "problem.type"),
left_on="flatzinc.id",
right_on="id",
)
# Compute objective best and worst bounds
df = df.with_columns(
pl.when(pl.col("problem.type") == "minimize")
.then("objective_lb")
.otherwise("objective_ub")
.alias("objective_bb"),
pl.when(pl.col("problem.type") == "minimize")
.then("objective_ub")
.otherwise("objective_lb")
.alias("objective_wb"),
)
self.run_df = df.select(*self.run_df.columns, cs.starts_with("objective"))
assert self.run_df.get_column("id").is_sorted()
df = df.group_by("flatzinc.id", "problem.type").agg(
pl.min("objective_lb"),
pl.max("objective_ub"),
)
# Compute objective best and worst bounds
df = df.with_columns(
pl.when(pl.col("problem.type") == "minimize")
.then("objective_lb")
.otherwise("objective_ub")
.alias("objective_bb"),
pl.when(pl.col("problem.type") == "minimize")
.then("objective_ub")
.otherwise("objective_lb")
.alias("objective_wb"),
)
df = df.drop("problem.type")
df = self.flatzinc_df.join(
df,
left_on="id",
right_on="flatzinc.id",
how="left",
)
self.flatzinc_df = df
def add_num_solutions(self) -> None:
"""Add number of solutions to run dataframe."""
df = self.event_df.group_by("run.id").agg(
pl.max("num_solutions"),
)
df = self.run_df.join(
df,
left_on="id",
right_on="run.id",
how="left",
)
self.run_df = df
def add_objective_score(self) -> None:
"""Add objective score to run dataframe."""
df = self.run_df.join(
add_prefix(self.flatzinc_df.select("id", cs.starts_with("objective")), "flatzinc"),
on="flatzinc.id",
)
# Compute the objective score
df = df.with_columns(
(
(pl.col("objective_bb") - pl.col("flatzinc.objective_bb")).abs() /
(pl.col("flatzinc.objective_ub") - pl.col("flatzinc.objective_lb"))
).alias("objective_score"),
)
# Drop flatzinc objective values
df = df.drop(cs.starts_with("flatzinc.objective"))
self.run_df = df
def add_bounds(self, col: str) -> None:
"""Add bounds to run and flatzinc dataframes for a given column e.g. time.
It adds fsol and lsol in column name for first solution and last solution."""
# Only keep new solution events
event_df = self.event_df.filter(
pl.col("type") == "new_solution",
)
# Compute value of the first and last solution of a run
df = event_df.group_by("run.id").agg(
pl.min(col).alias(f"{col}_fsol"),
pl.max(col).alias(f"{col}_lsol"),
)
df = self.run_df.join(
df,
left_on="id",
right_on="run.id",
how="left",
)
self.run_df = df
# Compute value of the first and last solution of a flatzinc
df = self.run_df.group_by("flatzinc.id").agg(
pl.min(f"{col}_fsol").alias(f"{col}_fsol"),
pl.max(f"{col}_lsol").alias(f"{col}_lsol"),
)
df = self.flatzinc_df.join(
df,
left_on="id",
right_on="flatzinc.id",
how="left",
)
self.flatzinc_df = df
def add_auc_score(self, col: str, name: str = "auc_score") -> None:
"""Add area under the curve score to run dataframe.
The score represents the ratio between area under objective-time curve
and the area of the bounding box of all solution points in the same plot."""
# Extract column value, objective and run id for new solutions
df = self.event_df.filter(
pl.col("type") == "new_solution",
).select("run.id", col, "objective")
# Compute area under the curve
df = df.group_by("run.id").agg(
(pl.col("objective") * (pl.col(col) - pl.col(col).shift()))
.sum()
.alias("area_under_curve"),
)
# Extract interesting columns from run dataframe
run_df = self.run_df.select(
"id",
"flatzinc.id",
"objective_bb",
"objective_wb",
f"{col}_fsol",
f"{col}_lsol",
)
# Join on run dataframe
df = run_df.join(
df,
left_on="id",
right_on="run.id",
how="left",
)
# Compute rectangle area for flatzinc
flatzinc_df = self.flatzinc_df.select(
"id",
"problem.type",
"objective_ub",
"objective_lb",
f"{col}_fsol",
f"{col}_lsol",
).with_columns(
(
(pl.col("objective_ub") - pl.col("objective_lb"))
* (pl.col(f"{col}_lsol") - pl.col(f"{col}_fsol"))
).alias("rectangle_area")
)
# Join on flatzinc dataframe
df = df.join(
add_prefix(flatzinc_df, "flatzinc"),
on="flatzinc.id",
how="left",
)
# Check the run bounds are correct compared to flatzinc bounds
assert df.get_column(f"{col}_fsol").ge(df.get_column(f"flatzinc.{col}_fsol")).all()
assert df.get_column(f"{col}_lsol").le(df.get_column(f"flatzinc.{col}_lsol")).all()
assert df.get_column("objective_wb").ge(df.get_column("flatzinc.objective_lb")).all()
assert df.get_column("objective_bb").ge(df.get_column("flatzinc.objective_lb")).all()
assert df.get_column("objective_wb").le(df.get_column("flatzinc.objective_ub")).all()
assert df.get_column("objective_bb").le(df.get_column("flatzinc.objective_ub")).all()
# Compute area inside flatzinc rectangle
df = df.with_columns(
(
+ pl.col("area_under_curve")
+ (pl.col(f"{col}_fsol") - pl.col(f"flatzinc.{col}_fsol")) * pl.col("objective_wb")
+ (pl.col(f"flatzinc.{col}_lsol") - pl.col(f"{col}_lsol")) * pl.col("objective_bb")
- (pl.col(f"flatzinc.{col}_lsol") - pl.col(f"flatzinc.{col}_fsol")) * pl.col("flatzinc.objective_lb")
).alias("area"),
)
# Compute area ratio with the rectangle
df = df.with_columns(
(pl.col("area") / pl.col("flatzinc.rectangle_area")).alias("area_ratio"),
)
# Compute auc score using problem type
df = df.with_columns(
pl.when(pl.col("problem.type") == "minimize")
.then("area_ratio")
.otherwise(1.0 - pl.col("area_ratio"))
.alias(name),
)
df = df.select("id", name)
self.run_df = self.run_df.join(
df,
on="id",
how="left"
)
def improve(self) -> None:
"""Improve the dataframes by adding columns. This should only be called once."""
self.add_problem_type()
self.propagate_type_to_flatzinc()
self.add_objective_bounds()
self.add_num_solutions()
self.add_objective_score()
self.add_bounds("time")
self.add_bounds("num_decisions")
self.add_auc_score("time", "autc_score")
self.add_auc_score("num_decisions", "audc_score")
def make_subplots(
db: Database,
x_col: str,
y_col: str,
palette: list[str] = plotly.colors.qualitative.Plotly,
line_shape: str = "linear",
row_height: int = 200,
) -> go.Figure:
"""Return a figure containing one plot per flatzinc, one color per configuration."""
# Cast duration to avoid issue with duration
db_event_df = cast_duration(db.event_df)
# Prepare the colors for configurations
configurations = db.configuration_df.get_column("id")
num_configurations = configurations.count()
colors = [palette[i % len(palette)] for i in range(num_configurations)]
configuration_color = dict(zip(configurations, colors))
num_rows = len(db.problem_df)
num_cols = db.flatzinc_df.group_by("problem.id").agg(
pl.col("id").count().alias("count"),
).get_column("count").max()
figure = plotly.subplots.make_subplots(
rows=num_rows,
cols=num_cols,
subplot_titles=tuple(" " for _ in range(num_rows*num_cols)),
row_titles=list(db.problem_df.get_column("name")),
)
for i, problem_row in enumerate(db.problem_df.iter_rows()):
(problem_id, problem_name, problem_type, *_) = problem_row
print(f"Problem {problem_name}:")
flatzinc_df = db.flatzinc_df.filter(pl.col("problem.id") == problem_id)
for j, flatzinc_row in enumerate(flatzinc_df.iter_rows()):
flatzinc_id, flatzinc_name, *_ = flatzinc_row
print(f" - {flatzinc_name}")
for configuration_row in db.configuration_df.iter_rows():
configuration_id, configuration_name, *_ = configuration_row
run_df = db.run_df.filter(
pl.col("configuration.id") == configuration_id,
pl.col("flatzinc.id") == flatzinc_id,
)
# If no run available: skip
if len(run_df) == 0:
continue
# The run should be unique
assert len(run_df) == 1, f"several runs with configuration.id={configuration_id} and flatzinc.id={flatzinc_id}"
run_id = run_df.item(0,0)
event_df = db_event_df.filter(pl.col("run.id") == run_id)
color = configuration_color[configuration_id]
trace = go.Scatter(
x=event_df.get_column(x_col),
y=event_df.get_column(y_col),
showlegend=False,
line={"color": color, "shape": line_shape},
name=configuration_name,
mode="lines+markers",
)
figure.add_trace(trace, row=i+1, col=j+1)
# Add vertical line for end
# TODO use event type == end
max_x = event_df.get_column(x_col).max()
figure.add_vline(
x=max_x,
row=i+1,
col=j+1,
line={"color": color, "width": 1},
)
# Add vertical line for start
figure.add_vline(x=0, row=i+1, col=j+1)
# Add title to subplot
arrow = db.PROBLEM_TYPE_ARROW[problem_type]
subplot_title = f"{flatzinc_name} - {flatzinc_id}{arrow}"
k = i*num_cols + j
figure.layout.annotations[k].update(text=subplot_title)
print("")
figure.update_layout(
height=row_height*num_rows,
title=f"Subplots - x={x_col} y={y_col}",
)
return figure
def make_flatzinc_plot(
db: Database,
x_col: str,
y_col: str,
flatzinc_id: int,
palette: list[str] = plotly.colors.qualitative.Plotly,
line_shape: str = "linear",
) -> go.Figure:
"""Create a line plot for the given flatzinc."""
# Get flatzinc name and objective bound
flatzinc_df = db.flatzinc_df.filter(
pl.col("id") == flatzinc_id,
).select("name", "problem.id", "problem.type")
assert len(flatzinc_df) == 1
flatzinc_name, problem_id, problem_type = flatzinc_df.row(0)
# Get problem name
problem_name = db.problem_df.filter(
pl.col("id") == problem_id,
).select("name").item()
# Keep run on the given flatzinc
run_df = db.run_df.filter(
pl.col("flatzinc.id") == flatzinc_id,
)
# Only keep new solution points
df = db.event_df.filter(
pl.col("type") == "new_solution",
)
# Cast duration to avoid issue with serialization
df = cast_duration(df)
df = df.join(
run_df,
left_on="run.id",
right_on="id",
).join(
db.configuration_df.select("id", "name"),
left_on="configuration.id",
right_on="id",
).rename({
"name": "configuration.name",
})
figure = px.line(
data_frame=df,
x=x_col,
y=y_col,
color="configuration.name",
color_discrete_sequence=palette,
hover_name="configuration.name",
line_shape=line_shape,
markers=True,
title=f"{problem_name} - {flatzinc_name}",
subtitle=f"{flatzinc_id} - {problem_type}",
)
max_df = df.group_by("configuration.id", maintain_order=True).agg(
pl.max(x_col),
)
# Add vertical lines
# TODO use event type == end
for i, max_x in enumerate(max_df.get_column(x_col)):
color=palette[i % len(palette)]
figure.add_vline(
x=max_x,
line={"color": color, "width": 1},
)
# Global min and max on x and y axes
min_x = df.get_column(x_col).min()
max_x = df.get_column(x_col).max()
min_y = df.get_column(y_col).min()
max_y = df.get_column(y_col).max()
figure.add_shape(
type="rect",
x0=min_x,
y0=min_y,
x1=max_x,
y1=max_y,
layer="between",
line={"width": 1},
)
return figure
def make_heatmap_plot(
db: Database,
z_col: str,
palette: list[str] = plotly.colors.sequential.Plasma,
q0: float = 0.1,
q1: float = 0.9,
) -> go.Figure:
"""Create a heatmap configuration-flatzinc. The color is given by z_col from run dataframe ."""
# Control quantiles validity
assert 0.0 <= q0 and q0 <= 1.0
assert 0.0 <= q1 and q1 <= 1.0
assert q0 < q1
df = db.run_df.join(
add_prefix(db.configuration_df.select("id", "name"), "configuration"),
on="configuration.id",
).join(
add_prefix(db.flatzinc_df.select("id", "name", "problem.id"), "flatzinc"),
on="flatzinc.id",
).join(
add_prefix(db.problem_df.select("id", "name"), "problem"),
on="problem.id",
)
# Add info in flatzinc name: problem first letters and id
df = df.with_columns(
pl.format(
"{}. - {} - {}",
pl.col("problem.name").cast(pl.String).str.slice(0, 3),
"flatzinc.name",
"flatzinc.id"
).alias("flatzinc.name"),
)
# Cast duration to avoid issue with serialization
df = cast_duration(df)
num_flatzincs = len(db.flatzinc_df)
# Remove outliers via q0 and q1 for color bar
min_color = df.get_column(z_col).quantile(q0)
max_color = df.get_column(z_col).quantile(q1)
figure = px.density_heatmap(
df,
y="flatzinc.name",
x="configuration.name",
color_continuous_scale=palette,
z=z_col,
text_auto=True,
height=25*num_flatzincs,
range_color=(min_color,max_color),
)
# Set color bar title and change orientation
figure.update_coloraxes(colorbar={"title": z_col, "orientation":"h"})
# Disable hover
figure.update_traces(hoverinfo="skip", hovertemplate=None)
# Remove axis titles
figure.update_layout(xaxis_title=None, yaxis_title=None)
return figure
def make_box_plot(
db: Database,
y_col: str,
palette: list[str] = plotly.colors.qualitative.Plotly,
log: bool = False,
notched: bool = False,
) -> go.Figure:
"""Create a line plot for the given flatzinc."""
# Get configuration, flatzinc and problem name
df = db.run_df.join(
add_prefix(db.configuration_df.select("id", "name"), "configuration"),
on="configuration.id",
how="left",
).join(
add_prefix(db.flatzinc_df.select("id", "name", "problem.id"), "flatzinc"),
on="flatzinc.id",
how="left",
).join(
add_prefix(db.problem_df.select("id", "name"), "problem"),
on="problem.id",
how="left",
)
figure = px.box(
df,
x="configuration.name",
y=y_col,
color="configuration.name",
color_discrete_sequence=palette,
hover_data=["problem.name", "flatzinc.name", "flatzinc.id"],
points="all",
log_y=log,
notched=notched,
title="Box plot",
)
# Remove x-axis title
figure.update_layout(xaxis_title=None)
return figure
def check_column(column: str, df: pl.DataFrame, df_name: str) -> str:
"""Return an error message if column is not in the dataframe.
Otherwise it returns an empty string."""
message = ""
if column not in df.columns:
valid_values = ", ".join(df.columns)