-
Notifications
You must be signed in to change notification settings - Fork 0
/
cube_interactive.py
664 lines (538 loc) · 22.6 KB
/
cube_interactive.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
#----------------------------------------------------------------------
# Matplotlib Rubik's cube simulator
# Written by Jake Vanderplas
# Adapted from cube code written by David Hogg
# https://github.com/davidwhogg/MagicCube
# Adapted by Miguel Hernando (Python 3 )
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import widgets
import threading
import time
"""
Sticker representation
----------------------
Each face is represented by a length [5, 3] array:
[v1, v2, v3, v4, v1]
Each sticker is represented by a length [9, 3] array:
[v1a, v1b, v2a, v2b, v3a, v3b, v4a, v4b, v1a]
In both cases, the first point is repeated to close the polygon.
Each face also has a centroid, with the face number appended
at the end in order to sort correctly using lexsort.
The centroid is equal to sum_i[vi].
Colors are accounted for using color indices and a look-up table.
With all faces in an NxNxN cube, then, we have three arrays:
centroids.shape = (6 * N * N, 4)
faces.shape = (6 * N * N, 5, 3)
stickers.shape = (6 * N * N, 9, 3)
colors.shape = (6 * N * N,)
The canonical order is found by doing
ind = np.lexsort(centroids.T)
After any rotation, this can be used to quickly restore the cube to
canonical position.
"""
class Quaternion:
"""Quaternion Rotation:
Class to aid in representing 3D rotations via quaternions.
"""
@classmethod
def from_v_theta(cls, v, theta):
"""
Construct quaternions from unit vectors v and rotation angles theta
Parameters
----------
v : array_like
array of vectors, last dimension 3. Vectors will be normalized.
theta : array_like
array of rotation angles in radians, shape = v.shape[:-1].
Returns
-------
q : quaternion object
quaternion representing the rotations
"""
theta = np.asarray(theta)
v = np.asarray(v)
s = np.sin(0.5 * theta)
c = np.cos(0.5 * theta)
v = v * s / np.sqrt(np.sum(v * v, -1))
x_shape = v.shape[:-1] + (4,)
x = np.ones(x_shape).reshape(-1, 4)
x[:, 0] = c.ravel()
x[:, 1:] = v.reshape(-1, 3)
x = x.reshape(x_shape)
return cls(x)
def __init__(self, x):
self.x = np.asarray(x, dtype=float)
def __repr__(self):
return "Quaternion:\n" + self.x.__repr__()
def __mul__(self, other):
# multiplication of two quaternions.
# we don't implement multiplication by a scalar
sxr = self.x.reshape(self.x.shape[:-1] + (4, 1))
oxr = other.x.reshape(other.x.shape[:-1] + (1, 4))
prod = sxr * oxr
return_shape = prod.shape[:-1]
prod = prod.reshape((-1, 4, 4)).transpose((1, 2, 0))
ret = np.array([(prod[0, 0] - prod[1, 1]
- prod[2, 2] - prod[3, 3]),
(prod[0, 1] + prod[1, 0]
+ prod[2, 3] - prod[3, 2]),
(prod[0, 2] - prod[1, 3]
+ prod[2, 0] + prod[3, 1]),
(prod[0, 3] + prod[1, 2]
- prod[2, 1] + prod[3, 0])],
dtype=np.float64,
order='F').T
return self.__class__(ret.reshape(return_shape))
def as_v_theta(self):
"""Return the v, theta equivalent of the (normalized) quaternion"""
x = self.x.reshape((-1, 4)).T
# compute theta
norm = np.sqrt((x ** 2).sum(0))
theta = 2 * np.arccos(x[0] / norm)
# compute the unit vector
v = np.array(x[1:], order='F', copy=True)
v /= np.sqrt(np.sum(v ** 2, 0))
# reshape the results
v = v.T.reshape(self.x.shape[:-1] + (3,))
theta = theta.reshape(self.x.shape[:-1])
return v, theta
def as_rotation_matrix(self):
"""Return the rotation matrix of the (normalized) quaternion"""
v, theta = self.as_v_theta()
shape = theta.shape
theta = theta.reshape(-1)
v = v.reshape(-1, 3).T
c = np.cos(theta)
s = np.sin(theta)
mat = np.array([[v[0] * v[0] * (1. - c) + c,
v[0] * v[1] * (1. - c) - v[2] * s,
v[0] * v[2] * (1. - c) + v[1] * s],
[v[1] * v[0] * (1. - c) + v[2] * s,
v[1] * v[1] * (1. - c) + c,
v[1] * v[2] * (1. - c) - v[0] * s],
[v[2] * v[0] * (1. - c) - v[1] * s,
v[2] * v[1] * (1. - c) + v[0] * s,
v[2] * v[2] * (1. - c) + c]],
order='F').T
return mat.reshape(shape + (3, 3))
def rotate(self, points):
M = self.as_rotation_matrix()
return np.dot(points, M.T)
def project_points(points, q, view, vertical=[0, 1, 0]):
"""Project points using a quaternion q and a view v
Parameters
----------
points : array_like
array of last-dimension 3
q : Quaternion
quaternion representation of the rotation
view : array_like
length-3 vector giving the point of view
vertical : array_like
direction of y-axis for view. An error will be raised if it
is parallel to the view.
Returns
-------
proj: array_like
array of projected points: same shape as points.
"""
points = np.asarray(points)
view = np.asarray(view)
xdir = np.cross(vertical, view).astype(float)
if np.all(xdir == 0):
raise ValueError("vertical is parallel to v")
xdir /= np.sqrt(np.dot(xdir, xdir))
# get the unit vector corresponing to vertical
ydir = np.cross(view, xdir)
ydir /= np.sqrt(np.dot(ydir, ydir))
# normalize the viewer location: this is the z-axis
v2 = np.dot(view, view)
zdir = view / np.sqrt(v2)
# rotate the points
R = q.as_rotation_matrix()
Rpts = np.dot(points, R.T)
# project the points onto the view
dpoint = Rpts - view
dpoint_view = np.dot(dpoint, view).reshape(dpoint.shape[:-1] + (1,))
dproj = -dpoint * v2 / dpoint_view
trans = list(range(1, dproj.ndim)) + [0]
return np.array([np.dot(dproj, xdir),
np.dot(dproj, ydir),
-np.dot(dpoint, zdir)]).transpose(trans)
class Cube:
"""Magic Cube Representation"""
# define some attribues
default_plastic_color = 'black'
default_face_colors = ["w", "#ffcf00", "#cf0000", "#ff6f00", "#009f0f", "#00008f", "gray", "none"]
''' "w", "#ffcf00" '''
base_face = np.array([[1, 1, 1],
[1, -1, 1],
[-1, -1, 1],
[-1, 1, 1],
[1, 1, 1]], dtype=float)
stickerwidth = 0.9
stickermargin = 0.5 * (1. - stickerwidth)
stickerthickness = 0.001
(d1, d2, d3) = (1 - stickermargin,
1 - 2 * stickermargin,
1 + stickerthickness)
base_sticker = np.array([[d1, d2, d3], [d2, d1, d3],
[-d2, d1, d3], [-d1, d2, d3],
[-d1, -d2, d3], [-d2, -d1, d3],
[d2, -d1, d3], [d1, -d2, d3],
[d1, d2, d3]], dtype=float)
base_face_centroid = np.array([[0, 0, 1]])
base_sticker_centroid = np.array([[0, 0, 1 + stickerthickness]])
# Define rotation angles and axes for the six sides of the cube
x, y, z = np.eye(3)
rots = []
for theta in (np.pi / 2, -np.pi / 2):
rots.append(Quaternion.from_v_theta(x, theta))
for theta in (np.pi / 2, -np.pi / 2, np.pi, 2 * np.pi):
rots.append(Quaternion.from_v_theta(y, theta))
# define face movements
facesdict = dict(F=z, B=-z,
R=x, L=-x,
U=y, D=-y)
def __init__(self, N=3, plastic_color=None, face_colors=None):
self.N = N
if plastic_color is None:
self.plastic_color = self.default_plastic_color
else:
self.plastic_color = plastic_color
if face_colors is None:
self.face_colors = self.default_face_colors
else:
self.face_colors = face_colors
self._move_list = []
self._initialize_arrays()
def _initialize_arrays(self):
# initialize centroids, faces, and stickers. We start with a
# base for each one, and then translate & rotate them into position.
# Define N^2 translations for each face of the cube
cubie_width = 2. / self.N
translations = np.array([[[-1 + (i + 0.5) * cubie_width,
-1 + (j + 0.5) * cubie_width, 0]]
for i in range(self.N)
for j in range(self.N)])
# Create arrays for centroids, faces, stickers, and colors
face_centroids = []
faces = []
sticker_centroids = []
stickers = []
colors = []
state = []
factor = np.array([1. / self.N, 1. / self.N, 1])
for i in range(6):
M = self.rots[i].as_rotation_matrix()
faces_t = np.dot(factor * self.base_face
+ translations, M.T)
stickers_t = np.dot(factor * self.base_sticker
+ translations, M.T)
face_centroids_t = np.dot(self.base_face_centroid
+ translations, M.T)
sticker_centroids_t = np.dot(self.base_sticker_centroid
+ translations, M.T)
colors_i = i + np.zeros(face_centroids_t.shape[0], dtype=int)
state_i = i + np.zeros(face_centroids_t.shape[0], dtype=int)
# append face ID to the face centroids for lex-sorting
face_centroids_t = np.hstack([face_centroids_t.reshape(-1, 3),
colors_i[:, None]])
sticker_centroids_t = sticker_centroids_t.reshape((-1, 3))
faces.append(faces_t)
face_centroids.append(face_centroids_t)
stickers.append(stickers_t)
sticker_centroids.append(sticker_centroids_t)
colors.append(colors_i)
state.append(state_i)
self._face_centroids = np.vstack(face_centroids)
self._faces = np.vstack(faces)
self._sticker_centroids = np.vstack(sticker_centroids)
self._stickers = np.vstack(stickers)
self._colors = np.concatenate(colors)
self._state = np.concatenate(state)
self._sort_faces()
def _sort_faces(self):
# use lexsort on the centroids to put faces in a standard order.
ind = np.lexsort(self._face_centroids.T)
self._face_centroids = self._face_centroids[ind]
self._sticker_centroids = self._sticker_centroids[ind]
self._stickers = self._stickers[ind]
self._colors = self._colors[ind]
self._faces = self._faces[ind]
def rotate_face(self, f, n=1, layer=0):
"""Rotate Face"""
if layer < 0 or layer >= self.N:
raise ValueError('layer should be between 0 and N-1')
try:
f_last, n_last, layer_last = self._move_list[-1]
except:
f_last, n_last, layer_last = None, None, None
if (f == f_last) and (layer == layer_last):
ntot = (n_last + n) % 4
if abs(ntot - 4) < abs(ntot):
ntot = ntot - 4
if np.allclose(ntot, 0):
self._move_list = self._move_list[:-1]
else:
self._move_list[-1] = (f, ntot, layer)
else:
self._move_list.append((f, n, layer))
v = self.facesdict[f]
r = Quaternion.from_v_theta(v, n * np.pi / 2)
M = r.as_rotation_matrix()
proj = np.dot(self._face_centroids[:, :3], v)
cubie_width = 2. / self.N
flag = ((proj > 0.9 - (layer + 1) * cubie_width) &
(proj < 1.1 - layer * cubie_width))
for x in [self._stickers, self._sticker_centroids,
self._faces]:
x[flag] = np.dot(x[flag], M.T)
self._face_centroids[flag, :3] = np.dot(self._face_centroids[flag, :3],
M.T)
def draw_interactive(self):
fig = plt.figure(figsize=(5, 5))
fig.add_axes(InteractiveCube(self))
return fig
class InteractiveCube(plt.Axes):
def __init__(self, cube=None,
interactive=True,
view=(0, 0, 10),
fig=None, rect=[0, 0.16, 1, 0.84],
**kwargs):
if cube is None:
self.cube = Cube(3)
elif isinstance(cube, Cube):
self.cube = cube
else:
self.cube = Cube(cube)
self._view = view
self._start_rot = Quaternion.from_v_theta((1, -1, 0),
-np.pi / 6)
if fig is None:
fig = plt.gcf()
# disable default key press events
callbacks = fig.canvas.callbacks.callbacks
del callbacks['key_press_event']
# add some defaults, and draw axes
kwargs.update(dict(aspect=kwargs.get('aspect', 'equal'),
xlim=kwargs.get('xlim', (-2.0, 2.0)),
ylim=kwargs.get('ylim', (-2.0, 2.0)),
frameon=kwargs.get('frameon', False),
xticks=kwargs.get('xticks', []),
yticks=kwargs.get('yticks', [])))
super(InteractiveCube, self).__init__(fig, rect, **kwargs)
self.xaxis.set_major_formatter(plt.NullFormatter())
self.yaxis.set_major_formatter(plt.NullFormatter())
self._start_xlim = kwargs['xlim']
self._start_ylim = kwargs['ylim']
# Define movement for up/down arrows or up/down mouse movement
self._ax_UD = (1, 0, 0)
self._step_UD = 0.01
# Define movement for left/right arrows or left/right mouse movement
self._ax_LR = (0, -1, 0)
self._step_LR = 0.01
self._ax_LR_alt = (0, 0, 1)
# Internal state variable
self._active = False # true when mouse is over axes
self._button1 = False # true when button 1 is pressed
self._button2 = False # true when button 2 is pressed
self._event_xy = None # store xy position of mouse event
self._shift = False # shift key pressed
self._digit_flags = np.zeros(10, dtype=bool) # digits 0-9 pressed
self._current_rot = self._start_rot #current rotation state
self._face_polys = None
self._sticker_polys = None
self._draw_cube()
# connect some GUI events
self.figure.canvas.mpl_connect('button_press_event',
self._mouse_press)
self.figure.canvas.mpl_connect('button_release_event',
self._mouse_release)
self.figure.canvas.mpl_connect('motion_notify_event',
self._mouse_motion)
self.figure.canvas.mpl_connect('key_press_event',
self._key_press)
self.figure.canvas.mpl_connect('key_release_event',
self._key_release)
self._initialize_widgets()
# write some instructions
self.figure.text(0.05, 0.05,
"Mouse/arrow keys adjust view\n"
"U/D/L/R/B/F keys turn faces\n"
"(hold shift for counter-clockwise)",
size=10)
def _initialize_widgets(self):
self._ax_reset = self.figure.add_axes([0.75, 0.05, 0.2, 0.075])
self._btn_reset = widgets.Button(self._ax_reset, 'Reset View')
self._btn_reset.on_clicked(self._reset_view)
self._ax_solve = self.figure.add_axes([0.55, 0.05, 0.2, 0.075])
self._btn_solve = widgets.Button(self._ax_solve, 'Solve Cube')
self._btn_solve.on_clicked(self._solve_cube)
def _project(self, pts):
return project_points(pts, self._current_rot, self._view, [0, 1, 0])
def _draw_cube(self):
stickers = self._project(self.cube._stickers)[:, :, :2]
faces = self._project(self.cube._faces)[:, :, :2]
face_centroids = self._project(self.cube._face_centroids[:, :3])
sticker_centroids = self._project(self.cube._sticker_centroids[:, :3])
plastic_color = self.cube.plastic_color
colors = np.asarray(self.cube.face_colors)[self.cube._colors]
face_zorders = -face_centroids[:, 2]
sticker_zorders = -sticker_centroids[:, 2]
if self._face_polys is None:
# initial call: create polygon objects and add to axes
self._face_polys = []
self._sticker_polys = []
for i in range(len(colors)):
fp = plt.Polygon(faces[i], facecolor=plastic_color,
zorder=face_zorders[i])
sp = plt.Polygon(stickers[i], facecolor=colors[i],
zorder=sticker_zorders[i])
self._face_polys.append(fp)
self._sticker_polys.append(sp)
self.add_patch(fp)
self.add_patch(sp)
else:
# subsequent call: update the polygon objects
for i in range(len(colors)):
self._face_polys[i].set_xy(faces[i])
self._face_polys[i].set_zorder(face_zorders[i])
self._face_polys[i].set_facecolor(plastic_color)
self._sticker_polys[i].set_xy(stickers[i])
self._sticker_polys[i].set_zorder(sticker_zorders[i])
self._sticker_polys[i].set_facecolor(colors[i])
self.figure.canvas.draw()
def rotate(self, rot):
self._current_rot = self._current_rot * rot
def rotate_face(self, face, turns=1, layer=0, steps=5):
if not np.allclose(turns, 0):
for i in range(steps):
self.cube.rotate_face(face, turns * 1. / steps,
layer=layer)
self._draw_cube()
def _reset_view(self, *args):
self.set_xlim(self._start_xlim)
self.set_ylim(self._start_ylim)
self._current_rot = self._start_rot
self._draw_cube()
def _solve_cube(self, *args):
move_list = self.cube._move_list[:]
for (face, n, layer) in move_list[::-1]:
self.rotate_face(face, -n, layer, steps=3)
self.cube._move_list = []
def _key_press(self, event):
"""Handler for key press events"""
if event.key == 'shift':
self._shift = True
elif event.key.isdigit():
self._digit_flags[int(event.key)] = 1
elif event.key == 'right':
if self._shift:
ax_LR = self._ax_LR_alt
else:
ax_LR = self._ax_LR
self.rotate(Quaternion.from_v_theta(ax_LR,
5 * self._step_LR))
elif event.key == 'left':
if self._shift:
ax_LR = self._ax_LR_alt
else:
ax_LR = self._ax_LR
self.rotate(Quaternion.from_v_theta(ax_LR,
-5 * self._step_LR))
elif event.key == 'up':
self.rotate(Quaternion.from_v_theta(self._ax_UD,
5 * self._step_UD))
elif event.key == 'down':
self.rotate(Quaternion.from_v_theta(self._ax_UD,
-5 * self._step_UD))
elif event.key.upper() in 'LRUDBF':
if self._shift:
direction = -1
else:
direction = 1
if np.any(self._digit_flags[:N]):
for d in np.arange(N)[self._digit_flags[:N]]:
self.rotate_face(event.key.upper(), direction, layer=d)
else:
self.rotate_face(event.key.upper(), direction)
self._draw_cube()
self.cube._sort_faces()
self._draw_cube()
def _key_release(self, event):
"""Handler for key release event"""
if event.key == 'shift':
self._shift = False
elif event.key.isdigit():
self._digit_flags[int(event.key)] = 0
def _mouse_press(self, event):
"""Handler for mouse button press"""
self._event_xy = (event.x, event.y)
if event.button == 1:
self._button1 = True
elif event.button == 3:
self._button2 = True
def _mouse_release(self, event):
"""Handler for mouse button release"""
self._event_xy = None
if event.button == 1:
self._button1 = False
elif event.button == 3:
self._button2 = False
def _mouse_motion(self, event):
"""Handler for mouse motion"""
if self._button1 or self._button2:
dx = event.x - self._event_xy[0]
dy = event.y - self._event_xy[1]
self._event_xy = (event.x, event.y)
if self._button1:
if self._shift:
ax_LR = self._ax_LR_alt
else:
ax_LR = self._ax_LR
rot1 = Quaternion.from_v_theta(self._ax_UD,
self._step_UD * dy)
rot2 = Quaternion.from_v_theta(ax_LR,
self._step_LR * dx)
self.rotate(rot1 * rot2)
self._draw_cube()
if self._button2:
factor = 1 - 0.003 * (dx + dy)
xlim = self.get_xlim()
ylim = self.get_ylim()
self.set_xlim(factor * xlim[0], factor * xlim[1])
self.set_ylim(factor * ylim[0], factor * ylim[1])
self.figure.canvas.draw()
def update_cube(cube, interactive_cube, delay, rotations):
interactive_cube._draw_cube()
time.sleep(delay)
for rotation in rotations:
face, sense, layer = rotation
cube.rotate_face(face, sense, layer)
interactive_cube._draw_cube()
time.sleep(delay)
if __name__ == '__main__':
import sys
try:
N = int(sys.argv[1])
except:
N = 3
cube = Cube(N)
rotations = [('F', 1, 0), ('U', -1, 2)]
fig = plt.figure(figsize = (5, 5))
interactive_cube = InteractiveCube(cube, fig = fig)
fig.add_axes(interactive_cube)
update_thread = threading.Thread(target = update_cube, args = (cube, interactive_cube, 2, rotations))
update_thread.start()
plt.show()
#c.draw_interactive()
# do a 3-corner swap
#c.rotate_face('D')
#c.rotate_face('R', -1)
#c.rotate_face('U', -1)
#c.rotate_face('R')
#c.rotate_face('D', -1)
#c.rotate_face('R', -1)
#c.rotate_face('U')