Geometric algebra¶
ue_math.ga_graph draws kingdon multivectors in the world, the way ganja.js does in a browser. It knows plane-based (PGA), conformal (CGA) and vector (VGA) algebras.
A triangle in 2D PGA¶
from kingdon import Algebra
from ue_math.ga_graph import graph
alg = Algebra(2, 0, 1)
point = lambda x, y: alg.vector(e0=1, e1=x, e2=y).dual()
A, B, C = point(-1, -1), point(1, -1), point(0, 1)
graph(alg,
0xD0FFE1, [A, B, C], # colour, then a polygon
0x224488, A, 'A', B, 'B', C, 'C', # labelled points
0x882244, lambda: A & B, 'a line', # recomputed on every update
grid=True)
Drag the points. Hold the left mouse button on a point and move it. Everything given as a lambda follows, because it is recomputed from the moved point. Drag anywhere else on a 3D graph to turn it.
In a code cell¶
In a code cell, pass at=actor to draw next to the cell. Running the cell again replaces the graph.
from kingdon import Algebra
from ue_math.ga_graph import graph
alg = Algebra(2, 0, 1)
point = lambda x, y: alg.vector(e0=1, e1=x, e2=y).dual()
A, B = point(0, 0), point(1, 1)
graph(alg, A, 'A', B, 'B', lambda: A & B, at=actor)
What goes in the list¶
| Item | Means |
|---|---|
0xRRGGBB |
Colour for what follows. 0xAARRGGBB: AA is transparency, 00 opaque. |
'text' |
Label for the item before it ('_...' isn't drawn) |
| a multivector | Drawn according to its algebra (below) |
[P, Q] |
Line segment; [P, Q, R, ...] a polygon |
lambda: ... |
Replaced by its result on every update |
lambda t: ... |
t from 0 to 1: points make a curve, motors an orbit, numbers y = f(x) |
lambda u, v: ... |
A surface; numbers or RGB make a heat map |
{'name': element} |
Elements labelled with their names |
| Algebra | Draws |
|---|---|
PGA Algebra(2, 0, 1), Algebra(3, 0, 1) |
Points, lines, planes, ideal points as arrows |
CGA Algebra(3, 1), Algebra(4, 1) |
Points, point pairs, circles, spheres, lines and planes. ipns=True for the inner product form. Imaginary rounds are red. (3, 1) needs conformal=True. |
VGA Algebra(2), Algebra(3) |
Vectors as arrows, bivectors as squares |
Options¶
ganja's options work: animate, grid, labels, scale, lineWidth, pointRadius, fontSize, clip, range, dual, conformal, ipns, camera, h, p.
For Unreal:
| Option | Does |
|---|---|
uu |
UU per unit (default 100) |
location |
Where, as an FVector |
orientation |
'wall' (y up, facing you) or 'ground' (z up) |
at |
Draw next to this actor |
fps, planeSize |
Update rate, size of drawn planes |
3D CGA: spheres and planes through points¶
from kingdon import Algebra
from ue_math.ga_graph import graph
alg = Algebra(4, 1)
ni = alg.vector(e4=1, e5=1)
no = alg.vector(e4=-0.5, e5=0.5)
up = lambda x=0., y=0., z=0.: no + alg.vector(e1=x, e2=y, e3=z) + 0.5 * (x*x + y*y + z*z) * ni
p1, p2, p3, p4 = up(1), up(0, 1), up(0, 0, -1), up(0, -1)
graph(alg,
0x00FF0000, p1, 'p1', p2, 'p2', p3, 'p3', p4, 'p4',
0xE0008800, lambda: p1 ^ p2 ^ p3 ^ ni, 'plane',
0xE00000FF, lambda: p1 ^ p2 ^ p3 ^ p4, 'sphere',
conformal=True, grid=True)
Drag p1 ... p4 and the sphere and plane follow.
Built-in examples¶
from ue_math import ga_graph
ga_graph.show('pga2d_triangle')
ga_graph.show('cga3d_project_reject')
graphs = ga_graph.show_all() # all of them, side by side
Examples: pga2d_triangle, cga3d_points_spheres_planes, cga3d_project_reject, pga3d_distances_and_angles (animated), pga3d_points_and_lines.
Translating ganja.js¶
| ganja.js | Python |
|---|---|
a ^ b, a & b, a << b |
a ^ b, a & b, a.lc(b) |
!x |
x.dual() |
~x |
x.reverse() |
x.Normalized, x.Length |
x.normalized(), ga_graph.length(x) |
Precedence
In Python * binds tighter than &, and & tighter than ^. In ganja.js ^ & << bind tighter than *. Add brackets when you translate.
kingdon's own method works too: alg.graph(A, B, graph_widget=ga_graph.UnrealGraph).
In the tests¶
Copied from the code when this site is built. test_ga_graph in test_spawn.py draws every example in the game:
From the tests: test_ga_graph (Content/Scripts/test_spawn.py:1753)
def test_ga_graph(base_y=0):
"""Draw every ga_graph example, one per 600 UU along Y."""
try:
import ue_math.ga_graph as ex
except Exception as e:
_log_exception('ga_graph/import', e)
return _result('ga_graph', None, extra=f'import failed: {e!r}')
results = {}
for i, name in enumerate(ex.EXAMPLES):
g, problems = None, []
t0 = time.monotonic()
try:
g = ex.show(name, location=FVector(0, base_y + 300 + i * 600, 300))
problems = g.errors + g.warnings
except Exception as e:
_log_exception(f'ga_{name}', e)
problems.append(repr(e))
results.update(_result(
f'ga_{name}', None if problems else g,
extra='; '.join(problems) or f'{len(g.factory._spawned)} actors',
elapsed=time.monotonic() - t0))
return results
The offline tests in ue_math/test_ga_graph.py run without Unreal (python -m ue_math.test_ga_graph in Content/Scripts). draw() there returns what would be drawn, so they show what each kind of subject turns into:
From the tests: Subjects.test_ganja_list (Content/Scripts/ue_math/test_ga_graph.py:184)
def test_ganja_list(self):
A, B, C = pt2(0, 0), pt2(1, 0), pt2(0, 1)
pr = draw(P2, 0xD0FFE1, [A, B, C], 0x224488, A, 'A', [A, B], '_no')
self.assertEqual([p.kind for p in pr], ['mesh', 'point', 'text', 'segment'])
self.assertEqual(pr[0].color, (0xD0 / 255, 1, 0xE1 / 255))
self.assertEqual(pr[1].color, (0x22 / 255, 0x44 / 255, 0x88 / 255))
self.assertAlmostEqual(draw(P2, 0x80FF0000, A)[0].opacity, 1 - 128 / 255)
From the tests: Subjects.test_functions_and_containers (Content/Scripts/ue_math/test_ga_graph.py:192)
def test_functions_and_containers(self):
A, B = pt2(0, 0), pt2(1, 0)
self.assertEqual(len(draw(P2, lambda: [A, B])), 2) # list of subjects
self.assertEqual(len(draw(P2, lambda: [A, B], A)), 2) # segment + point
self.assertEqual(len(draw(P2, A, lambda: lambda: B)), 2)
self.assertEqual([p.text for p in draw(P2, {'A': A, 'c': 0xFF, 'B': B})],
['', 'A', '', 'B'])
cloud = P3.vector(np.array([[1, 1], [0, 1], [2, 3], [4, 5]], float)).dual()
pr = draw(P3, cloud)
np.testing.assert_allclose([p.pts[0] for p in pr], [[0, 2, 4], [1, 3, 5]])
From the tests: Subjects.test_curves (Content/Scripts/ue_math/test_ga_graph.py:203)
def test_curves(self):
pr = draw(P2, lambda x: x * x)[0]
self.assertEqual(pr.kind, 'polyline')
np.testing.assert_allclose(pr.pts[:, 1], pr.pts[:, 0] ** 2)
pr = draw(P2, lambda t: pt2(t, 2 * t), 'x')[0]
np.testing.assert_allclose(pr.pts[-1], [1, 2, 0])
# motor orbit: translation by t along x
trans = lambda t: P3.multivector(e=1, e01=-t / 2)
end = draw(P3, trans, 'x')[0].pts[-1]
want = draw(P3, (trans(1) >> pt3(0, 0, 0)))[0].pts[0]
np.testing.assert_allclose(end, want, atol=1e-9)
self.assertAlmostEqual(np.linalg.norm(end), 1)
From the tests: Subjects.test_surfaces (Content/Scripts/ue_math/test_ga_graph.py:220)
From the tests: View.test_drag_updates_mv_and_dependents (Content/Scripts/ue_math/test_ga_graph.py:660)
def test_drag_updates_mv_and_dependents(self):
for alg, A, B, kw in (
(P2, pt2(0, 0), pt2(1, 0), {}),
(P3, pt3(0, 0, 0), pt3(1, 0, 0), {}),
(C2, up(C2, 0, 0), up(C2, 1, 0), {'conformal': True}),
(C3, up(C3, 0, 0, 0), up(C3, 1, 0, 0), {})):
g = self.view(alg, A, B, lambda: [A, B], A, **kw)
self.assertIsNotNone(g._ticker)
g._drag_to(g._pool['point'][1], g_at(g, (1.5, 0.5, 0)))
np.testing.assert_allclose(g.model.position(B), [1.5, .5, 0], atol=1e-9)
seg = [p for p in g.prims if p.kind == 'segment'][0]
np.testing.assert_allclose(seg.pts[1], [1.5, .5, 0], atol=1e-9)