-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaft.py
1430 lines (1134 loc) · 42.3 KB
/
daft.py
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
# -*- coding: utf-8 -*-
"""Code for Daft"""
__all__ = ["PGM", "Node", "Edge", "Plate"]
from pkg_resources import get_distribution, DistributionNotFound
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.patches import FancyArrow
from matplotlib.patches import Rectangle
import numpy as np
try:
__version__ = get_distribution("daft").version
except DistributionNotFound:
pass
# pylint: disable=too-many-arguments, protected-access, unused-argument, too-many-lines
class PGM(object):
"""
The base object for building a graphical model representation.
:param shape: (optional)
The number of rows and columns in the grid. Will automatically
determine is not provided.
:param origin: (optional)
The coordinates of the bottom left corner of the plot. Will
automatically determine if not provided.
:param grid_unit: (optional)
The size of the grid spacing measured in centimeters.
:param node_unit: (optional)
The base unit for the node size. This is a number in centimeters that
sets the default diameter of the nodes.
:param observed_style: (optional)
How should the "observed" nodes be indicated? This must be one of:
``"shaded"``, ``"inner"`` or ``"outer"`` where ``inner`` and
``outer`` nodes are shown as double circles with the second circle
plotted inside or outside of the standard one, respectively.
:param alternate_style: (optional)
How should the "alternate" nodes be indicated? This must be one of:
``"shaded"``, ``"inner"`` or ``"outer"`` where ``inner`` and
``outer`` nodes are shown as double circles with the second circle
plotted inside or outside of the standard one, respectively.
:param node_ec: (optional)
The default edge color for the nodes.
:param node_fc: (optional)
The default face color for the nodes.
:param plate_fc: (optional)
The default face color for plates.
:param directed: (optional)
Should the edges be directed by default?
:param aspect: (optional)
The default aspect ratio for the nodes.
:param label_params: (optional)
Default node label parameters. See :class:`PGM.Node` for details.
:param dpi: (optional)
Set DPI for display and saving files.
"""
def __init__(
self,
shape=None,
origin=None,
grid_unit=2.0,
node_unit=1.0,
observed_style="shaded",
alternate_style="inner",
line_width=1.0,
node_ec="k",
node_fc="w",
plate_fc="w",
directed=True,
aspect=1.0,
label_params=None,
dpi=None,
):
self._nodes = {}
self._edges = []
self._plates = []
self._dpi = dpi
# if shape and origin are not given, pass a default
# and we will determine at rendering time
self.shape = shape
self.origin = origin
if shape is None:
shape = [1, 1]
if origin is None:
origin = [0, 0]
self._ctx = _rendering_context(
shape=shape,
origin=origin,
grid_unit=grid_unit,
node_unit=node_unit,
observed_style=observed_style,
alternate_style=alternate_style,
line_width=line_width,
node_ec=node_ec,
node_fc=node_fc,
plate_fc=plate_fc,
directed=directed,
aspect=aspect,
label_params=label_params,
dpi=dpi,
)
def __enter__(self):
return self
def __exit__(self, *args):
self._ctx.close()
def add_node(
self,
node,
content="",
x=0,
y=0,
scale=1.0,
aspect=None,
observed=False,
fixed=False,
alternate=False,
offset=(0.0, 0.0),
fontsize=None,
plot_params=None,
label_params=None,
shape="ellipse",
):
"""
Add a :class:`Node` to the model.
:param node:
The plain-text identifier for the nodeself.
Can also be the :class:`Node` to retain backward compatibility.
:param content:
The display form of the variable.
:param x:
The x-coordinate of the node in *model units*.
:param y:
The y-coordinate of the node.
:param scale: (optional)
The diameter (or height) of the node measured in multiples of
``node_unit`` as defined by the :class:`PGM` object.
:param aspect: (optional)
The aspect ratio width/height for elliptical nodes; default 1.
:param observed: (optional)
Should this be a conditioned variable?
:param fixed: (optional)
Should this be a fixed (not permitted to vary) variable?
If `True`, modifies or over-rides ``diameter``, ``offset``,
``facecolor``, and a few other ``plot_params`` settings.
This setting conflicts with ``observed``.
:param alternate: (optional)
Should this use the alternate style?
:param offset: (optional)
The ``(dx, dy)`` offset of the label (in points) from the default
centered position.
:param fontsize: (optional)
The fontsize to use.
:param plot_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.patches.Ellipse` constructor.
:param label_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.text.Annotation` constructor. Any kwargs not
used by Annontation get passed to :class:`matplotlib.text.Text`.
:param shape: (optional)
String in {ellipse (default), rectangle}
If rectangle, aspect and scale holds for rectangle
"""
if isinstance(node, Node):
_node = node
else:
_node = Node(
node,
content,
x,
y,
scale,
aspect,
observed,
fixed,
alternate,
offset,
fontsize,
plot_params,
label_params,
shape,
)
self._nodes[_node.name] = _node
return node
def add_edge(
self,
name1,
name2,
directed=None,
xoffset=0.0,
yoffset=0.1,
label=None,
plot_params=None,
label_params=None,
**kwargs # pylint: disable=unused-argument
):
"""
Construct an :class:`Edge` between two named :class:`Node` objects.
:param name1:
The name identifying the first node.
:param name2:
The name identifying the second node. If the edge is directed,
the arrow will point to this node.
:param directed: (optional)
Should the edge be directed from ``node1`` to ``node2``? In other
words: should it have an arrow?
:param label: (optional)
A string to annotate the edge.
:param xoffset: (optional)
The x-offset from the middle of the arrow to plot the label.
Only takes effect if `label` is defined in `plot_params`.
:param yoffset: (optional)
The y-offset from the middle of the arrow to plot the label.
Only takes effect if `label` is defined in `plot_params`.
:param plot_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.patches.FancyArrow` constructor.
:param label_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.axes.Axes.annotate` constructor.
"""
if directed is None:
directed = self._ctx.directed
e = Edge(
self._nodes[name1],
self._nodes[name2],
directed=directed,
label=label,
xoffset=xoffset,
yoffset=yoffset,
plot_params=plot_params,
label_params=label_params,
)
self._edges.append(e)
return e
def add_plate(
self,
plate,
label=None,
label_offset=(5, 5),
shift=0,
position="bottom left",
fontsize=None,
rect_params=None,
bbox=None,
):
"""
Add a :class:`Plate` object to the model.
:param plate:
The rectangle describing the plate bounds in model coordinates.
Can also be the :class:`Plate` to retain backward compatibility.
:param label: (optional)
A string to annotate the plate.
:param label_offset: (optional)
The x and y offsets of the label text measured in points.
:param shift: (optional)
The vertical "shift" of the plate measured in model units. This
will move the bottom of the panel by ``shift`` units.
:param position: (optional)
One of ``"{vertical} {horizontal}"`` where vertical is ``"bottom"``
or ``"middle"`` or ``"top"`` and horizontal is ``"left"`` or
``"center"`` or ``"right"``.
:param fontsize: (optional)
The fontsize to use.
:param rect_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.patches.Rectangle` constructor.
"""
if isinstance(plate, Plate):
_plate = plate
else:
_plate = Plate(
plate,
label,
label_offset,
shift,
position,
fontsize,
rect_params,
bbox,
)
self._plates.append(_plate)
def add_text(self, x, y, label, fontsize=None):
"""
A subclass of plate to writing text using grid coordinates. Any
``**kwargs`` are passed through to :class:`PGM.Plate`.
:param x:
The x-coordinate of the text in *model units*.
:param y:
The y-coordinate of the text.
:param label:
A string to write.
:param fontsize: (optional)
The fontsize to use.
"""
text = Text(x=x, y=y, label=label, fontsize=fontsize)
self._plates.append(text)
return None
def render(self, dpi=None):
"""
Render the :class:`Plate`, :class:`Edge` and :class:`Node` objects in
the model. This will create a new figure with the correct dimensions
and plot the model in this area.
:param dpi: (optional)
The DPI value to use for rendering.
"""
if dpi is None:
self._ctx.dpi = self._dpi
else:
self._ctx.dpi = dpi
def get_max(maxsize, artist):
if isinstance(artist, Ellipse):
maxsize = np.maximum(
maxsize,
artist.center
+ np.array([artist.width, artist.height]) / 2,
dtype=np.float64,
)
elif isinstance(artist, Rectangle):
maxsize = np.maximum(
maxsize,
np.array([artist._x0, artist._y0], dtype=np.float64)
+ np.array([artist._width, artist._height]),
dtype=np.float64,
)
return maxsize
def get_min(minsize, artist):
if isinstance(artist, Ellipse):
minsize = np.minimum(
minsize,
artist.center
- np.array([artist.width, artist.height]) / 2,
dtype=np.float64,
)
elif isinstance(artist, Rectangle):
minsize = np.minimum(
minsize,
np.array([artist._x0, artist._y0], dtype=np.float64),
)
return minsize
# Auto-set shape
# We pass through each object once to find the maximum coordinates
if self.shape is None:
maxsize = np.copy(self._ctx.origin)
for plate in self._plates:
artist = plate.render(self._ctx)
maxsize = get_max(maxsize, artist)
for name in self._nodes:
if self._nodes[name].fixed:
self._nodes[name].offset[1] -= 12.5
artist = self._nodes[name].render(self._ctx)
maxsize = get_max(maxsize, artist)
self._ctx.reset_shape(maxsize)
# Pass through each object to find the minimum coordinates
if self.origin is None:
minsize = np.copy(self._ctx.shape * self._ctx.grid_unit)
for plate in self._plates:
artist = plate.render(self._ctx)
minsize = get_min(minsize, artist)
for name in self._nodes:
artist = self._nodes[name].render(self._ctx)
minsize = get_min(minsize, artist)
self._ctx.reset_origin(minsize, self.shape is None)
# Clear the figure from rendering context
self._ctx.reset_figure()
for plate in self._plates:
plate.render(self._ctx)
for edge in self._edges:
edge.render(self._ctx)
for name in self._nodes:
self._nodes[name].render(self._ctx)
return self.ax
@property
def figure(self):
"""Figure as a property."""
return self._ctx.figure()
@property
def ax(self):
"""Axes as a property."""
return self._ctx.ax()
def show(self, *args, dpi=None, **kwargs):
"""
Wrapper on :class:`PGM.render()` that calls `matplotlib.show()`
immediately after.
:param dpi: (optional)
The DPI value to use for rendering.
"""
self.render(dpi=dpi)
plt.show(*args, **kwargs)
def savefig(self, fname, *args, **kwargs):
"""
Wrapper on ``matplotlib.Figure.savefig()`` that sets default image
padding using ``bbox_inchaes = tight``.
``*args`` and ``**kwargs`` are passed to `matplotlib.Figure.savefig()`.
:param fname:
The filename to save as.
:param dpi: (optional)
The DPI value to use for saving.
"""
kwargs["bbox_inches"] = kwargs.get("bbox_inches", "tight")
kwargs["dpi"] = kwargs.get("dpi", self._dpi)
if not self.figure:
self.render()
self.figure.savefig(fname, *args, **kwargs)
class Node(object):
"""
The representation of a random variable in a :class:`PGM`.
:param name:
The plain-text identifier for the node.
:param content:
The display form of the variable.
:param x:
The x-coordinate of the node in *model units*.
:param y:
The y-coordinate of the node.
:param scale: (optional)
The diameter (or height) of the node measured in multiples of
``node_unit`` as defined by the :class:`PGM` object.
:param aspect: (optional)
The aspect ratio width/height for elliptical nodes; default 1.
:param observed: (optional)
Should this be a conditioned variable?
:param fixed: (optional)
Should this be a fixed (not permitted to vary) variable?
If `True`, modifies or over-rides ``diameter``, ``offset``,
``facecolor``, and a few other ``plot_params`` settings.
This setting conflicts with ``observed``.
:param alternate: (optional)
Should this use the alternate style?
:param offset: (optional)
The ``(dx, dy)`` offset of the label (in points) from the default
centered position.
:param fontsize: (optional)
The fontsize to use.
:param plot_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.patches.Ellipse` constructor.
:param label_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.text.Annotation` constructor. Any kwargs not
used by Annontation get passed to :class:`matplotlib.text.Text`.
:param shape: (optional)
String in {ellipse (default), rectangle}
If rectangle, aspect and scale holds for rectangle.
"""
def __init__(
self,
name,
content,
x,
y,
scale=1.0,
aspect=None,
observed=False,
fixed=False,
alternate=False,
offset=(0.0, 0.0),
fontsize=None,
plot_params=None,
label_params=None,
shape="ellipse",
):
# Check Node style.
# Iterable is consumed, so first condition checks if two or more are
# true
node_style = iter((observed, alternate, fixed))
test = (any(node_style) and not any(node_style)) or not any(
(observed, alternate, fixed)
)
assert (
test
), "A node cannot be more than one of `observed`, `fixed`, or `alternate`."
self.observed = observed
self.fixed = fixed
self.alternate = alternate
# Metadata.
self.name = name
self.content = content
# Coordinates and dimensions.
self.x, self.y = float(x), float(y)
self.scale = float(scale)
if self.fixed:
self.scale /= 6.0
if aspect is not None:
self.aspect = float(aspect)
else:
self.aspect = aspect
# Set fontsize
self.fontsize = fontsize if fontsize else mpl.rcParams["font.size"]
# Display parameters.
self.plot_params = dict(plot_params) if plot_params else {}
# Text parameters.
self.offset = list(offset)
self.label_params = dict(label_params) if label_params else None
# Shape
if shape in ["ellipse", "rectangle"]:
self.shape = shape
else:
print("Warning: wrong shape value, set to ellipse instead")
self.shape = "ellipse"
def render(self, ctx):
"""
Render the node.
:param ctx:
The :class:`_rendering_context` object.
"""
# Get the axes and default plotting parameters from the rendering
# context.
ax = ctx.ax()
# Resolve the plotting parameters.
plot_params = dict(self.plot_params)
plot_params["lw"] = _pop_multiple(
plot_params, ctx.line_width, "lw", "linewidth"
)
plot_params["ec"] = plot_params["edgecolor"] = _pop_multiple(
plot_params, ctx.node_ec, "ec", "edgecolor"
)
fc_is_set = "fc" in plot_params or "facecolor" in plot_params
plot_params["fc"] = _pop_multiple(
plot_params, ctx.node_fc, "fc", "facecolor"
)
fc = plot_params["fc"]
plot_params["alpha"] = plot_params.get("alpha", 1)
# And the label parameters.
if self.label_params is None:
label_params = dict(ctx.label_params)
else:
label_params = dict(self.label_params)
label_params["va"] = _pop_multiple(
label_params, "center", "va", "verticalalignment"
)
label_params["ha"] = _pop_multiple(
label_params, "center", "ha", "horizontalalignment"
)
# Deal with ``fixed`` nodes.
scale = self.scale
if self.fixed:
# MAGIC: These magic numbers should depend on the grid/node units.
self.offset[1] += 6
label_params["va"] = "baseline"
label_params.pop("verticalalignment", None)
label_params.pop("ma", None)
if not fc_is_set:
plot_params["fc"] = "k"
diameter = ctx.node_unit * scale
if self.aspect is not None:
aspect = self.aspect
else:
aspect = ctx.aspect
# Set up an observed node or alternate node. Note the fc INSANITY.
if self.observed and not self.fixed:
style = ctx.observed_style
elif self.alternate and not self.fixed:
style = ctx.alternate_style
else:
style = False
if style:
# Update the plotting parameters depending on the style of
# observed node.
h = float(diameter)
w = aspect * float(diameter)
if style == "shaded":
plot_params["fc"] = "0.7"
elif style == "outer":
h = diameter + 0.1 * diameter
w = aspect * diameter + 0.1 * diameter
elif style == "inner":
h = diameter - 0.1 * diameter
w = aspect * diameter - 0.1 * diameter
plot_params["fc"] = fc
# Draw the background ellipse.
if self.shape == "ellipse":
bg = Ellipse(
xy=ctx.convert(self.x, self.y),
width=w,
height=h,
**plot_params
)
elif self.shape == "rectangle":
# Adapt to make Rectangle the same api than ellipse
wi = w
xy = ctx.convert(self.x, self.y)
xy[0] = xy[0] - wi / 2.0
xy[1] = xy[1] - h / 2.0
bg = Rectangle(xy=xy, width=wi, height=h, **plot_params)
else:
# Should never append
raise (
ValueError(
"Wrong shape in object causes an error in render"
)
)
ax.add_artist(bg)
# Reset the face color.
plot_params["fc"] = fc
# Draw the foreground ellipse.
if not fc_is_set and not self.fixed and self.observed:
plot_params["fc"] = "none"
if self.shape == "ellipse":
el = Ellipse(
xy=ctx.convert(self.x, self.y),
width=diameter * aspect,
height=diameter,
**plot_params
)
elif self.shape == "rectangle":
# Adapt to make Rectangle the same api than ellipse
wi = diameter * aspect
xy = ctx.convert(self.x, self.y)
xy[0] = xy[0] - wi / 2.0
xy[1] = xy[1] - diameter / 2.0
el = Rectangle(xy=xy, width=wi, height=diameter, **plot_params)
else:
# Should never append
raise (
ValueError("Wrong shape in object causes an error in render")
)
ax.add_artist(el)
# Reset the face color.
plot_params["fc"] = fc
# Annotate the node.
ax.annotate(
self.content,
ctx.convert(self.x, self.y),
xycoords="data",
xytext=self.offset,
textcoords="offset points",
size=self.fontsize,
**label_params
)
return el
def get_frontier_coord(self, target_xy, ctx, edge):
"""
Get the coordinates of the point of intersection between the
shape of the node and a line starting from the center of the node to an
arbitrary point. Will throw a :class:`SameLocationError` if the nodes
contain the same `x` and `y` coordinates. See the example of rectangle
below:
.. code-block:: python
_____________
| | ____--X (target_node)
| __--X----
| X-- |(return coordinate of this point)
| |
|____________|
:target_xy: (x float, y float)
A tuple of coordinate of target node
"""
# Scale the coordinates appropriately.
x1, y1 = ctx.convert(self.x, self.y)
x2, y2 = target_xy[0], target_xy[1]
# Aspect ratios.
if self.aspect is not None:
aspect = self.aspect
else:
aspect = ctx.aspect
if self.shape == "ellipse":
# Compute the distances.
dx, dy = x2 - x1, y2 - y1
if dx == 0.0 and dy == 0.0:
raise SameLocationError(edge)
dist1 = np.sqrt(dy * dy + dx * dx / float(aspect * aspect))
# Compute the fractional effect of the radii of the nodes.
alpha1 = 0.5 * ctx.node_unit * self.scale / dist1
# Get the coordinates of the starting position.
x0, y0 = x1 + alpha1 * dx, y1 + alpha1 * dy
return x0, y0
elif self.shape == "rectangle":
dx, dy = x2 - x1, y2 - y1
# theta = np.angle(complex(dx, dy))
# print(theta)
# left or right intersection
dxx1 = self.scale * aspect / 2.0 * (np.sign(dx) or 1.0)
dyy1 = (
self.scale
* aspect
/ 2.0
* np.abs(dy / dx)
* (np.sign(dy) or 1.0)
)
val1 = np.abs(complex(dxx1, dyy1))
# up or bottom intersection
dxx2 = self.scale * 0.5 * np.abs(dx / dy) * (np.sign(dx) or 1.0)
dyy2 = self.scale * 0.5 * (np.sign(dy) or 1.0)
val2 = np.abs(complex(dxx2, dyy2))
if val1 < val2:
return x1 + dxx1, y1 + dyy1
else:
return x1 + dxx2, y1 + dyy2
else:
# Should never append
raise ValueError("Wrong shape in object causes an error")
class Edge(object):
"""
An edge between two :class:`Node` objects.
:param node1:
The first :class:`Node`.
:param node2:
The second :class:`Node`. The arrow will point towards this node.
:param directed: (optional)
Should the edge be directed from ``node1`` to ``node2``? In other
words: should it have an arrow?
:param label: (optional)
A string to annotate the edge.
:param xoffset: (optional)
The x-offset from the middle of the arrow to plot the label.
Only takes effect if `label` is defined in `plot_params`.
:param yoffset: (optional)
The y-offset from the middle of the arrow to plot the label.
Only takes effect if `label` is defined in `plot_params`.
:param plot_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.patches.FancyArrow` constructor to adjust
edge behavior.
:param label_params: (optional)
A dictionary of parameters to pass to the
:class:`matplotlib.axes.Axes.annotate` constructor to adjust
label behavior.
"""
def __init__(
self,
node1,
node2,
directed=True,
label=None,
xoffset=0,
yoffset=0.1,
plot_params=None,
label_params=None,
):
self.node1 = node1
self.node2 = node2
self.directed = directed
self.label = label
self.xoffset = xoffset
self.yoffset = yoffset
self.plot_params = dict(plot_params) if plot_params else {}
self.label_params = dict(label_params) if label_params else {}
def _get_coords(self, ctx):
"""
Get the coordinates of the line.
:param conv:
A callable coordinate conversion.
:returns:
* ``x0``, ``y0``: the coordinates of the start of the line.
* ``dx0``, ``dy0``: the displacement vector.
"""
# Scale the coordinates appropriately.
x1, y1 = ctx.convert(self.node1.x, self.node1.y)
x2, y2 = ctx.convert(self.node2.x, self.node2.y)
x3, y3 = self.node1.get_frontier_coord((x2, y2), ctx, self)
x4, y4 = self.node2.get_frontier_coord((x1, y1), ctx, self)
return x3, y3, x4 - x3, y4 - y3
def render(self, ctx):
"""
Render the edge in the given axes.
:param ctx:
The :class:`_rendering_context` object.
"""
ax = ctx.ax()
plot_params = self.plot_params
plot_params["linewidth"] = _pop_multiple(
plot_params, ctx.line_width, "lw", "linewidth"
)
plot_params["linestyle"] = plot_params.get("linestyle", "-")
# Add edge annotation.
if self.label is not None:
x, y, dx, dy = self._get_coords(ctx)
ax.annotate(
self.label,
[x + 0.5 * dx + self.xoffset, y + 0.5 * dy + self.yoffset],
xycoords="data",
xytext=[0, 3],
textcoords="offset points",
ha="center",
va="center",
**self.label_params
)
if self.directed:
plot_params["ec"] = _pop_multiple(
plot_params, "k", "ec", "edgecolor"
)
plot_params["fc"] = _pop_multiple(
plot_params, "k", "fc", "facecolor"
)
plot_params["head_length"] = plot_params.get("head_length", 0.25)
plot_params["head_width"] = plot_params.get("head_width", 0.1)
# Build an arrow.
args = self._get_coords(ctx)
# zero lengh arrow produce error
if not (args[2] == 0.0 and args[3] == 0.0):
ar = FancyArrow(
*self._get_coords(ctx),
width=0,
length_includes_head=True,
**plot_params
)