def describe_simulation(self, save=False): """ This function plots the simulation of a von Mises distribution for different values of n """ n = [10_000, 100_000, 1_000_000] x = np.linspace(-np.pi, np.pi, 300) fig, ax = plt.subplots(1, 3, figsize=(12, 5), sharey=True) i = 0 for val in n: self.simulate(n=val) ax[i].hist(self.results, bins=200, density=True, color='grey') ax[i].plot(x, vonmises.pdf(x, self.kappa, loc=self.mu), 'r-', lw=1, label='theoretical') if self.proposal == 'uniform': ax[i].plot([-np.pi, np.pi], 2 * [vonmises.pdf(x, self.kappa, loc=self.mu).max()], 'b-', lw=1, label='proposal') elif self.proposal == 'cauchy': y, x = np.histogram(wrapped_cauchy(mu=self.mu, kappa=self.kappa, n=10_000_000), bins=np.linspace(-np.pi, np.pi, 1_000), density=True) y_, _ = np.histogram(von_mises_cauchy(mu=self.mu, kappa=self.kappa, n=10_000_000), bins=np.linspace(-np.pi, np.pi, 1_000), density=True) ax[i].plot((x[:-1] + x[1:]) / 2, (y_ / y).max() * gaussian_filter1d(y, sigma=10), 'b-', lw=1, label='proposal') ax[i].set_ylim([0., None]) ax[i].set_xticks([-3.14, 0., 3.14]) ax[i].title.set_text(f'n = {val:.1e}') i += 1 ax[0].locator_params(axis="y", nbins=4) ax[1].get_yaxis().set_visible(False) ax[2].get_yaxis().set_visible(False) fig.suptitle( f'von Mises (\u03BC = {self.mu:.3f}, \u03BA = {self.kappa:.3f}, proposal = {self.proposal})' ) plt.legend(prop={'size': 8}) plt.show() if save: fig.savefig('Graphs/describe_simulation_' + self.proposal + '.png')
def __calcPFrame(self, kappa_ver, kappa_hor, tau, theta_rod): # computes kappas kappa1 = kappa_ver - \ (1 - np.cos(np.abs(2 * self.frames))) * \ tau * \ (kappa_ver - kappa_hor) kappa2 = kappa_hor + \ (1 - np.cos(np.abs(2 * self.frames))) * \ (1 - tau) * \ (kappa_ver - kappa_hor) # for every frame orientation, calculate frame influence P_frame = np.empty([len(theta_rod), self.frame_num]) for i in range(self.frame_num): # the context provided by the frame P_frame0 = vonmises.pdf(theta_rod - self.frames[i], kappa1[i]) P_frame90 = vonmises.pdf(theta_rod - np.pi / 2 - self.frames[i], kappa2[i]) P_frame180 = vonmises.pdf(theta_rod - np.pi - self.frames[i], kappa1[i]) P_frame270 = vonmises.pdf( theta_rod - np.pi * 3 / 2 - self.frames[i], kappa2[i]) # add convolved distributions to P_frame P_frame[:, i] = P_frame0 + P_frame90 + P_frame180 + P_frame270 return P_frame
def angular_linear_pdf(x, alpha, speed_params, vonmises_params, connection_params, cartesian=False): from scipy.stats import kappa4, vonmises # 1. Speed k, h, scale, loc = speed_params x_pdf = kappa4.pdf(x, h, k, loc=loc, scale=scale) x_cdf = kappa4.cdf(x, h, k, loc=loc, scale=scale) # 2. Direction alpha_pdf = np.sum( [vonmises.pdf(alpha, k, loc=u) * w for k, u, w in vonmises_params], axis=0) alpha_cdf = np.sum( [vonmises.cdf(alpha, k, loc=u) * w for k, u, w in vonmises_params], axis=0) # 3. Connection phi = 2 * pi * (x_cdf - alpha_cdf) phi_pdf = np.sum( [vonmises.pdf(phi, k, loc=u) * w for k, u, w in connection_params], axis=0) if cartesian == True: pdf = div0(2 * pi * x_pdf * alpha_pdf * phi_pdf, x) else: pdf = 2 * pi * x_pdf * alpha_pdf * phi_pdf return pdf
def makeProbTable(self): nFrames = np.size(self.theta_frame,0) nRods = np.size(self.theta_rod,0) cdf=np.zeros((nFrames,nRods)) #compute kappas kappa1 = self.kappa_ver-(1-np.cos(np.abs(2*self.theta_frame)))*self.tau*(self.kappa_verself.kappa_hor) kappa2 = self.kappa_hor+(1-np.cos(np.abs(2*self.theta_frame)))*(1-self.tau)*(self.kappa_verself.kappa_hor) #for every frame orientation, compute: for i in range(0,np.size(self.theta_frame,0)): # the context provided by the frame P_frame1 = vonmises.pdf(self.theta_rod-self.theta_frame[i],kappa1[i]) P_frame2 = vonmises.pdf(self.theta_rod-np.pi/2-self.theta_frame[i],kappa2[i]) P_frame3 = vonmises.pdf(self.theta_rod-np.pi-self.theta_frame[i],kappa1[i]) P_frame4 = vonmises.pdf(self.theta_rod-3*np.pi/2-self.theta_frame[i],kappa2[i]) P_frame = (P_frame1+P_frame2+P_frame3+P_frame4)/4 # the otoliths P_oto = vonmises.pdf(self.theta_rod,self.kappa_oto) # cumulatitve response distribution per frame cdf[i,:]=np.cumsum(np.multiply(P_oto, P_frame))/np.sum(np.multiply(P_oto, P_frame)) #save cdf as lookup table self.prob_table=cdf
def vm4_pdf(x, l1, l2, l3, l4, k1, k2, k3, k4, a1, a2, a3, a4, c): return a1*vonmises.pdf(x, k1, l1) + \ a2*vonmises.pdf(x, k2, l2) + \ a3*vonmises.pdf(x, k3, l3) + \ a4*vonmises.pdf(x, k4, l4) + c
def verif(kappa): largeur = largeur95(kappa) xx = [180.0 * i / 1000 - 90 for i in range(1000)] yy = [ vonmises.pdf(x * 2 * np.pi / 180, kappa) / vonmises.pdf(0, kappa) for x in xx ] plt.plot(xx, yy) plt.vlines([-largeur / 2, largeur / 2], 0, 1, color='red') plt.show() return
def frame(self): # Aocr is normally a free parameter (the uncompensated ocular counterroll) Aocr = 14.6 * np.pi / 180 # convert to radians and fixed across subjects factor = len(self.a_oto) * len(self.b_oto) * len(self.sigma_prior) for i in range(len(self.kappa_ver)): for j in range(len(self.kappa_hor)): for k in range(len(self.tau)): for l in range(self.n_head): for m in range(self.n_frames): # the frame in retinal coordinates frame_retinal = -(self.frames[m] - self.head[l] ) - Aocr * np.sin(self.head[l]) # make sure we stay in the -45 to 45 deg range if frame_retinal > np.pi / 4: frame_retinal = frame_retinal - np.pi / 2 elif frame_retinal < -np.pi / 4: frame_retinal = frame_retinal + np.pi / 2 # compute how the kappa's changes with frame angle kappa1 = self.kappa_ver[i] - (1 - np.cos( np.abs(2 * frame_retinal))) * self.tau[k] * ( self.kappa_ver[i] - self.kappa_hor[j]) kappa2 = self.kappa_hor[j] + ( 1 - np.cos(np.abs(2 * frame_retinal))) * ( 1 - self.tau[k]) * (self.kappa_ver[i] - self.kappa_hor[j]) # probability distributions for the four von-mises P_frame1 = vonmises.pdf(-self.rods + frame_retinal, kappa1) P_frame2 = vonmises.pdf( -self.rods + np.pi / 2 + frame_retinal, kappa2) P_frame3 = vonmises.pdf( -self.rods + np.pi + frame_retinal, kappa1) P_frame4 = vonmises.pdf( -self.rods + 3 * np.pi / 2 + frame_retinal, kappa2) # add the probability distributions P_frame = (P_frame1 + P_frame2 + P_frame3 + P_frame4) P_frame = P_frame / np.sum( P_frame) # normalize to one P_frame = np.tile(P_frame, factor) P_frame = P_frame.reshape(self.dims[:3] + self.dims[8:]) self.P_frame[:, :, :, i, j, k, l, m] = P_frame self.P_frame = self.P_frame / (np.prod(self.dims) / self.n_rods) self.P_frame[np.isnan(self.P_frame)] = 1e-307
def plot_vmf_fit(x, mu, kappa, scale, index, title): subplot = plt.subplot(3, 1, 1 + index) plt.hist(x, bins=8, normed=True, histtype='stepfilled') domain = np.linspace(vonmises.ppf(0.01, kappa), vonmises.ppf(0.99, kappa), 100) plt.plot(domain, vonmises.pdf(domain, kappa=kappa, loc=mu, scale=scale)) plt.title(title)
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via calculation of soft-bins over dihdral angle space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ x = [] for a in self.types: func = getattr(md, 'compute_%s' % a) _, y = func(traj) x.extend(vm.pdf(y, loc=self.loc, kappa=self.kappa).reshape(self.n_bins, -1, 1)) return np.hstack(x)
def test_von_mises_featurizer_2(): trajectories = MinimalFsPeptide().get_cached().trajectories # test to make sure results are being put in the right order feat = VonMisesFeaturizer(["phi", "psi"], n_bins=10) _, all_phi = compute_phi(trajectories[0]) X_all = feat.transform(trajectories) all_res = [] for frame in all_phi: for dihedral_value in frame: all_res.extend(vm.pdf(dihedral_value, loc=feat.loc, kappa=feat.kappa)) print(len(all_res)) # this checks 10 random dihedrals to make sure that they appear in the right columns # for the vonmises bins n_phi = all_phi.shape[1] for k in range(5): # pick a random phi dihedral rndint = np.random.choice(range(n_phi)) # figure out where we expect it to be in X_all indices_to_expect = [] for i in range(10): indices_to_expect += [n_phi * i + rndint] # we know the results in all_res are dihedral1(bin1-bin10) dihedral2(bin1 to bin10) # we are checking if X is alldihedrals(bin1) then all dihedrals(bin2) expected_res = all_res[rndint * 10:10 + rndint * 10] assert (np.array( [X_all[0][0, i] for i in indices_to_expect]) == expected_res).all()
def density(x, data, kappa): denom = np.exp(kappa) / vonmises.pdf(0., kappa) N = len(data) p = 0. for z in data: p += np.exp(np.cos(x - z) * kappa) / denom / N return p
def test_VonMisesFeaturizer_describe_features(): feat = VonMisesFeaturizer() rnd_traj = np.random.randint(len(trajectories)) features = feat.transform([trajectories[rnd_traj]]) df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj])) for f in range(25): f_index = np.random.choice(len(df)) atom_inds = df.iloc[f_index].atominds bin_index = int(df.iloc[f_index].otherinfo.strip('bin-')) dihedral_value = md.compute_dihedrals(trajectories[rnd_traj], [atom_inds]) feature_value = [ vm.pdf(i, loc=feat.loc, kappa=feat.kappa)[bin_index] for i in dihedral_value ] assert (features[0][:, f_index] == feature_value).all()
def prob_vonmises(x, kappa, loc): # print "kappa, loc: ", kappa, loc # p = vonmises.pdf(x*pi/180.0,kappa, loc=loc) # p = vonmises.pdf(x,kappa, loc=loc) p = np.array([vonmises.pdf(x+m,kappa, loc=loc) for m in [-2*pi,0,2*pi]]) p = np.amax(p,axis=0) return p
def test_von_mises_featurizer_2(): trajectories = MinimalFsPeptide().get_cached().trajectories # test to make sure results are being put in the right order feat = VonMisesFeaturizer(["phi", "psi"], n_bins=10) _, all_phi = compute_phi(trajectories[0]) X_all = feat.transform(trajectories) all_res = [] for frame in all_phi: for dihedral_value in frame: all_res.extend( vm.pdf(dihedral_value, loc=feat.loc, kappa=feat.kappa)) print(len(all_res)) # this checks 10 random dihedrals to make sure that they appear in the right columns # for the vonmises bins n_phi = all_phi.shape[1] for k in range(5): # pick a random phi dihedral rndint = np.random.choice(range(n_phi)) # figure out where we expect it to be in X_all indices_to_expect = [] for i in range(10): indices_to_expect += [n_phi * i + rndint] # we know the results in all_res are dihedral1(bin1-bin10) dihedral2(bin1 to bin10) # we are checking if X is alldihedrals(bin1) then all dihedrals(bin2) expected_res = all_res[rndint * 10:10 + rndint * 10] assert (np.array([X_all[0][0, i] for i in indices_to_expect]) == expected_res).all()
def mixture_model_pdf(x, precision=STARTING_PRECISION, guess_rate=STARTING_GUESS_RATE, bias=STARTING_BIAS): """Returns a probability density function for a mixture model. Parameters ---------- x : A list (or other iterable object) of values for the x axis. For example `range(-180, 181)` would generate the PDF for every relevant value. precision: The precision (or kappa) parameter. This is inversely related to the standard deviation, and is a value in degrees. guess_rate: The proportion of guess responses (0 - 1). bias: The bias (or loc) parameter in degrees. Returns ------- An array with probability densities for each value of x. """ x = np.radians(x) pdf_vonmises = vonmises.pdf(x=x, kappa=np.radians(precision), loc=np.radians(bias)) pdf_uniform = uniform.pdf(x, loc=-np.pi, scale=2 * np.pi) return pdf_vonmises * (1 - guess_rate) + pdf_uniform * guess_rate
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via calculation of soft-bins over dihdral angle space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ x = [] for a in self.types: func = getattr(md, 'compute_%s' % a) _, y = func(traj) x.extend( vm.pdf(y, loc=self.loc, kappa=self.kappa).reshape(self.n_bins, -1, 1)) return np.hstack(x)
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via calculation of soft-bins over dihdral angle space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ x = [] for a in self.types: func = getattr(md, 'compute_%s' % a) _, y = func(traj) res = vm.pdf(y[..., np.newaxis], loc=self.loc, kappa=self.kappa) #we reshape the results using a Fortran-like index order, #so that it goes over the columns first. This should put the results #phi dihedrals(all bin0 then all bin1), psi dihedrals(all_bin1) x.extend( np.reshape(res, (1, -1, self.n_bins * y.shape[1]), order='F')) return np.hstack(x)
def prob_vonmises(x, kappa, loc): # print "kappa, loc: ", kappa, loc # p = vonmises.pdf(x*pi/180.0,kappa, loc=loc) # p = [vonmises.pdf(x*pi/180.0 + m,kappa, loc=loc) for m in [-2*pi, 0, 2*pi]] p = [vonmises.pdf(x + m,kappa, loc=loc) for m in [-2*pi, 0, 2*pi]] p = max(p) return p
def describe_kappa(self, save=False): """ This function plots the density of a von Mises distribution for different values of kappa """ kappa = [0, 0.1, 0.5, 1.5, 4, 20] x = np.linspace(-np.pi, np.pi, 300) fig, ax = plt.subplots(2, 3, figsize=(13, 7)) i = 1 ax[0, 0].plot([-np.pi, np.pi], 2 * [1 / (2 * np.pi)], 'r-', lw=1) ax[0, 0].set_ylim([0., None]) ax[0, 0].set_xticks([-3.14, 0., 3.14]) ax[0, 0].locator_params(axis="y", nbins=4) ax[0, 0].title.set_text(f'\u03BA = {0}') for val in kappa: if val != 0: ax[i // 3, i % 3].plot(x, vonmises.pdf(x, val, loc=0.), 'r-', lw=1) ax[i // 3, i % 3].set_ylim([0., None]) ax[i // 3, i % 3].set_xticks([-3.14, 0., 3.14]) ax[i // 3, i % 3].locator_params(axis="y", nbins=4) ax[i // 3, i % 3].title.set_text(f'\u03BA = {val}') i += 1 fig.suptitle('von Mises (\u03BC = 0)') fig.tight_layout(pad=1.0) plt.show() if save: fig.savefig('Graphs/describe_kappa.png')
def invmievonmises_pdf(theta, kappa, nu, lambda_, loc): alpha1 = i1(kappa) / i0(kappa) # inverse transformation by Newton's method inv_theta = inv_trans_APF(theta, loc, lambda_, nu) C = (1 - nu * alpha1) p = vonmises.pdf(inv_theta, loc=0, kappa=kappa) / C return p
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via calculation of soft-bins over dihdral angle space. Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ x = [] for a in self.types: func = getattr(md, 'compute_%s' % a) _, y = func(traj) res = vm.pdf(y[..., np.newaxis], loc=self.loc, kappa=self.kappa) #we reshape the results using a Fortran-like index order, #so that it goes over the columns first. This should put the results #phi dihedrals(all bin0 then all bin1), psi dihedrals(all_bin1) x.extend(np.reshape(res, (1, -1, self.n_bins*y.shape[1]), order='F')) return np.hstack(x)
def describe_mu(self, save=False): """ This function plots the density of a von Mises distribution for different values of mu """ mu = [-np.pi / 2, 0, np.pi / 2] x = np.linspace(-np.pi, np.pi, 300) fig, ax = plt.subplots(1, 3, figsize=(12, 5), sharey=True) i = 0 for val in mu: ax[i].plot(x, vonmises.pdf(x, self.kappa, loc=val), 'r-', lw=1) ax[i].set_ylim([0., None]) ax[i].set_xticks([-3.14, 0., 3.14]) i += 1 ax[0].title.set_text(f'\u03BC = -\u03C0/2') ax[1].title.set_text(f'\u03BC = 0') ax[2].title.set_text(f'\u03BC = \u03C0/2') ax[0].locator_params(axis="y", nbins=4) ax[1].get_yaxis().set_visible(False) ax[2].get_yaxis().set_visible(False) fig.suptitle(f'von Mises (\u03BA = {self.kappa})') plt.show() if save: fig.savefig('Graphs/describe_mu.png')
def query_model(self,x): if self.models: best = np.argmin(self.bic) logprob, responsibilities = self.models[best].score_samples(normalize([x])) return np.exp(logprob)[0]/self.max_pdf else: return vonmises.pdf(to_rad(x,self.period), kappa=self.kappa, loc=to_rad(self.circ_mu,self.period), scale=1)/self.max_pdf
def rose_plot(ang, **kwargs): if 'ax' in kwargs: ax = kwargs.pop('ax') else: fig = plt.figure(figsize=kwargs.get('figsize', plt.rcParams.get('figure.figsize'))) ax = fig.add_subplot(111, polar=True) ax.set_theta_zero_location('N') ax.set_theta_direction(-1) if kwargs.get('pdf', False): from scipy.stats import vonmises theta = np.linspace(-np.pi, np.pi, 1801) radii = np.zeros_like(theta) kappa = kwargs.get('kappa', 250) for a in ang: radii += vonmises.pdf(theta, kappa, loc=np.radians(a)) radii += vonmises.pdf(theta, kappa, loc=np.radians(a + 180)) radii /= len(ang) else: bins = kwargs.get('bins', 36) width = 360 / bins if 'weights' in kwargs: num, bin_edges = np.histogram(np.concatenate((ang, ang + 180)), bins=bins + 1, range=(-width / 2, 360 + width / 2), weights=np.concatenate((kwargs.get('weights'), kwargs.get('weights'))), density=kwargs.get('density', False)) else: num, bin_edges = np.histogram(np.concatenate((ang, ang + 180)), bins=bins + 1, range=(-width / 2, 360 + width / 2), density=kwargs.get('density', False)) num[0] += num[-1] num = num[:-1] theta, radii = [], [] arrow = kwargs.get('arrow', 0.95) rwidth = kwargs.get('rwidth', 1) for cc, val in zip(np.arange(0, 360, width), num): theta.extend([cc - width / 2, cc - rwidth * width / 2, cc, cc + rwidth * width / 2, cc + width / 2, ]) radii.extend([0, val * arrow, val, val * arrow, 0]) theta = np.deg2rad(theta) if kwargs.get('scaled', False): radii = np.sqrt(radii) ax.fill(theta, radii, **kwargs.get('fill_kwg', {})) if kwargs.get('show', True): plt.show() return ax
def prob_vonmises(x, kappa, loc): # print "kappa, loc: ", kappa, loc # p = vonmises.pdf(x*pi/180.0,kappa, loc=loc) # p = vonmises.pdf(x,kappa, loc=loc) p = np.array( [vonmises.pdf(x + m, kappa, loc=loc) for m in [-2 * pi, 0, 2 * pi]]) p = np.amax(p, axis=0) return p
def _vm_gauss(self, x, amp, kappa, loc): if kappa <= 10: # Use vonmises g = vonmises.pdf(x, kappa, loc) g = amp * g/max(g) else: # Use regular gaussian - vonmises can't handle large kappa sigma = np.sqrt(1/kappa) # This is true for kappa approx > 10 g = amp * np.exp(-(((x-loc)**2) / (2*sigma**2))) return g
def pdf_random_rotation(self, x, v, mu, kappa, n): """ Gives back the probability of observing the vector x, such that its angle with v is coming from a Von Mises distribution with k = self.kappa and its length coming form chi squared distribution with the parameter n. """ v = v/LA.norm(v,2) x = x/LA.norm(x,2) ang = sum(v*x) return (.5/np.pi)*(chi2.pdf(n*LA.norm(x,2),n)*n)*(vonmises.pdf(ang, kappa))
def plot(self, obj, *args, **kwargs): if type(obj) is Group: ang, _ = obj.dd weights = abs(obj) self.title_text = obj.name else: ang = np.array(obj) weights = None if 'weights' in kwargs: weights = kwargs.pop('weights') if self.axial: ang = np.concatenate((ang % 360, (ang + 180) % 360)) if weights is not None: weights = np.concatenate((weights, weights)) if self.pdf: theta = np.linspace(-np.pi, np.pi, 1801) radii = np.zeros_like(theta) for a in ang: radii += vonmises.pdf(theta, self.kappa, loc=np.radians(a % 360)) radii /= len(ang) else: width = 360 / self.bins if weights is not None: num, bin_edges = np.histogram(ang, bins=self.bins + 1, range=(-width / 2, 360 + width / 2), weights=weights, density=self.density) else: num, bin_edges = np.histogram(ang, bins=self.bins + 1, range=(-width / 2, 360 + width / 2), density=self.density) num[0] += num[-1] num = num[:-1] theta, radii = [], [] for cc, val in zip(np.arange(0, 360, width), num): theta.extend([ cc - width / 2, cc - self.rwidth * width / 2, cc, cc + self.rwidth * width / 2, cc + width / 2, ]) radii.extend([0, val * self.arrow, val, val * self.arrow, 0]) theta = np.deg2rad(theta) if self.scaled: radii = np.sqrt(radii) fill_kw = self.fill_kw.copy() fill_kw.update(kwargs) self.ax.fill(theta, radii, **fill_kw)
def test_von_mises_featurizer(): dataset = fetch_alanine_dipeptide() trajectories = dataset["trajectories"] featurizer = VonMisesFeaturizer(["phi"], n_bins=18) X_all = featurizer.transform(trajectories) n_frames = trajectories[0].n_frames assert X_all[0].shape == (n_frames, 18), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) featurizer = VonMisesFeaturizer(["phi", "psi"], n_bins=18) X_all = featurizer.transform(trajectories) n_frames = trajectories[0].n_frames assert X_all[0].shape == (n_frames, 36), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) featurizer = VonMisesFeaturizer(["phi", "psi"], n_bins=10) X_all = featurizer.transform(trajectories) assert X_all[0].shape == (n_frames, 20), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) dataset = fetch_fs_peptide() trajectories = dataset["trajectories"][0] #test to make sure results are being put in the right order feat = VonMisesFeaturizer(["phi", "psi"], n_bins=10) _, all_phi = compute_phi(trajectories[0]) X_all = feat.transform([trajectories]) all_res = [] for frame in all_phi: for dihedral_value in frame: all_res.extend( vm.pdf(dihedral_value, loc=feat.loc, kappa=feat.kappa)) print(len(all_res)) #this checks 10 random dihedrals to make sure that they appear in the right columns #for the vonmises bins n_phi = all_phi.shape[1] for k in range(5): #pick a random phi dihedral rndint = np.random.choice(range(n_phi)) #figure out where we expect it to be in X_all indices_to_expect = [] for i in range(10): indices_to_expect += [n_phi * i + rndint] #we know the results in all_res are dihedral1(bin1-bin10) dihedral2(bin1 to bin10) # we are checking if X is alldihedrals(bin1) then all dihedrals(bin2) expected_res = all_res[rndint * 10:10 + rndint * 10] assert (np.array([X_all[0][0, i] for i in indices_to_expect]) == expected_res).all()
def _swap_pdf(x_target, x_nontargets, precision=STARTING_PRECISION, guess_rate=STARTING_GUESS_RATE, swap_rate=STARTING_SWAP_RATE, bias=STARTING_BIAS): x_target = np.radians(x_target) pdf_vonmises_target = vonmises.pdf(x=x_target, kappa=np.radians(precision), loc=np.radians(bias)) pdf_vonmises_non_targets = [ vonmises.pdf(x=np.radians(x_nontarget), kappa=np.radians(precision), loc=np.radians(bias)) for x_nontarget in x_nontargets ] pdf_uniform = uniform.pdf(x_target, loc=-np.pi, scale=2 * np.pi) return (pdf_vonmises_target * (1 - guess_rate - swap_rate) + swap_rate * sum(pdf_vonmises_non_targets) / len(pdf_vonmises_non_targets) + pdf_uniform * guess_rate)
def _pdf(self, x, *lks): print 'lks', lks locs, kappas= lks[:len(lks)/2], lks[len(lks)/2:] print 'x', x print 'locs', locs print 'kapps', kappas #return np.sum([vonmises.pdf(x, l, k) for l, k in zip(locs, kappas)], 0) ret = np.zeros_like(x) for l, k in zip(locs, kappas): ret += vonmises.pdf(x, l, k) return ret / len(locs)
def vonCoordinates(mu, kappa, size, alpha): tRads = numpy.random.vonmises(mu, kappa, size) tPdf = vonmises.pdf(tRads, loc=mu, kappa=kappa) tInterval = vonmises.interval( alpha, loc=mu, kappa=kappa ) #Endpoints of the range that contains alpha percent of the distribution tCdf = vonmises.cdf(tInterval, loc=mu, kappa=kappa) tDegs = numpy.degrees(tRads) tmpArray = tools.coordinatetools.pol2cart(tDegs, dictGen['stimDist']) coordList = zip(tmpArray[0], tmpArray[1]) return (coordList, tPdf, tCdf)
def invsevonmises_pdf(theta, loc, kappa, lambda_): def normalized_constraint_inv_se(kappa, lambda_): def f(theta, kappa, lambda_): return ((1 - (1 + lambda_) * np.cos(theta) / 2) * vonmises.pdf((theta) - (1 - lambda_) * np.sin(theta) / 2, kappa=kappa, loc=0)) return quad(f, -np.pi, np.pi, args=(kappa, lambda_))[0] # inverse transformation by Newton's method C = np.vectorize(normalized_constraint_inv_se)(kappa, lambda_) theta_trans = inv_trans_se(theta, loc, lambda_) p = vonmises.pdf(theta_trans, loc=loc, kappa=kappa) / C return p
def jonespewsey_pdf(theta, loc, kappa, psi): def molecule(theta, loc, kappa, psi): d = np.power(np.cosh(kappa * psi) + np.sinh(kappa * psi) * np.cos(theta - loc), 1/psi) return d if np.any(np.abs(psi) < 1e-10): p = vonmises.pdf(theta, kappa=kappa, loc=loc) else: m = molecule(theta, loc, kappa, psi) C = 2 * np.pi * lpmv(0, 1/psi, np.cosh(kappa*psi)) p = m / C return p
def __makeProbTable(self): # the rods I need for the cumulative density function theta_rod = np.linspace(-np.pi, np.pi, 10000) # allocate memory for the probability table self.prob_table = np.zeros([self.rod_num, self.frame_num]) # the distribution of the otoliths P_oto = vonmises.pdf(theta_rod, self.kappa_oto) # compute kappas kappa1, kappa2 = self.__computeKappas() # for every frame orientation, calculate frame influence for i in range(self.frame_num): # the context provided by the frame P_frame0 = vonmises.pdf(theta_rod - self.frames[i], kappa1[i]) P_frame90 = vonmises.pdf(theta_rod - np.pi / 2 - self.frames[i], kappa2[i]) P_frame180 = vonmises.pdf(theta_rod - np.pi - self.frames[i], kappa1[i]) P_frame270 = vonmises.pdf( theta_rod - np.pi * 3 / 2 - self.frames[i], kappa2[i]) # initialize convolved distributions as P_frame P_frame = P_frame0 + P_frame90 + P_frame180 + P_frame270 # cumulative response distribution per frame cdf = np.cumsum(P_frame * P_oto) / np.sum(P_frame * P_oto) # reduce cdf to |rods| using spline interpolation cdf_continuous = splrep(theta_rod, cdf, s=0) cdf = splev(self.rods, cdf_continuous, der=0) # add lapse probability to distribution PCW = cdf # add probabilities to look-up table self.prob_table[:, i] = PCW
def test_VonMisesFeaturizer_describe_features(): feat = VonMisesFeaturizer() rnd_traj = np.random.randint(len(trajectories)) features = feat.transform([trajectories[rnd_traj]]) df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj])) for f in range(25): f_index = np.random.choice(len(df)) atom_inds = df.iloc[f_index].atominds bin_index = int(df.iloc[f_index].otherinfo.strip('bin-')) dihedral_value = md.compute_dihedrals(trajectories[rnd_traj], [atom_inds]) feature_value = [vm.pdf(i, loc=feat.loc, kappa=feat.kappa)[bin_index] for i in dihedral_value] assert (features[0][:, f_index] == feature_value).all()
def PlotPDF(): mu = 0.0 kappa_list = [0.0, 0.5, 1.0, 2.0, 4.0, 8.0] data = [] for kappa in kappa_list: x = np.linspace(-np.pi, np.pi, 100) if kappa == 0.0: y = 1 / (2.0 * np.pi) * np.ones(len(x)) else: y = vonmises.pdf(x, kappa) data.append(([x, y, "$\kappa = {0}$".format(kappa)])) data_list_plot.PlotContinuousData(data) plt.axis([-np.pi, np.pi, 0.0, 1.2]) plt.xlabel('$x$') plt.ylabel('Probability Density Function (PDF)') fig = plt.gcf() fig.savefig("./von_mises_pdf.eps")
def fit_curve(xfit,fit_type,param): if fit_type == 'n': yfit = mlab.normpdf(xfit ,param[1], param[2]) # mu, sigma elif fit_type == 'v': yfit = vonmises.pdf(xfit, kappa=param[1], loc=param[2], scale=param[3]) # kappa, circ_mu, circ_sd return yfit