forked from argriffing/xgcode
/
interlace.py
638 lines (600 loc) · 22.6 KB
/
interlace.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
"""
Interlacing functions.
This includes polynomials.
Some families of polynomial sequences are known to
strictly or weakly interlace.
This includes all sequences of polynomials that you get by
starting with a high degree polynomial with distinct real roots
and then taking derivatives.
Also all orthogonal polynomial sequences interlace.
So do certain sequences of characteristic polynomials.
This includes characteristic polynomials of sequences
of real symmetric matrices whose dimension is reduced by
taking principal submatrices.
Also reducing the dimensions of real symmetric positive semidefinite matrices
by taking the Schur complement gives a sequence
of interlacing characteristic polynomials.
"""
from StringIO import StringIO
import math
import unittest
import numpy as np
import scipy
from scipy import linalg
import sympy
from sympy import matrices
from sympy import abc
import tikz
import sympyutils
import iterutils
import color
import pcurve
import bezier
class Shape:
"""
This is like a tree or a curve embedded in Euclidean space.
It is basically a bunch of 1D curves glued together
and embedded in a higher dimensional Euclidean space.
Shapes are expected to have the following functions --
a function that gives bounding box info,
a function that returns a collection of bezier paths,
a function that returns the orthoplanar intersections.
"""
def get_infinity_radius(self):
"""
Infinity refers to the infinity norm.
@return: max of absolute values of axis aligned bounding box coords
"""
a = np.linalg.norm(self.get_bb_min(), np.Inf)
b = np.linalg.norm(self.get_bb_max(), np.Inf)
return max(a, b)
class ParametricShape(Shape):
"""
This 1D shape is parameterized by a single variable.
The fp member function should map the time to a point.
"""
def get_bb_min(self):
"""
Get the min value on each axis.
"""
times = self.get_bb_min_times()
points = [self.fp(t) for t in times]
return np.min(points, axis=0)
def get_bb_max(self):
"""
Get the max value on each axis.
"""
times = self.get_bb_max_times()
points = [self.fp(t) for t in times]
return np.max(points, axis=0)
def get_orthoplanar_intersections(self):
"""
Get the list of intersection points per axis.
"""
point_seqs = []
for time_seq in self.get_orthoplanar_intersection_times():
point_seqs.append([self.fp(t) for t in time_seq])
return point_seqs
def get_bezier_paths(self):
return [self.get_bezier_path()]
class DifferentiableShape(ParametricShape):
"""
This is a differentiable parametric curve of interlacing functions.
"""
def __init__(self, position_exprs, t_initial, t_final, nchunks_default=20):
"""
The position expressions are univariate sympy expressions.
Each gives the position along an axis as a function of time t.
@param position_exprs: sympy expressions that give position at time t
@param t_initial: initial time
@param t_final: final time
@param nchunks_default: the default number of chunks for a bpath
"""
velocity_exprs = [x.diff(sympy.abc.t) for x in position_exprs]
self.fps = [sympyutils.WrappedUniExpr(x) for x in position_exprs]
self.fvs = [sympyutils.WrappedUniExpr(x) for x in velocity_exprs]
self.fp = Multiplex(self.fps)
self.fv = Multiplex(self.fvs)
self.t_initial = t_initial
self.t_final = t_final
self.nchunks_default = nchunks_default
def get_bb_min_times(self):
"""
Get the time of the min value on each axis.
"""
return [scipy.optimize.fminbound(
f, self.t_initial, self.t_final) for f in self.fps]
def get_bb_max_times(self):
"""
Get the time of the max value on each axis.
"""
return [scipy.optimize.fminbound(
(lambda x: -f(x)), self.t_initial, self.t_final) for f in self.fps]
def get_orthoplanar_intersection_times(self):
"""
Get the intersection times for the plane orthogonal to each axis.
Note that this function assumes interlacing roots.
"""
root_seqs = [[]]
for f in self.fps:
root_seq = []
for low, high in iterutils.pairwise(
[self.t_initial] + root_seqs[-1] + [self.t_final]):
root_seq.append(scipy.optimize.brentq(f, low, high))
root_seqs.append(root_seq)
return root_seqs[1:]
def get_bezier_path(self, nchunks_in=None):
"""
@param nchunks_in: use this many chunks in the piecewise approximation
@return: a BezierPath
"""
nchunks = self.nchunks_default
if nchunks_in:
nchunks = nchunks_in
return pcurve.get_bezier_path(
self.fp, self.fv, self.t_initial, self.t_final, nchunks)
class CubicPolyShape(ParametricShape):
"""
A parametric cubic polynomial is exactly represented by a Bezier curve.
Polynomials are sympy Poly objects.
"""
def __init__(self, polys, t_initial, t_final):
"""
@param polys: cubic sympy Poly objects
@param t_initial: initial time
@param t_final: final time
"""
self.polys = polys
self.fps = [sympyutils.WrappedUniPoly(p) for p in polys]
self.fvs = [sympyutils.WrappedUniPoly(p.diff()) for p in polys]
self.fp = Multiplex(self.fps)
self.fv = Multiplex(self.fvs)
self.t_initial = t_initial
self.t_final = t_final
def get_bb_min_times(self):
"""
Get the time of the min value on each axis.
"""
return [sympyutils.poly_fminbound(
poly, self.t_initial, self.t_final) for poly in self.polys]
def get_bb_max_times(self):
"""
Get the time of the max value on each axis.
"""
return [sympyutils.poly_fminbound(
-poly, self.t_initial, self.t_final) for poly in self.polys]
def get_orthoplanar_intersection_times(self):
"""
Get the intersection times for the plane orthogonal to each axis.
"""
return [p.nroots() for p in self.polys]
def get_bezier_path(self):
b = bezier.create_bchunk_hermite(
self.t_initial, self.t_final,
self.fp(self.t_initial), self.fp(self.t_final),
self.fv(self.t_initial), self.fv(self.t_final))
return pcurve.BezierPath([b])
class ParametricPiecewiseLinearPathShape(ParametricShape):
def __init__(self, points, edge_lengths):
"""
This exists for orthoplanar intersection times.
If the times are not needed then use the non parametric shape.
@param points: a sequence of high dimensional points as numpy arrays
@param edge_lengths: this is how long it takes to traverse each edge
"""
self.points = [np.array(p) for p in points]
self.edge_lengths = edge_lengths
self.ndim = len(points[0])
self.times = [0.0]
t = 0.0
for length in self.edge_lengths:
t += length
self.times.append(t)
self.t_initial = self.times[0]
self.t_final = self.times[-1]
self.fp = self.evaluate
self.fps = [Demux(self.evaluate, i) for i in range(self.ndim)]
def get_bb_min(self):
"""
Get the min value on each axis.
"""
return np.min(self.points, axis=0)
def get_bb_max(self):
"""
Get the max value on each axis.
"""
return np.max(self.points, axis=0)
def get_orthoplanar_intersection_times(self):
"""
Get the list of intersection points per axis.
This is a geometric concept.
"""
npoints = len(self.points)
abstol = 1e-6
time_seqs = []
for axis in range(self.ndim):
time_seq = []
# check points for exact intersections
for p, t in zip(self.points, self.times):
if abs(p[axis]) < abstol:
time_seq.append(t)
# check line segments for intersections
for i, j in iterutils.pairwise(range(npoints)):
pa, pb = self.points[i], self.points[j]
ta, tb = self.times[i], self.times[j]
if abs(pa[axis]) > abstol and abs(pb[axis]) > abstol:
if pa[axis]*pb[axis] < 0:
t_local = pa[axis] / (pa[axis] - pb[axis])
t_global = ta + t_local * (tb - ta)
time_seq.append(t_global)
time_seqs.append(sorted(time_seq))
return time_seqs
def evaluate(self, t_target):
"""
This is slow.
@param t_target: target time
"""
if not self.times[0] <= t_target <= self.times[-1]:
raise ValueError('out of range')
npoints = len(self.points)
for i, j in iterutils.pairwise(range(npoints)):
pa, pb = self.points[i], self.points[j]
ta, tb = self.times[i], self.times[j]
if ta <= t_target <= tb:
t_local = (t_target - ta) / (tb - ta)
p = (1 - t_local) * pa + t_local * pb
return p
def get_bezier_path(self):
bchunks = []
npoints = len(self.points)
for i, j in iterutils.pairwise(range(npoints)):
pa, pb = self.points[i], self.points[j]
ta, tb = self.times[i], self.times[j]
b = bezier.create_bchunk_line_segment(pa, pb)
b.start_time = ta
b.stop_time = tb
bchunks.append(b)
return pcurve.BezierPath(bchunks)
class PiecewiseLinearPathShape(Shape):
def __init__(self, points):
"""
@param points: a sequence of high dimensional points as numpy arrays
"""
self.points = [np.array(p) for p in points]
self.ndim = len(points[0])
def get_bb_min(self):
"""
Get the min value on each axis.
"""
return np.min(self.points, axis=0)
def get_bb_max(self):
"""
Get the max value on each axis.
"""
return np.max(self.points, axis=0)
def get_orthoplanar_intersections(self):
"""
Get the list of intersection points per axis.
This is a geometric concept.
"""
abstol = 1e-6
point_seqs = []
for axis in range(self.ndim):
point_seq = []
# check points for exact intersections
for p in self.points:
if abs(p[axis]) < abstol:
point_seq.append(p)
# check line segments for intersections
for pa, pb in iterutils.pairwise(self.points):
if abs(pa[axis]) > abstol and abs(pb[axis]) > abstol:
if pa[axis]*pb[axis] < 0:
p = (pb[axis]*pa - pa[axis]*pb) / (pb[axis] - pa[axis])
point_seq.append(p)
point_seqs.append(point_seq)
return point_seqs
def get_bezier_path(self):
bchunks = []
for i, (pa, pb) in enumerate(iterutils.pairwise(self.points)):
b = bezier.create_bchunk_line_segment(pa, pb)
b.start_time = float(i)
b.stop_time = float(i+1)
bchunks.append(b)
return pcurve.BezierPath(bchunks)
def get_bezier_paths(self):
return [self.get_bezier_path()]
class PiecewiseLinearTreeShape(Shape):
def __init__(self, T, v_to_point):
"""
This is a purely geometric view of the tree.
The branch lengths are irrelevant given the points.
The layout is also irrelevant given the points.
The points are, for example, multiplexed eigenvector valuations
or inverse-sqrt-of-eigenvalue-scaled eigenvector valuations.
@param T: set of vertex frozensets as in the Ftree module
@param v_to_point: map a vertex to a numpy point
"""
self.T = T
self.v_to_point = v_to_point
self.points = self.v_to_point.values()
self.ndim = len(self.points[0])
def get_bb_min(self):
"""
Get the min value on each axis.
"""
return np.min(self.points, axis=0)
def get_bb_max(self):
"""
Get the max value on each axis.
"""
return np.max(self.points, axis=0)
def get_orthoplanar_intersections(self):
"""
Get the list of intersection points per axis.
This is a geometric concept.
"""
abstol = 1e-6
point_seqs = []
for axis in range(self.ndim):
point_seq = []
# check points for exact intersections
for p in self.points:
if abs(p[axis]) < abstol:
point_seq.append(p)
# check line segments for intersections
for va, vb in self.T:
pa, pb = self.v_to_point[va], self.v_to_point[vb]
if abs(pa[axis]) > abstol and abs(pb[axis]) > abstol:
if pa[axis]*pb[axis] < 0:
p = (pb[axis]*pa - pa[axis]*pb) / (pb[axis] - pa[axis])
point_seq.append(p)
point_seqs.append(point_seq)
return point_seqs
def get_bezier_paths(self):
bpaths = []
for va, vb in self.T:
pa, pb = self.v_to_point[va], self.v_to_point[vb]
b = bezier.create_bchunk_line_segment(pa, pb)
b.start_time = 0.0
b.stop_time = 1.0
bpaths.append(pcurve.BezierPath([b]))
return bpaths
class Hypershape:
"""
A hypershape defines points in a more-than-geometric space.
For example each point could be like (x1, x2, y1, y2, y3) meaning
that at (x1, x2) the value is (y1, y2, y3).
A purely geometric shape would only care about
the set of (y1, y2, y3) triples and would not care about the domain.
"""
pass
class PiecewiseLinearPathHypershape(Hypershape):
"""
This is a sequence of points augmented with timing information.
Practically, this should be used for the superposition figures and the
sign cut figures.
"""
pass
class PiecewiseLinearTreeHypershape(Hypershape):
"""
This is a set of points with 2d tree topology and layout information.
Practically, this should be used for the superposition figures and the
sign cut figures.
"""
pass
def is_strictly_increasing(seq):
for a, b in iterutils.pairwise(seq):
if not a < b:
return False
return True
def assert_support(t_seq, y_seqs):
# check that the t sequence is increasing
if not is_strictly_increasing(t_seq):
raise ValueError('expected a strictly increasing t sequence')
# check that each sequence has the same number of samples
seqs = [t_seq] + y_seqs
lengths = set(len(seq) for seq in seqs)
if len(lengths) != 1:
raise ValueError('expected each sequence to have the same length')
def get_tikz_bezier_2d(bpath):
lines = []
# draw everything except for the last point of the last chunk
for b in bpath.bchunks:
pts = [tikz.point_to_tikz(p) for p in b.get_points()[:-1]]
lines.append('%s .. controls %s and %s ..' % tuple(pts))
# draw the last point of the last chunk
lines.append('%s;' % tikz.point_to_tikz(bpath.bchunks[-1].p3))
return '\n'.join(lines)
def tikz_shape_superposition(shapes, width, height):
"""
Return the body of a tikzpicture environment.
@param shapes: a sequence of 2D Shape objects
@param width: max tikz width
@param height: max tikz height
@return: tikz text
"""
bbmax = np.max([shape.get_bb_max() for shape in shapes], axis=0)
bbmin = np.min([shape.get_bb_min() for shape in shapes], axis=0)
scale = np.array([width, height], dtype=float) / (bbmax - bbmin)
f = lambda x: x*scale
colors = ['black'] + color.wolfram
arr = []
for c, shape in zip(colors, shapes):
for bpath in shape.get_bezier_paths():
bpath.transform(f)
# Chop up the bpath so that the stupid bounding box that tikz
# makes will still be approximately correct.
bpath.refine_for_bb()
# Draw the bpath.
arr.extend([
'\\draw[thick,%s]' % c,
get_tikz_bezier_2d(bpath)])
return '\n'.join(arr)
def tikz_superposition(t_seq, y_seqs, width, height):
"""
Return the body of a tikzpicture environment.
The input defines k piecewise-linear parametric functions.
The domain is a real interval.
The kth sequence of y values should have k zero-crossings.
The returned drawing has arbitrary horizontal and vertical scale.
@param t_seq: sequence of t values
@param y_seqs: sequence of y value sequences
@param width: a horizontal scaling factor
@param height: a vertical scaling factor
@return: LaTeX code for a tikzpicture
"""
# check the form of the input sequences
assert_support(t_seq, y_seqs)
# Get the y scaling factor.
# This is the value by which the observed y values are multiplied
# to give a number that is relevant to the tikz coordinate system.
ymin = min(min(seq) for seq in y_seqs)
ymax = max(max(seq) for seq in y_seqs)
yscale = height / float(ymax - ymin)
# Get the x scaling factor.
xmin = t_seq[0]
xmax = t_seq[-1]
xscale = width / float(xmax - xmin)
# Get the rescaled sequences.
t_seq_rescaled = [t*xscale for t in t_seq]
y_seqs_rescaled = [[y*yscale for y in seq] for seq in y_seqs]
# Start the text array.
arr = []
# Plot the horizontal domain segment.
pa = tikz.point_to_tikz((t_seq_rescaled[0], 0))
pb = tikz.point_to_tikz((t_seq_rescaled[-1], 0))
arr.append('\\draw %s -- %s;' % (pa, pb))
# Plot the scaled functions.
for seq, c in zip(y_seqs_rescaled, color.wolfram):
arr.append('\\draw[color=%s]' % c)
points = zip(t_seq_rescaled, seq)
arr.append(tikz.curve_to_tikz(points, 3) + ';')
# Return the text.
return '\n'.join(arr)
def roots_to_differential_polys(roots):
"""
Construct a sequence of interlacing polynomials.
The input is the collection of distinct roots
of the highest degree polynomial in the sequence.
@param roots: a collection of distinct roots
@return: a sequence of interlacing polynomials
"""
sympy_t = sympy.abc.t
if len(roots) != len(set(roots)):
raise ValueError('expected distinct roots')
p = sympyutils.roots_to_poly(roots)
nroots = len(roots)
polys = [p]
for i in range(nroots-1):
p = polys[-1].diff(sympy_t)
polys.append(p)
polys.reverse()
return polys
def matrix_to_principal_polys(M):
"""
Construct a sequence of interlacing polynomials.
@param M: real symmetric matrix
@return: a sequence of interlacing polynomials
"""
pass
def matrix_to_schur_polys(M):
"""
Construct a sequence of interlacing polynomials.
@param M: positive semidefinite real symmetric matrix
@return: a sequence of interlacing polynomials
"""
pass
class Multiplex:
"""
Turn an iterable of functions into a single function.
Each component function should return a float given a float,
while the returned function will return a numpy array given a float.
"""
def __init__(self, fs):
"""
@param fs: iterable of (float -> float) python functions
"""
self.fs = list(fs)
def __call__(self, t):
return np.array([f(t) for f in self.fs])
class Demux:
def __init__(self, f, index):
self.f = f
self.index = index
def __call__(self, t):
return self.f(t)[self.index]
class TestInterlacing(unittest.TestCase):
def test_roots_to_poly(self):
roots = (1.0, 4.0, 5.0)
p = sympyutils.roots_to_poly(roots)
self.assertTrue(p.is_monic)
root_to_count = sympy.roots(p)
self.assertEqual(set(root_to_count.values()), set([1]))
observed = set(root_to_count.keys())
expected = set(roots)
for r_observed, r_expected in zip(sorted(observed), sorted(expected)):
self.assertAlmostEqual(r_observed, r_expected)
def test_ndiff_roots(self):
roots = (1, 4, 5)
a, b, c = roots
polys = roots_to_differential_polys(roots)
# compute linear root manually
r = float(a + b + c) / 3
# check linear root
observed = sorted(float(r) for r in sympy.roots(polys[0]))
expected = sorted([r])
self.assertTrue(np.allclose(observed, expected))
# compute quadratic roots manually
A = a*a + b*b + c*c
B = a*b + a*c + b*c
S = a + b + c
r0 = float(S + math.sqrt(A - B)) / 3
r1 = float(S - math.sqrt(A - B)) / 3
# check quadratic roots
observed = sorted(float(r) for r in sympy.roots(polys[1]))
expected = sorted([r0, r1])
self.assertTrue(np.allclose(observed, expected))
# check cubic roots
observed = sorted(float(r) for r in sympy.roots(polys[2]))
expected = sorted(roots)
self.assertTrue(np.allclose(observed, expected))
def test_ndiff_roots_symbolic(self):
roots = (1.25, 4.5, 5.75)
a, b, c = roots
polys = roots_to_differential_polys(roots)
# compute linear root manually
r = float(a + b + c) / 3
# check linear root
observed = sorted(float(r) for r in sympy.roots(polys[0]))
expected = sorted([r])
self.assertTrue(np.allclose(observed, expected))
# compute quadratic roots manually
A = a*a + b*b + c*c
B = a*b + a*c + b*c
S = a + b + c
r0 = float(S + math.sqrt(A - B)) / 3
r1 = float(S - math.sqrt(A - B)) / 3
# check quadratic roots
observed = sorted(float(r) for r in sympy.roots(polys[1]))
expected = sorted([r0, r1])
self.assertTrue(np.allclose(observed, expected))
# check cubic roots
observed = sorted(float(r) for r in sympy.roots(polys[2]))
expected = sorted(roots)
self.assertTrue(np.allclose(observed, expected))
def test_poly_eval(self):
roots = (1, 4, 5)
t = 3.2
a, b, c = roots
polys = roots_to_differential_polys(roots)
f = Multiplex((sympyutils.WrappedUniPoly(p) for p in polys))
# compute the evaluation manually
z = (t - a) * (t - b) * (t - c)
y = 3*t*t - 2*t*(a + b + c) + a*b + a*c + b*c
x = 6*t - 2*(a + b + c)
# check the evaluation
observed = f(t)
expected = np.array([x, y, z])
self.assertTrue(np.allclose(observed, expected))
if __name__ == '__main__':
unittest.main()