-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_figures.py
More file actions
720 lines (638 loc) · 28.2 KB
/
Copy pathtest_figures.py
File metadata and controls
720 lines (638 loc) · 28.2 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
import numpy as np
import matplotlib
from matplotlib import pyplot as plt, _pylab_helpers
from functools import total_ordering
import math
import re
def assert_similar_figures(ref_fig, other_fig, attrs=None, tol=1e-5):
"""
Assert that two figures are similar.
Parameters:
ref_fig (matplotlib figure): The reference figure
other_fig (matplotlib figure): The figure to compare to the reference
Raises:
AssertionError if the figures are dissimilar
"""
if not isinstance(ref_fig, Figure):
ref_fig = Figure(ref_fig)
if not isinstance(other_fig, Figure):
other_fig = Figure(other_fig)
ref_fig.assert_similar(other_fig, attrs, tol=tol)
def capture_figures(func, *args, **kwargs):
"""
Runs a function which generates figures (where the function doesn't return
the figures), gets a handle to the figures and returns them.
Parameters:
func (callable): The function which generates figures
Returns:
Tuple[matplotlib.figure.Figure,...]: Handles to the figures generated by the
function
"""
# Keep track of the original figures
original_figs = _pylab_helpers.Gcf.figs.copy()
# determine if matplotlib is in interactive mode
interactive = matplotlib.is_interactive()
# Turning interactive mode on means plt.show() is non-blocking,
# and won't clear the active figures on calling plt.show()
if not interactive:
plt.ion()
# close existing figures, so that we don't get confused by them
plt.close("all")
# call the function which generates the figures
try:
returns = func(*args, **kwargs)
except Exception as err:
print(err)
raise Exception(err)
# get handles to the figures
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
figs = []
for fig_manager in fig_managers:
figs.append(fig_manager.canvas.figure)
# restore interactive mode to its original state
if not interactive:
plt.ioff()
# reset the figure manager to its original state, as if we
# were never here
_pylab_helpers.Gcf.figs = original_figs
# we're done!
return tuple(figs), returns
def get_active_figures():
"""
Get all the figures currently managed by matplotlib
Parameters:
None
Returns:
Tuple[matplotlib.figure.Figure, ...]: Handles to
the figures managed by matplotlib
"""
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
figs = []
for fig_manager in fig_managers:
figs.append(fig_manager.canvas.figure)
return tuple(figs)
class FigureOutput:
""" Handles writing figures to a file """
def __init__(self, file_name):
self.figs = []
self.file_name = file_name
def write_to_file(self, fig, fig_name):
self.figs.append((fig, fig_name))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
with open(self.file_name, "w", encoding="utf-8") as f:
f.write("from autograder.matplotlib_figure_testing.test_figures import *\n")
f.write("from matplotlib.text import Text\n")
f.write("from matplotlib.path import Path\n")
f.write("from numpy import array as array\n")
f.write("from numpy import uint8, float64\n")
f.write("import numpy as np\n")
f.write("\n")
for fig, fig_name in self.figs:
f.write(f"{fig_name} = {Figure(fig)}")
f.write("\n")
class Figure:
"""Representation of a matplotlib figure object"""
all_attrs = ("suptitle", "has_suptitle", "sup_ylabel", "sup_xlabel", "size")
def __init__(self, fig):
if isinstance(fig, dict):
self.size = fig.get("size")
self.suptitle = fig.get("suptitle")
self.sup_xlabel = fig.get("sup_xlabel", None)
self.sup_ylabel = fig.get("sup_ylabel", None)
self.has_suptitle = fig.get("has_suptitle", False)
self.axes = [axis for axis in fig["axes"]]
else:
self.size = fig.get_figwidth(), fig.get_figheight()
sup_title = fig._suptitle
self.sup_xlabel = fig._supxlabel
self.sup_ylabel = fig._supylabel
if sup_title:
self.suptitle = fig._suptitle.get_text()
self.has_suptitle = True
else:
self.suptitle = ""
self.has_suptitle = False
self.axes = [Axis(axis) for axis in fig.get_axes()]
def get_num_axes(self):
"""Returns the number of axes in the figure"""
return len(self.axes)
def assert_similar(self, other, attrs=None, tol=None):
"""Assert that the Figure is similar to another figure"""
test_attrs = self.all_attrs if not attrs else attrs
if self.get_num_axes() != other.get_num_axes():
raise AssertionError(f"Incorrect number of axes (subfigures). "
f"Expected {self.get_num_axes()}, "
f"found {other.get_num_axes()}")
for attr in set(self.all_attrs).intersection(test_attrs):
correct = True
if attr in ("sup_xlabel", "sup_ylabel"):
if not check_text_equal(getattr(self, attr),
getattr(other, attr),
tol=tol):
correct = False
elif getattr(self, attr) != getattr(other, attr):
correct = False
if not correct:
raise AssertionError(f"Incorrect {attr}. "
f"Expected {getattr(self, attr)}, "
f"found {getattr(other, attr)} \n")
for axis, other_axis in zip(self.axes, other.axes):
axis.assert_similar(other_axis, attrs, tol=tol)
def __repr__(self):
axis_repr = repr(list([axis for axis in self.axes]))
rep = "Figure({\n"
rep += f' "size": {self.size},\n'
rep += f' "suptitle": """{self.suptitle}""", \n'
rep += f' "has_suptitle": {self.has_suptitle},\n'
rep += f' "sup_xlabel": {self.sup_xlabel},\n'
rep += f' "sup_ylabel": {self.sup_ylabel},\n'
rep += f' "axes": {axis_repr}\n'
rep += "})"
return rep
def common_element(test_tuple, ref_tuple):
""" Return True if an element in `test_tuple` is in `ref_tuple`
otherwise return False"""
for i in test_tuple:
if i in ref_tuple:
return True
return False
class Axis:
"""Representation of a matplotlib axes object"""
all_attrs = ("title", "has_title", "xlabel", "has_xlabel", "ylabel", "has_ylabel",
"xtick_label", "ytick_label", "x_scale", "y_scale", "legend_entries",
"num_legend_entries", "has_legend", "grid_spec", "sharex", "sharey")
def __init__(self, ax):
if isinstance(ax, dict):
# We need to create an axis from a dictionary
self.title = ax.get("title")
self.has_title = ax.get("has_title")
self.xlabel = ax.get("xlabel")
self.has_xlabel = ax.get("has_xlabel", False)
self.ylabel = ax.get("ylabel")
self.has_ylabel = ax.get("has_ylabel", False)
self.xtick_label = ax.get("xtick_label")
self.ytick_label = ax.get("ytick_label")
self.x_scale = ax.get("x_scale")
self.y_scale = ax.get("y_scale")
self.legend_entries = ax.get("legend_entries")
self.num_legend_entries = ax.get("num_legend_entries")
self.has_legend = ax.get("has_legend")
self.grid_spec = ax.get("grid_spec")
self.sharey = ax.get("sharey")
self.sharex = ax.get("sharex")
# sort the lines, path_collections and patches, so that
# the order that they get plotted in doesn't matter
self.lines = sorted([line for line in ax.get("lines")])
self.path_collections = sorted([PathCollection(pc)
for pc in ax.get("path_collections", [])])
self.patches = sorted([patch for patch in ax.get("patches", [])])
else:
# we need to create an axis from a matplotlib axis
self.title = ax.get_title()
self.has_title = False if self.title == "" else True
self.xlabel = ax.get_xaxis().get_label().get_text()
self.has_xlabel = False if self.xlabel == "" else True
self.ylabel = ax.get_yaxis().get_label().get_text()
self.has_ylabel = False if self.ylabel == "" else True
self.xtick_label = ax.get_xaxis().get_ticklabels()
self.ytick_label = ax.get_yaxis().get_ticklabels()
self.x_scale = ax.get_xscale()
self.y_scale = ax.get_yscale()
if ax._sharex:
self.sharex = ax.get_figure().get_axes().index(ax._sharex)
else:
self.sharex = None
if ax._sharey:
self.sharey = ax.get_figure().get_axes().index(ax._sharey)
else:
self.sharey = None
legend = ax.get_legend()
if legend:
self.legend_entries = [entry for entry in
ax.get_legend().get_texts()]
self.num_legend_entries = len(self.legend_entries)
self.has_legend = True
else:
self.legend_entries = [None]
self.num_legend_entries = 0
self.has_legend = False
self.grid_spec = ax.get_gridspec().get_geometry()
# sort the lines, path_collections and patches, so that
# the order that they get plotted in doesn't matter
self.lines = sorted([Line(line) for line in ax.get_lines() if line.get_xdata().size!=0])
self.path_collections = sorted([PathCollection(pc)
for pc in ax.collections])
self.patches = sorted([create_patch(patch) for patch in ax.patches])
def get_num_pc(self):
"""Return the number of path_collections"""
return len(self.path_collections)
def get_num_lines(self):
"""Get the number of lines on the axis"""
return len(self.lines)
def get_num_patches(self):
"""Get the number of patches"""
return len(self.patches)
def __repr__(self):
rep = "Axis({\n"
rep += f' "title": """{self.title}""", \n'
rep += f' "has_title": {self.has_title}, \n'
rep += f' "xlabel": """{self.xlabel}""", \n'
rep += f' "has_xlabel": {self.has_xlabel}, \n'
rep += f' "ylabel": """{self.ylabel}""", \n'
rep += f' "has_ylabel": {self.has_ylabel}, \n'
rep += f' "sharex": {self.sharex},\n'
rep += f' "sharey": {self.sharey},\n'
rep += f' "xtick_label": {self.xtick_label}, \n'
if self.ytick_label:
rep += f' "ytick_label": {self.ytick_label}, \n'
rep += f' "x_scale": """{self.x_scale}""", \n'
rep += f' "y_scale": """{self.y_scale}""", \n'
rep += f' "legend_entries": {repr(self.legend_entries)}, \n'
rep += f' "has_legend": {self.has_legend}, \n'
rep += f' "num_legend_entries": {self.num_legend_entries},\n'
rep += f' "grid_spec": {self.grid_spec}, \n'
lines_repr = repr([line for line in self.lines])
rep += ' "lines": ' + f"{lines_repr},\n"
pc_repr = repr([pc for pc in self.path_collections])
rep += f' "path_collections": {pc_repr},\n'
patch_repr = repr([patch for patch in self.patches])
rep += f' "patches": {patch_repr},\n'
rep += " })\n"
return rep
def assert_similar(self, other, attrs=None, tol=None):
"""Assert that the axis is similar to another axis"""
test_attrs = self.all_attrs if not attrs else attrs
# test all the attributes that relate to an axes
for attr in set(test_attrs).intersection(self.all_attrs):
if attr in ["xtick_label", "ytick_label", "legend_entries"]:
# It seems that matplotlib.text.Text doesn't implement __eq__
# so here we are doing matplotlib's job for them...
for text, text_ref in zip(getattr(self, attr),
getattr(other, attr)):
if not check_text_equal(text, text_ref):
raise AssertionError(f"Incorrect {attr}: "
f"'{getattr(other, attr)}', "
f"Expected '{getattr(self, attr)}'")
elif getattr(self, attr) != getattr(other, attr):
raise AssertionError(f"Incorrect {attr}, "
f"'{getattr(other, attr)}'. "
f"Expected '{getattr(self, attr)}'")
if attrs is None or common_element(attrs, Line.all_attrs):
# check that the lines are similar. The lines may be in a different order
if self.get_num_lines() != other.get_num_lines():
raise AssertionError(f"Incorrect number of lines. "
f"Expected {self.get_num_lines()}, "
f"found {other.get_num_lines()}")
for line, other_line in zip(self.lines, other.lines):
line.assert_similar(other_line, attrs, tol=tol)
if attrs is None or common_element(attrs, PathCollection.all_attrs):
# check that the path collections are similar
if self.get_num_pc() != other.get_num_pc():
raise AssertionError(f"Incorrect number of items in the"
f"scatter plot. Expected {self.get_num_pc()} "
f"found {other.get_num_pc()}")
for pc, other_pc in zip(self.path_collections, other.path_collections):
pc.assert_similar(other_pc, attrs, tol=tol)
if attrs is None or common_element(attrs, Wedge.all_attrs) or common_element(attrs, Rectangle.all_attrs):
# check that the patches are similar
if self.get_num_patches() != other.get_num_patches():
raise AssertionError("Incorrect number of patches "
f"Expected {self.get_num_patches()} "
f"but got {other.get_num_patches()}")
for patch, other_patch in zip(self.patches, other.patches):
patch.assert_similar(other_patch, attrs, tol=tol)
def create_patch(patch):
if isinstance(patch, matplotlib.patches.Wedge):
return Wedge(patch)
elif isinstance(patch, matplotlib.patches.Rectangle):
return Rectangle(patch)
elif isinstance(patch, matplotlib.patches.Circle):
return Circle(patch)
class Patch:
"""
Representation of a matplotlib patch
"""
def check_similar(self, other, attrs=None, tol=None):
test_attrs = self.all_attrs if not attrs else attrs
if self.patch_type != other.patch_type:
msg = f"Incorrect shape. Expected {self.patch_type}, got {other.patch_type}"
return False, msg
test_attrs = self.all_attrs if not attrs else attrs
for attr in set(test_attrs).intersection(self.all_attrs):
if not math.isclose(getattr(self, attr), getattr(other, attr)):
msg = f"Incorrect {self.patch_type} {attr}: {getattr(other, attr)}. "
msg += f"Expected {getattr(self, attr)}"
return False, msg
return True, None
def assert_similar(self, other, attrs=None, tol=None):
test_attrs = self.all_attrs if not attrs else attrs
similar, msg = self.check_similar(other, test_attrs, tol=tol)
if not similar:
raise AssertionError(msg)
def __eq__(self, other):
similar, _ = self.check_similar(other)
return similar
def __gt__(self, other):
for attr in self.all_attrs:
if getattr(self, attr) > getattr(other, attr):
return True
elif getattr(self, attr) < getattr(other, attr):
return False
return False
@total_ordering
class Rectangle(Patch):
"""
Representation of a matplotlib Rectangle patch
"""
patch_type = "rectangle"
all_attrs = ("position_x", "height", "width", "position_y")
def __init__(self, rectangle):
if isinstance(rectangle, dict):
self.height = rectangle.get("height")
self.width = rectangle.get("width")
self.position_x, self.position_y = rectangle.get("position_x"), rectangle.get("position_y")
else:
self.height = rectangle.get_height()
self.width = rectangle.get_width()
self.position_x, self.position_y = rectangle.get_xy()
def __repr__(self):
rep = "Rectangle({"
rep += f"'height': {self.height}, "
rep += f"'width': {self.width}, "
rep += f"'position_x': {self.position_x}, "
rep += f"'position_y': {self.position_y}, "
rep += "})"
return rep
@total_ordering
class Wedge(Patch):
"""
Representation of a matplotlib Wedge patch
"""
patch_type = "wedge"
all_attrs = ("theta", "r", "theta1", "theta2", "center_x", "center_y")
def __init__(self, wedge):
if isinstance(wedge, dict):
self.r = wedge.get("r")
self.theta1 = wedge.get("theta1")
self.theta2 = wedge.get("theta2")
self.center_x, self.center_y = wedge.get("center_x"), wedge.get("center_y")
self.theta = abs(self.theta1 - self.theta2)
else:
self.r = wedge.r
self.theta1 = wedge.theta1
self.theta2 = wedge.theta2
self.center_x, self.center_y = wedge.center
self.theta = abs(wedge.theta1 - wedge.theta2)
def __repr__(self):
rep = "Wedge({"
rep += f"'r': {self.r}, "
rep += f"'theta1': {self.theta1}, "
rep += f"'theta2': {self.theta2}, "
rep += f"'theta': {self.theta}, "
rep += f"'center_x': {self.center_x}, "
rep += f"'center_y': {self.center_y}"
rep += "})"
return rep
@total_ordering
class Circle(Patch):
"""
Representation of a matplotlib Circle patch
"""
patch_type = "circle"
all_attrs = ("radius", "center_x", "center_y")
def __init__(self, circle):
if isinstance(circle, dict):
self.radius = circle.get("radius")
self.center_x, self.center_y = circle.get("center_x"), circle.get("center_y")
else:
self.radius = circle.radius
self.center_x, self.center_y = circle.center
def __repr__(self):
rep = "Circle({"
rep += f"'radius': {self.radius}, "
rep += f"'center_x': {self.center_x}, "
rep += f"'center_y': {self.center_y}"
rep += "})"
return rep
@total_ordering
class PathCollection:
"""
Representation of a matplotlib PathCollection object.
In matplotlib, PathCollection is used to define the
data in a scatter plot
"""
all_attrs = ("x_data", "y_data", "marker")
def __init__(self, pc):
if isinstance(pc, dict):
self.x_data = pc.get("x_data")
self.y_data = pc.get("y_data")
self.marker = pc.get("marker")
else:
data = pc.get_offsets().data
self.x_data = data[:, 0]
self.y_data = data[:, 1]
self.marker = pc.get_paths()[0]
def __repr__(self):
rep = f' {{"x_data": np.{repr(self.x_data)}, \n'
rep += f' "y_data": np.{repr(self.y_data)}, \n'
rep += f' "marker": {self.marker} }}'
return rep
def __eq__(self, other):
eq, _ = self.check_similar(other)
if eq:
return True
return False
def __gt__(self, other):
if self.marker.vertices.tolist() > other.marker.vertices.tolist():
return True
if self.marker.vertices.tolist() < other.marker.vertices.tolist():
return False
if list(self.x_data) > list(other.x_data):
return True
if list(self.x_data) < list(other.x_data):
return False
if list(self.y_data) > list(other.y_data):
return True
if list(self.y_data) < list(other.y_data):
return False
return False
def check_similar(self, other, attrs=None, tol=None):
""" Check if two PathCollections are similar """
test_attrs = self.all_attrs if not attrs else attrs
for attr in set(test_attrs).intersection(self.all_attrs):
if attr in ("x_data", "y_data"):
try:
data_correct = np.allclose(getattr(self, attr),
getattr(other, attr),
atol=tol)
except ValueError:
data_correct = False
if not data_correct:
msg = "Scatter plot has points in the wrong place"
return False, msg
elif attr == "marker":
try:
vert_correct = np.allclose(self.marker.vertices,
other.marker.vertices,
atol=tol)
code_correct = np.allclose(self.marker.vertices,
other.marker.vertices,
atol=tol)
marker_correct = vert_correct and code_correct
except ValueError:
marker_correct = False
if not marker_correct:
return False, "Incorrect marker in scatter plot"
return True, None
def assert_similar(self, other, attrs=None, tol=None):
""" Assert two PathCollections are similar """
test_attrs = self.all_attrs if not attrs else attrs
similar, msg = self.check_similar(other, test_attrs, tol=tol)
if not similar:
raise AssertionError(msg)
def numpy_array_gt(array1, array2):
for i, j in zip(array1, array2):
if i > j:
return True
if i < j:
return False
return False
def numpy_array_lt(array1, array2):
for i, j in zip(array1, array2):
if i < j:
return True
if i > j:
return False
return False
@total_ordering
class Line:
"""Representation of a matplotlib line object"""
all_attrs = ("x_data", "y_data", "linewidth",
"linestyle", "marker", "colour", "label")
def __init__(self, line):
if isinstance(line, dict):
# we need to create a line from a dictionary
self.x_data = line.get("x_data")
self.y_data = line.get("y_data")
self.linewidth = line.get("linewidth", 1.5)
self.linestyle = line.get("linestyle", "")
self.marker = line.get("marker", "")
self.colour = line.get("colour", "")
self.label = line.get("label", "")
else:
# we probably have a matplotlib figure
self.x_data = line.get_xdata()
self.y_data = line.get_ydata()
self.linewidth = line.get_linewidth()
self.linestyle = line.get_linestyle()
self.marker = line.get_marker()
self.colour = matplotlib.colors.to_hex(line.get_color())
self.label = line.get_label()
# the default label seems to be _child0, _child1,...
# so if the label matches that pattern,
# set the label to an empty string
if re.match(r"^_child[0-9]+$", self.label):
self.label = ""
def __repr__(self):
rep = "Line({\n"
rep += f' "x_data": np.{repr(self.x_data)}, \n'
rep += f' "y_data": np.{repr(self.y_data)}, \n'
rep += f' "linewidth": {self.linewidth}, \n'
rep += f' "linestyle": "{self.linestyle}", \n'
rep += f' "marker": "{self.marker}", \n '
rep += f' "colour": "{self.colour}",\n'
rep += f' "label": "{self.label}",\n'
rep += " })"
return rep
def __eq__(self, other):
similar, _ = self.check_similar(other)
return similar
def __gt__(self, other):
if numpy_array_gt(self.x_data, other.x_data):
return True
if numpy_array_lt(self.x_data, other.x_data):
return False
if numpy_array_gt(self.y_data, other.y_data):
return True
if numpy_array_lt(self.y_data, other.y_data):
return False
if self.label > other.label:
return True
if self.label < other.label:
return False
if self.colour > other.colour:
return True
if self.colour < other.colour:
return False
if self.linewidth > other.linewidth:
return True
if self.linewidth < other.linewidth:
return False
if self.linestyle > other.linestyle:
return True
if self.linestyle < other.linestyle:
return False
if (self.marker is not None) and (other.marker is not None) and (self.marker > other.marker):
return True
if (self.marker is not None) and (other.marker is not None) and (self.marker < other.marker):
return False
return False
def check_similar(self, other, attrs=None, tol=None):
""" Check if two lines are similar """
test_attrs = self.all_attrs if not attrs else attrs
# test all the attributes that relate to a line
for attr in set(test_attrs).intersection(self.all_attrs):
if attr in ("x_data", "y_data"):
# we have numeric data, so should test if close
# use a try except block to catch when allclose errors
# for example when the data are different lengths
data = getattr(self, attr)
try:
if type(data) == np.ndarray and data.dtype == 'datetime64[us]':
data_correct = np.all(data == getattr(other, attr))
else:
data_correct = np.allclose(
data, getattr(other, attr), atol=tol
)
except:
data_correct = False
if not data_correct:
msg = f"A line (colour='{self.colour}', "
msg += f"label='{self.label}', "
msg += f"marker='{self.marker}', "
msg += f"linestyle='{self.linestyle}', "
msg += f"linewidth={self.linewidth}) "
msg += "isn't where it should be\n"
msg += f"Expected {attr}: {getattr(self, attr)}\n"
msg += f"But got {getattr(other, attr)}\n"
return False, msg
else:
# we have non numeric data, so can test exactly
if getattr(self, attr) != getattr(other, attr):
msg = f"Incorrect {attr}, '{getattr(other, attr)}'."
msg += f"Expected '{getattr(self, attr)}'"
return False, msg
return True, None
def assert_similar(self, other, attrs=None, tol=None):
"""Assert that the line is similar to another line"""
test_attrs = self.all_attrs if not attrs else attrs
similar, msg = self.check_similar(other, test_attrs, tol=tol)
if not similar:
raise AssertionError(msg)
def check_text_equal(text, ref_text, tol=None):
"""Check if two matplotlib.text.Text objects are equal"""
if text is None and ref_text is None:
return True
if text is None and ref_text is not None:
return False
if ref_text is None and text is not None:
return False
if text.get_position() != ref_text.get_position():
return False
if text.get_text() != ref_text.get_text():
return False
if text.get_size() != ref_text.get_size():
return False
return True