def wasserstein_matching(I1, I2, matchidx, labels=["dgm1", "dgm2"]): plot_dgms([I1, I2], labels=labels) cp = np.cos(np.pi / 4) sp = np.sin(np.pi / 4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) for index in matchidx: (i, j) = index if i >= I1.shape[0] and j >= I2.shape[0]: continue if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], "g") elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], "g") else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], "g")
def plotBottleneckMatching(I1, I2, matchidx, D, labels=['dgm1', 'dgm2']): plot_dgms([I1, I2], labels=labels) cp = np.cos(np.pi / 4) sp = np.sin(np.pi / 4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) dists = [D[i, j] for (i, j) in matchidx] (i, j) = matchidx[np.argmax(dists)] if i >= I1.shape[0] and j >= I2.shape[0]: return if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], 'g') elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], 'g') else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], 'g')
def plotWassersteinMatching(I1, I2, matchidx, labels = ['dgm1', 'dgm2']): plot_dgms([I1, I2], labels = labels) cp = np.cos(np.pi/4) sp = np.sin(np.pi/4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) for index in matchidx: (i, j) = index if i >= I1.shape[0] and j >= I2.shape[0]: continue if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], 'g') elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], 'g') else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], 'g')
def plotBottleneckMatching(I1, I2, matchidx, D, labels = ['dgm1', 'dgm2']): plot_dgms([I1, I2], labels = labels) cp = np.cos(np.pi/4) sp = np.sin(np.pi/4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) dists = [D[i, j] for (i, j) in matchidx] (i, j) = matchidx[np.argmax(dists)] if i >= I1.shape[0] and j >= I2.shape[0]: return if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], 'g') elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], 'g') else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], 'g')
def test_show(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, legend=False, show=True)
def bottleneck_matching(I1, I2, matchidx, D, labels=["dgm1", "dgm2"], ax=None): plot_dgms( [I1, I2], labels=labels) # ax=ax) # <- not supported until next ripser release cp = np.cos(np.pi / 4) sp = np.sin(np.pi / 4) R = np.array([[cp, -sp], [sp, cp]]) if I1.size == 0: I1 = np.array([[0, 0]]) if I2.size == 0: I2 = np.array([[0, 0]]) I1Rot = I1.dot(R) I2Rot = I2.dot(R) dists = [D[i, j] for (i, j) in matchidx] (i, j) = matchidx[np.argmax(dists)] if i >= I1.shape[0] and j >= I2.shape[0]: return if i >= I1.shape[0]: diagElem = np.array([I2Rot[j, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I2[j, 0], diagElem[0]], [I2[j, 1], diagElem[1]], "g") elif j >= I2.shape[0]: diagElem = np.array([I1Rot[i, 0], 0]) diagElem = diagElem.dot(R.T) plt.plot([I1[i, 0], diagElem[0]], [I1[i, 1], diagElem[1]], "g") else: plt.plot([I1[i, 0], I2[j, 0]], [I1[i, 1], I2[j, 1]], "g")
def test_default_label(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, show=False) assert ax.get_ylabel() == 'Death' assert ax.get_xlabel() == 'Birth'
def test_default_square(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, show=False) diagonal = ax.lines[0].get_xydata() assert diagonal[0, 0] == diagonal[0, 1] assert diagonal[1, 0] == diagonal[1, 1]
def test_set_title(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, title='my title', show=False) assert ax.get_title() == 'my title' f, ax = plt.subplots() plot_dgms(diagrams, show=False) assert ax.get_title() == ''
def test_legend_true(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, legend=True, show=False) legend = [ child for child in ax.get_children() if child.__class__.__name__ == "Legend" ] assert len(legend) == 1
def test_lifetime(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, lifetime=True, show=False) assert ax.get_ylabel() == 'Lifetime' assert ax.get_xlabel() == 'Birth' line = ax.get_lines()[0] np.testing.assert_array_equal(line.get_ydata(), [0, 0])
def test_multiple(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, show=False) pathcols = [ child for child in ax.get_children() if child.__class__.__name__ == "PathCollection" ] assert len(pathcols) == 2 np.testing.assert_array_equal(pathcols[0].get_offsets(), diagrams[0]) np.testing.assert_array_equal(pathcols[1].get_offsets(), diagrams[1])
def test_single(self): """ Most just test this doesn't crash """ diagram = np.array([[0, 1], [1, 1], [2, 4], [3, 5]]) f, ax = plt.subplots() plot_dgms(diagram, show=False) x_plot, y_plot = ax.lines[0].get_xydata().T assert x_plot[0] <= np.min(diagram) assert x_plot[1] >= np.max(diagram) # get PathCollection pathcols = [ child for child in ax.get_children() if child.__class__.__name__ == "PathCollection" ] assert len(pathcols) == 1
def test_lifetime_removes_birth(self): diagrams = [ np.array([[0, 1], [1, 1], [2, 4], [3, 5]]), np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]]) ] f, ax = plt.subplots() plot_dgms(diagrams, lifetime=True, show=False) pathcols = [ child for child in ax.get_children() if child.__class__.__name__ == "PathCollection" ] modded1 = diagrams[0] modded1[:, 1] = diagrams[0][:, 1] - diagrams[0][:, 0] modded2 = diagrams[1] modded2[:, 1] = diagrams[1][:, 1] - diagrams[1][:, 0] assert len(pathcols) == 2 np.testing.assert_array_equal(pathcols[0].get_offsets(), modded1) np.testing.assert_array_equal(pathcols[1].get_offsets(), modded2)
ax = Axes3D(fig) ax.view_init(elev=elevation, azim=azimuth) ax.scatter(arr[:,0],arr[:,1],arr[:,2]) pyplot.show() return ax def randompd(k): data = np.random.random((k,3)) s=timer() diagrams = ripser(data,maxdim=1)['dgms'] timer(s,4) randompd(100) sph=ripser(sphere(100),maxdim=2) plot_dgms(sph['dgms'],show=True) def geomill(arr,dim=1,cutoff=2,elevation=45,azimuth=30): #E3view(arr,elevation,azimuth) #VR complex skeletondim=dim+1 filtration = d.fill_rips(arr, skeletondim, cutoff) #persistent homology ph = d.homology_persistence(filtration) dgms = d.init_diagrams(ph, filtration) d.plot.plot_bars(dgms[dim], show = True) return dgms
def testVideoSkeletonTDA(): """ Look at an example of using sliding window + TDA on keypoints from OpenPose """ blocktime = 2000 fac = 10 winlen = 5 keypt_types = [ 'pose_keypoints_2d', 'hand_left_keypoints_2d', 'hand_right_keypoints_2d' ] studyname = "URI-001-01-18-08" video = PoseVideo(studyname, save_skeletons=False, delete_frames=False, framerange=(1000, np.inf)) NA = len(ACCEL_TYPES) ftemplate = "neudata/data/Study1/%s" % studyname + "/MITes_%s_RawCorrectedData_%s.RAW_DATA.csv" XsAccel = [ loadAccelerometerData(ftemplate % (ACCEL_NUMS[i], ACCEL_TYPES[i])) for i in range(NA) ] idxs = np.arange(XsAccel[0].shape[0]) ## Step 0: Upsample and interpolate keypoints XsVideo = [] tsvideo = [] for k, kstr in enumerate(keypt_types): title = kstr.split("_keypoints")[0] tic = time.time() print("Upsampling %s..." % kstr) X, M, ts = video.getKeypointStack(kstr) XNew, tsnew = upsampleFeatureStack(X, M, ts, fac) print("Elapsed Time: %.3g" % (time.time() - tic)) XNew = getAccelerationFeatureStack(XNew, 1) XsVideo.append(XNew) tsvideo.append(tsnew) colors = cycle(['C0', 'C1', 'C2']) resol = 5 plt.figure(figsize=(resol * 5, resol * 4)) for i, v in enumerate(video.frames[0:-2 * winlen]): p = v.people[0] plt.clf() I = np.array(v.I) ## Step 1: Plot detected keypoints plt.subplot2grid((4, 5), (0, 0), rowspan=2, colspan=2) plt.imshow(I) for k, (kstr, color) in enumerate(zip(keypt_types, colors)): keypts = p[kstr] # Plot detected keypoints as dots toplot = keypts[keypts[:, 2] > 0, :] plt.scatter(toplot[:, 0], toplot[:, 1], 4, color) # Plot interpolated keypoints as xs toplot = keypts[keypts[:, 2] == 0, :] plt.scatter(toplot[:, 0], toplot[:, 1], 8, color, marker="x") plt.axis('off') plt.xlim([0, I.shape[1]]) plt.ylim([I.shape[0], 0]) # Step 2: For each region (left/right hand and trunk), plot SSMs and H1 for video, # then accelerometer data, then accelerometer SSMs for k, (kstr, tsk, XVk) in enumerate(zip(keypt_types, tsvideo, XsVideo)): ## Plot video statistics tidxs = np.arange(tsk.size) title = kstr.split("_keypoints")[0] t1 = v.timestamp t2 = t1 + blocktime i1 = tidxs[np.argmin(np.abs(t1 - tsk))] i2 = tidxs[np.argmin(np.abs(t2 - tsk))] X = XVk[i1:i2, :] res = getPersistencesBlock(X, winlen * fac, mean_center=False, sphere_normalize=True) D, dgm = res['D'], res['I'] TExtent = (tsk[i2 - winlen * fac] - t1) / 1000.0 plt.subplot(4, 5, k + 3) plt.imshow(D, interpolation='none', extent=(0, TExtent, TExtent, 0)) plt.title("%s SSM" % title) plt.subplot(4, 5, 5 + k + 3) mp = 0.0 if dgm.size > 0: plot_dgms(diagrams=[dgm], labels=['H1'], size=50, xy_range=[0, 2, 0, 2], show=False) mp = np.max(dgm[:, 1] - dgm[:, 0]) plt.xlim([0, 2]) plt.ylim([0, 2]) plt.title("%s Max Pers = %.3g" % (title, mp)) ## Plot accelerometer statistics i1 = idxs[np.argmin(np.abs(XsAccel[k][:, 0] - t1))] i2 = idxs[np.argmin(np.abs(XsAccel[k][:, 0] - t2))] x = XsAccel[k][i1:i2, 1::] ts = np.array(XsAccel[k][i1:i2, 0]) ts -= ts[0] ts /= 1000.0 plt.subplot(4, 5, 10 + k + 3) plt.plot(ts, x) plt.title(ACCEL_TYPES[k]) # Estimate window length adim = int(x.shape[0] / 2) D = getPersistencesBlock(x, adim, mean_center=True, sphere_normalize=True)['D'] plt.subplot(4, 5, 15 + k + 3) plt.imshow(D, interpolation='none', extent=(0, TExtent, TExtent, 0)) plt.savefig("%i.png" % i, bbox_inches='tight')
import numpy as np import matplotlib.pyplot as plt import scipy from scipy import ndimage import PIL from ripser import ripser, plot_dgms, lower_star_img ts = np.linspace(-1, 1, 100) x1 = np.exp(-ts**2/(0.1**2)) ts -= 0.4 x2 = np.exp(-ts**2/(0.1**2)) img = -x1[None, :]*x1[:, None] - 2*x1[None, :]*x2[:, None] - 3*x2[None, :]*x2[:, None] dgm = lower_star_img(img) plt.figure(figsize=(10, 5)) plt.subplot(121) plt.imshow(img) plt.colorbar() plt.title("Test Image") plt.subplot(122) plot_dgms(dgm) plt.title("0-D Persistence Diagram") plt.tight_layout() plt.show()
def make2HoledTorusFigure(): x0 = np.array([0.2, 0.2]) dx = 0.1 * np.array([1.0, np.sqrt(3) / 2]) res = get2HoledTorusTraj(x0, dx, 750) Win = 40 endpts, X = res['endpts'], res['X'] c = plt.get_cmap('Spectral') C = c(np.array(np.round(np.linspace(0, 255, X.shape[0])), dtype=np.int32)) C = C[:, 0:3] y = get2HoledTorusDist(X, x0, endpts) Y = getSlidingWindowNoInterp(y, Win) sio.savemat("2HoledTorus.mat", {"X": Y}) tic = time.time() dgms = ripser(Y, maxdim=2)['dgms'] print("Elapsed Time: %.3g" % (time.time() - tic)) # Create distance image normals = endpts[1::, :] - endpts[0:-1, :] normals[:, 0], normals[:, 1] = normals[:, 1], -normals[:, 0] pix = np.linspace(-1.1, 1.1, 200) [I, J] = np.meshgrid(pix, pix) XDist = np.zeros((I.size, 2)) XDist[:, 0] = I.flatten() XDist[:, 1] = J.flatten() dist = get2HoledTorusDist(XDist, x0, endpts) dist = np.reshape(dist, I.shape) insideOctagon = np.ones(XDist.shape[0]) for i in range(8): dot = (XDist - endpts[i, :]).dot(normals[i, :]) insideOctagon *= (dot < 0) insideOctagon = np.reshape(insideOctagon, dist.shape) dist[insideOctagon == 0] = 0 plt.figure(figsize=(15, 5)) plt.subplot(131) plt.imshow(dist, cmap='gray', extent=[pix[0], pix[-1], pix[-1], pix[0]]) plt.scatter(x0[0], x0[0], 100, 'r', zorder=10) ax = plt.gca() AW = 0.05 AXW = 0.0025 idxperm = getGreedyPermEuclidean(X[0:-1, :], 200)['perm'] for i in idxperm: p1 = X[i, :] p2 = X[i + 1, :] rx = 0.6 * (p2 - p1) if np.sqrt(np.sum(rx**2)) > 0.5: continue ax.arrow(p1[0], p1[1], rx[0], rx[1], head_width=AW, head_length=AW, fc=C[i, :], ec=C[i, :], width=AXW) # Plot octagon AW = 0.1 AXW = 0.005 for i in range(8): p1 = endpts[i, :] + 0.5 * (endpts[i + 1, :] - endpts[i, :]) p2 = endpts[i, :] + 0.51 * (endpts[i + 1, :] - endpts[i, :]) rx = p2 - p1 if i >= 4: rx *= -1 p1, p2 = p2, p1 k = i % 4 plt.plot(endpts[i:i + 2, 0], endpts[i:i + 2, 1], c='C%i' % k, linewidth=2) ax.arrow(p1[0], p1[1], rx[0], rx[1], head_width=AW, head_length=AW, fc='C%i' % k, ec='C%i' % k, width=AXW, zorder=10) plt.xlim([-1.1, 1.1]) plt.ylim([-1.1, 1.1]) plt.axis('equal') plt.title("Observation Function") plt.subplot(132) drawLineColored(np.arange(y.size), y, C) ax = plt.gca() ax = plt.gca() #Draw sliding window AW = 0.05 AXW = 0.005 y1, y2 = np.min(y), np.max(y) pad = 0.05 * (y2 - y1) c = np.array([1.0, 0.737, 0.667]) ax.arrow(Win, y2 + 0.3 * pad, 20, 0, head_width=AW, head_length=20, fc=c, ec=c, width=AXW) ax.arrow(Win, y1 - 0.3 * pad, 20, 0, head_width=AW, head_length=20, fc=c, ec=c, width=AXW) y1 = y1 - pad y2 = y2 + pad plt.plot([0, Win], [y1, y1], c=c) plt.plot([0, Win], [y2, y2], c=c) plt.plot([0, 0], [y1, y2], c=c) plt.plot([Win, Win], [y1, y2], c=c) ax.set_facecolor((0.15, 0.15, 0.15)) plt.title("Time Series") plt.xlabel("Sample Number") plt.ylabel("Observation Function") plt.subplot(133) plot_dgms(dgms) plt.title("Persistence Diagrams $\mathbb{Z}/2$") plt.savefig("2HoledTorus.svg", bbox_inches='tight')
from ripser import ripser, plot_dgms import matplotlib.pyplot as plt import sys import numpy as np from TDA.persentropy import persentropy script, fileName = sys.argv data = np.genfromtxt(fileName, delimiter=",") dgms = ripser(data, maxdim=2)["dgms"] print(dgms[0]) entropies = persentropy(dgms) print(entropies) plot_dgms(dgms) plt.show()
def VR(path,matrix,is_distance_matrix=True): ret = ripser(matrix, maxdim=1, distance_matrix=is_distance_matrix) diagrams = ret['dgms'] plot_dgms(diagrams) with open(path, "wb") as f: pickle.dump(diagrams, f)
def makeConceptVideo(annoidx = 0, showPDs = False): NA = len(ACCEL_TYPES) #studyname = "URI-001-01-18-08" studyname = "URI-001-01-25-08" foldername = "neudata/data/Study1/%s"%studyname annofilename = "Annotator1Stereotypy.annotation.xml" annos = loadAnnotations("%s/%s"%(foldername, annofilename)) ftemplate = foldername + "/MITes_%s_RawCorrectedData_%s.RAW_DATA.csv" annos = annos[1::] Xs = [loadAccelerometerData(ftemplate%(ACCEL_NUMS[i], ACCEL_TYPES[i])) for i in range(NA)] video = PoseVideo(studyname) a = annos[annoidx] clipLen = a['stop'] - a['start'] print("Clip is %.3g seconds long:"%(clipLen/1000.0)) padding = 4000 #Amount of padding around annotation in milliseconds hop = 50 dim = 30 a['start'] -= padding a['stop'] += padding start = a['start'] annos = expandAnnotations([a], hop=hop) if showPDs: plt.figure(figsize=(16, 7)) else: plt.figure(figsize=(12, 7)) gridsize = (3, 3) if showPDs: gridsize = (3, 4) blurlast = [] blurlastlast = [] for i, a in enumerate(annos): plt.clf() scores = np.zeros(NA) dT = (a['stop'] - a['start']) frame = video.getNearestFrame(a['stop']) plt.subplot2grid(gridsize, (0, 0), rowspan=3, colspan=1) blurlastlast = blurlast blurlast = frame.render(showLandmarks=False, blurlast=blurlast+blurlastlast) if i*hop > padding and i*hop-padding < clipLen: plt.title("Annotated %s Action"%a["label"]) for k in range(NA): x = getAccelerometerRange(Xs[k], a)[:, 1::] plt.subplot2grid(gridsize, (k, 1)) plt.plot((a['start']-start+np.linspace(0, dT, len(x)))/1000.0, x) if k == 0: plt.legend(["X", "Y", "Z"], loc=(-0.4, 0.4)) if k < 2: ax = plt.gca() ax.set_xticks([]) else: plt.xlabel("Time (Sec)") plt.title("%s Accelerometer"%ACCEL_TYPES[k]) res = getPersistencesBlock(x, dim) [I, P] = [res['I'], res['P']] if showPDs: plt.subplot2grid(gridsize, (k, 2)) if I.size > 0: plot_dgms(diagrams=[I], labels=['H1'], size=50, show=False)#, \ #xy_range = [0, 2, 0, 2]) plt.title("%s Persistence Dgm"%ACCEL_TYPES[k]) scores[k] = P/np.sqrt(3) if showPDs: plt.subplot2grid(gridsize, (0, 3), rowspan=3, colspan=1) else: plt.subplot2grid(gridsize, (0, 2), rowspan=3, colspan=1) plt.barh(-np.arange(NA), scores) ax = plt.gca() ax.set_yticks([]) plt.xlim([0, 1]) plt.xlabel("Score") plt.title("Periodicity Scores") plt.savefig("anno%i_%i.png"%(annoidx, i), bbox_inches='tight')