def test_affine_transform(plot=False): np.random.seed(1) corrs = [0, 0.6, 0.95, 0.999] for corr in corrs: for scaleratio in [1]: #, 0.001]: covmatrix = np.array([[1., corr], [corr, 1.]]) # should draw uniformly sampled points points = genpoints_following_cov(covmatrix, size=400) print('settings: corr:', corr, 'scaleratio:', scaleratio, 'covmatrix:', covmatrix.flatten(), points.shape) points[:, 0] = points[:, 0] * 0.01 * scaleratio + 0.5 points[:, 1] = points[:, 1] * 0.01 + 0.5 layer = AffineLayer() layer.optimize(points, points) points3 = layer.untransform( genpoints_following_cov(np.diag([1, 1]), size=400)) #print('cov:', layer.cov, 'covmatrix:', covmatrix, 'ratio:', layer.cov / covmatrix) tpoints = layer.transform(points) assert tpoints.shape == points.shape, (tpoints.shape, points.shape) points2 = layer.untransform(tpoints) assert tpoints.shape == points2.shape, (tpoints.shape, points2.shape) if plot and scaleratio == 1: plt.figure(figsize=(9, 4)) plt.subplot(1, 2, 1) plt.scatter(points[:, 0], points[:, 1]) plt.scatter(points2[:, 0], points2[:, 1], marker='x') plt.scatter(points3[:, 0], points3[:, 1], marker='+') plt.subplot(1, 2, 2) plt.scatter(tpoints[:, 0], tpoints[:, 1]) lo, hi = plt.xlim() lo2, hi2 = plt.ylim() lo, hi = min(lo, lo2), max(hi, hi2) plt.xlim(lo, hi) plt.ylim(lo, hi) plt.savefig("testtransform_affine_corr%s_scale%s.pdf" % (corr, scaleratio), bbox_inches='tight') plt.close() assert (points2 == points).all(), (points, tpoints, points2) # transform a single point points = points[0] tpoints = layer.transform(points) assert tpoints.shape == points.shape, (tpoints.shape, points.shape) points2 = layer.untransform(tpoints) assert tpoints.shape == points2.shape, (tpoints.shape, points2.shape) assert (points2 == points).all(), (points, tpoints, points2)
def test_region_mean_distances(): np.random.seed(1) points = np.random.uniform(0.4, 0.6, size=(10000, 2)) #points[:,1] *= 0.5 mask = np.abs((points[:, 0] - 0.5)**2 + (points[:, 1] - 0.5)**2 - 0.08**2) < 0.02**2 print('circle:', mask.sum()) points = points[mask] mask = points[:, 0] < 0.5 print('half-circle:', mask.sum()) points = points[mask] transformLayer = AffineLayer(wrapped_dims=[]) transformLayer.optimize(points, points) region = MLFriends(points, transformLayer) region.maxradiussq, region.enlarge = region.compute_enlargement( nbootstraps=30) print("enlargement factor:", region.enlarge, 1 / region.enlarge) region.create_ellipsoid() meandist = region.compute_mean_pair_distance() t = transformLayer.transform(region.u) d = 0 N = 0 for i in range(len(t)): for j in range(i): d += ((t[i, :] - t[j, :])**2).sum()**0.5 #print(i, j, t[i,:], t[j,:], ((t[i,:] - t[j,:])**2).sum()) N += 1 print((meandist, d, N, t)) assert np.isclose(meandist, d / N), (meandist, d, N)