def rnm(self, rho, n, m): """ Zernike polynomial R coefficient Parameters ---------- rho: numpy array array of radial polar coordinates n: int Zernike polynomial radial order m: int Zernike polynomial azimuthal order """ if n < 0: raise ValueError("n must be >= 0") elif m < 0: raise ValueError("m must be >= 0") elif n < m: raise ValueError("n must be >= m") elif (n - m) % 2 == 0: R = 0. for s in np.arange(0, (n - m) / 2 + 1): r = rho**(n - 2 * s) * ((-1.)**s * fact(n - s)) / ( fact(s) * fact((n + m) / 2 - s) * fact((n - m) / 2 - s)) R = R + r else: R = 0. return R
def construct_markov_transition_matrix(net, conditioned_on={}, fatigue_tau=None, feedforward_boost=None): tmp = net.state_map() n_states = count_states(net) if n_states > 128: ans = raw_input( "really compute full %dx%d transition matrix over %d permutations? [y/N] " % (n_states, n_states, fact(len(net._nodes)))) if ans[0] not in "yY": return A = np.zeros((n_states, n_states)) orderings = itertools.permutations(enumerate(net.iter_nodes())) u = 1.0 / fact(len(net._nodes)) for ns in orderings: for i, j in itertools.product(range(n_states), range(n_states)): A[i][j] += u * transition_probability(net, id_to_state( net, j), id_to_state(net, i), ns, conditioned_on, fatigue_tau, feedforward_boost) net.evidence(tmp) return A
def first_der(self, x, a=None): """Compute first derivative""" r = np.empty((self.n + 1)) xcontr = np.linspace(0, 1, self.n + 1) if a is None: a = [1] * (self.n + 1) for i in range(0, self.n + 1): k = fact(self.n) / fact(i) / fact(self.n - i) # 1 alpha = ((1.0 - x)**(self.n - i + self.n2)) * (x**(i + self.n1)) alpha_p_1 = (i + self.n1) * (x**(i + self.n1 - 1.0)) * ( (1.0 - x)**(self.n - i + self.n2)) alpha_p_2 = (self.n - i + self.n2) * ( (1.0 - x)**(self.n - i + self.n2 - 1.0)) * (x**(i + self.n1)) alpha_p = alpha_p_1 - alpha_p_2 # 2 beta = np.cos(x - xcontr[i])**self.exp beta_p = -self.exp * (np.cos(x - xcontr[i]) **(self.exp - 1.0)) * np.sin(x - xcontr[i]) r[i] = a[i] * k * self.delta_frac * ((alpha * beta_p) + (beta * alpha_p)) return r
def _bernstein(self, x): """Bernstain polinomial basis""" r = np.empty((self.n + 1, len(x)), dtype=x.dtype) xcontr = np.linspace(0, 1, self.n + 1) for i in range(0, self.n + 1): k = fact(self.n) / fact(i) / fact(self.n - i) local = self.delta_frac * (np.cos(x - xcontr[i])**self.exp) r[i] = (k * (1.0 - x)**(self.n - i) * x**i) * local return r
def rnm(self, rho, n, m): if n < 0: raise ValueError("n must be >= 0") elif m < 0: raise ValueError("m must be >= 0") elif n < m: raise ValueError("n must be >= m") elif (n-m)%2 == 0: R = 0. for s in np.arange(0, (n-m)/2+1): r = rho**(n-2*s)*((-1.)**s * fact(n-s)) / (fact(s)*fact((n+m)/2-s)*fact((n-m)/2-s)) R = R + r else: R = 0. return R
def zero_der(self, x, a=None): """Compute zeroth derivative""" r = np.empty((self.n + 1)) xcontr = np.linspace(0, 1, self.n + 1) if a is None: a = [1] * (self.n + 1) for i in range(0, self.n + 1): k = fact(self.n) / fact(i) / fact(self.n - i) r[i] = a[i] * k * ((1.0 - x)**(self.n - i + self.n2)) * (x**( i + self.n1)) * self.delta_frac * ( (np.cos(x - xcontr[i]))**self.exp) return r
def integral(n): """Calculate the integral from 0 to 1 of x^n e^{x-1} dx using the closed form solution (-1)^n !n + (-1)^{n+1} n!/e. """ #raise NotImplementedError("Problem 3 Incomplete") r = n%2 return (-1)**r*subf(n)+(-1)**(r+1)*fact(n)/exp(1)
def question_c(b=3, a=0, N=0.0, debug=True): approx = lambda N: exp(N) * ((b - a)**N / (fact(N) * 2**(2 * N - 1))) while 10**-10 <= approx(N): N = N + 1.0 print N if debug is True: print "\nDEBUG MODE: ON [Question 3 (c.)]:" print "Number of Chebyshev Points N = ", int(N) print "Approximated Value, @ N = ", approx(N) return N
def series(self, input_vf, input_num_steps=None, input_pix_dims=None): """ Series method """ self.initialise_input(input_vf) self.initialise_number_of_steps(input_num_steps=input_num_steps, input_pix_dims=input_pix_dims) self.phi = np.copy(self.vf) # phi is initialised to vf not to zero. for k in range(2, self.num_steps): jac_v = jac.iterative_jacobian_product(self.vf, k) self.phi = self.phi[...] + jac_v[...] / fact(k) return self.phi
def poisson_likelihood_2(norm1_guess, norm2_guess, const_guess, fore_map, data_map, srctempl_map, exp=None, sr=None): """Compute the log-likelihood as decribed here: http://iopscience.iop.org/article/10.1088/0004-637X/750/1/3/pdf where the model to fit to data is given by norm*fore_map+const. norm1_guess : float initial guess for normalization parameter norm2_guess : float initial guess for normalization parameter const_guess : float initial guess for constant parameter fore_map : numpy array helapix map of foreground model data_map : numpy array helapix map of data. It could be either a count map or a flux map. If a counts map is given, an exposure map should be given too. See next parameter. srctempl_map : numpy array helapix map of source template exp : numpy array or None helapix map of the exposure. Should be given if the data map is in counts (beacause foreground map is in flux units by default and it needs to be turned to counts to be fitted). While, If data map is in flux units, do not declare this parameter, which is None by default. sr : float or None pixel area -> 4*pi/Npix """ a = norm1_guess b = const_guess c = norm2_guess s = srctempl_map factorial_data = fact(data_map) lh = 0 if exp is not None: for i, f in enumerate(fore_map): model_counts = (a*f+c*s[i]+b)*exp[i]*sr if data_map[i] > 50: uno = 0.5*(data_map[i]-model_counts)/np.sqrt(model_counts) due = np.log(1./np.sqrt(2*np.pi*model_counts)) lh = lh + uno - due else: due = np.log(factorial_data[i]) tre = data_map[i]*np.log(model_counts) lh = lh + model_counts + due - tre else: for i, f in enumerate(fore_map): lh += ((a*f+c*s[i]+b)+np.log(factorial_data[i]) -\ data_map[i]*np.log((a*f+c*s[i]+b))) return lh
def series_mod(self, input_vf, input_num_steps=None, input_pix_dims=None): """ """ # (0) self.initialise_input(input_vf) self.initialise_number_of_steps(input_num_steps=input_num_steps, input_pix_dims=input_pix_dims) jac_v = copy.deepcopy(self.vf) self.phi = np.copy(self.vf) # phi is initialised to vf not to zero. for k in range(1, input_num_steps): jac_v = jac.jacobian_product(jac_v, self.vf) self.phi = self.phi[...] + jac_v[...] / fact(k) return self.phi
def construct_markov_transition_matrix(net, conditioned_on={}, fatigue_tau=None, feedforward_boost=None): tmp = net.state_map() n_states = count_states(net) if n_states > 128: ans = raw_input("really compute full %dx%d transition matrix over %d permutations? [y/N] " % (n_states, n_states, fact(len(net._nodes)))) if ans[0] not in "yY": return A = np.zeros((n_states, n_states)) orderings = itertools.permutations(enumerate(net.iter_nodes())) u = 1.0 / fact(len(net._nodes)) for ns in orderings: for i,j in itertools.product(range(n_states), range(n_states)): A[i][j] += u * transition_probability(net, id_to_state(net, j), id_to_state(net, i), ns, conditioned_on, fatigue_tau, feedforward_boost) net.evidence(tmp) return A
def poisson(k, mean, coeff): ''' Parameters ---------- k: The real number which is to be mapped to a poisson distribution function (pdf). mean: The lambda parameter (mean) of the pdf. coeff: The coefficient of the pdf. Returns ---------- poiss_k: The mapped real number. ''' poiss_k = coeff * (mean**k / fact(k)) return poiss_k
def initialise_number_of_steps(self, input_num_steps=None, input_pix_dims=None): """ Automatic steps selector """ if input_num_steps is None: norm = np.linalg.norm(self.vf, axis=self.dimension - 1) max_norm = np.max(norm[:]) if max_norm < 0: raise ValueError('Maximum norm is invalid.') if max_norm == 0: return self.phi if input_pix_dims is None: self.num_steps = max( [0, np.ceil(np.log2(max_norm / 0.5)).astype('int')]) + 3 else: min_size = np.min(input_pix_dims[input_pix_dims > 0]) self.num_steps = max([ 0, np.ceil(np.log2(max_norm / (min_size / 2))).astype('int') ]) + 3 elif input_num_steps is 'test_method': norm_vf = np.linalg.norm(self.vf, axis=self.vf.ndim - 1) max_norm = np.max(norm_vf) toll = 1e-3 k = 10 while max_norm / fact(k) > toll: k += 1 self.num_steps = k print('automatic steps selector for series method: ' + str(k)) elif isinstance(input_num_steps, int): self.num_steps = input_num_steps else: raise IOError
def poisson_likelihood(norm_guess, const_guess, fore_map, data_map, exp=None, sr=None): """Compute the log-likelihood as decribed here: http://iopscience.iop.org/article/10.1088/0004-637X/750/1/3/pdf where the model to fit to data is given by norm*fore_map+const. norm_guess : float initial guess for normalization parameter const_guess : float initial guess for constant parameter fore_map : numpy array helapix map of foreground model data_map : numpy array helapix map of data. It could be either a count map or a flux map. If a counts map is given, an exposure map should be given too. See next parameter. exp : numpy array or None helapix map of the exposure. Should be given if the data map is in counts (beacause foreground map is in flux units by default and it needs to be turned to counts to be fitted). While, If data map is in flux units, do not declare this parameter, which is None by default. sr : float or None pixel area -> 4*pi/Npix """ a = norm_guess b = const_guess factorial_data = fact(data_map) lh = 0 if exp is not None: for i, f in enumerate(fore_map): lh += (a*f+b)*exp[i]*sr + np.log(factorial_data[i]) - \ data_map[i]*np.log((a*f+b)*exp[i]*sr) else: for i, f in enumerate(fore_map): lh += np.sum(((a*f+b)+np.log(factorial_data[i]) -\ data_map[i]*np.log((a*f+b)))) return lh
def g(i, par_i, data): """ returns the probability that node (attribute) <i> of data matrix <data> has the parents array <par_i>. """ xi = data[:,i] # data column i Vi = unique(xi) # unique values in data column i ri = len(Vi) # number of unique values in data column i d = data[:,par_i] # data truncated to only the parent nodes m,n = shape(d) # size of truncated data z = len(par_i) # number of parent nodes in par_i # if no parents, return the naive bayes probability : if z == 0: N_ij = len(data) alpha_i_ = array([]) for k in range(ri): alpha_i_k = sum(xi == Vi[k]) alpha_i_ = append(alpha_i_, alpha_i_k) res = fact(ri - 1) / fact(N_ij + ri - 1) * prod(fact(alpha_i_)) # otherwise include conditional probability terms : else: unq = [] # unique parent values list # iterate through each dimenson : for j in range(n): unq.append(unique(d[:,j])) # append the unique values of parent j phi_i = cartesian(unq) # form the cross product of parental values qi = len(phi_i) # number of possible parental combinations res = 1 for j in range(qi): N_ij = sum((d == phi_i[j]).all(axis=1)) alpha_ij = array([]) for k in range(ri): idx = where(xi == Vi[k]) alpha_ijk = sum((d[idx] == phi_i[j]).all(axis=1)) alpha_ij = append(alpha_ij, alpha_ijk) eta = fact(ri - 1) / fact(N_ij + ri - 1) * prod(fact(alpha_ij)) res *= eta return res
def binomial(x, n, p): B = float(fact(n)) / (fact(x) * fact(n - x)) * \ p ** x * (1 - p) ** (n - x) return B
lamdaMatrix=np.dstack((lamdaMatrix,DmatNumerical)) print lamdaMatrix.shape # print lamdaMatrix lamdaFinal=np.sum(lamdaMatrix,axis = 2) # print "lamda final ",lamdaFinal # sum = 0 for k in xrange(0,m-1): d=lamdaFinal/2.0 # print "before raise ",k # print d d=d**k # print "after raise ",k # print d d=d/(fact(k)) # print "d ",d sum=sum+d # print "sum ",sum # sum = sum + (((lamdaFinal/2))**k)/(abs(fact(k))) # print "sum matrix" # print sum # print "......" # print "......" # print "......" disimilarityFinal = np.exp(-1*(lamdaFinal/2))*sum # print "dissimilarity" # print "......" # print "......" # print "......"
from scipy.misc import factorial as fact print fact(40)/fact(20)**2
def three_j_symbol(jm1, jm2, jm3): j1, m1 = jm1 j2, m2 = jm2 j3, m3 = jm3 if (m1+m2+m3 != 0 or m1 < -j1 or m1 > j1 or m2 < -j2 or m2 > j2 or m3 < -j3 or m3 > j3 or j3 > j1 + j2 or j3 < abs(j1-j2)): return .0 result = -1.0 if (j1-j2-m3) % 2 else 1.0 result *= sqrt(fact(j1+j2-j3)*fact(j1-j2+j3)*fact(-j1+j2+j3)/fact(j1+j2+j3+1)) result *= sqrt(fact(j1-m1)*fact(j1+m1)*fact(j2-m2)*fact(j2+m2)*fact(j3-m3)*fact(j3+m3)) t_min = max(j2-j3-m1,j1-j3+m2,0) t_max = min(j1-m1,j2+m2,j1+j2-j3) t_sum = 0 for t in range(t_min,t_max+1): t_sum += (-1.0 if t % 2 else 1.0)/(fact(t)*fact(j3-j2+m1+t)*fact(j3-j1-m2+t)*fact(j1+j2-j3-t)*fact(j1-m1-t)*fact(j2+m2-t)) result *= t_sum return result
def second_der(self, x, a=None): """Compute second derivative""" r = np.empty((self.n + 1)) xcontr = np.linspace(0, 1, self.n + 1) if a is None: a = [1] * (self.n + 1) for i in range(0, self.n + 1): k = fact(self.n) / fact(i) / fact(self.n - i) cos = np.cos(x - xcontr[i]) sin = np.sin(x - xcontr[i]) # 1 ------------------ theta_1 = (x**(i + self.n1)) * ((1.0 - x)**(self.n - i + self.n2)) theta_1_p_1 = (x**(i + self.n1)) * (self.n - i + self.n2) * ( (1.0 - x)**(self.n - i + self.n2 - 1.0)) * -1.0 theta_1_p_2 = (i + self.n1) * (x**(i + self.n1 - 1.0)) * ( (1.0 - x)**(self.n - i + self.n2)) theta_1_p = theta_1_p_1 + theta_1_p_2 omega_1 = (cos**(self.exp - 1.0)) * sin omega_1_p_1 = (cos**(self.exp - 1.0)) * cos omega_1_p_2 = (self.exp - 1.0) * (cos**(self.exp - 1.0)) * sin * sin * -1.0 omega_1_p = omega_1_p_1 + omega_1_p_2 # 2 ------------------ theta_2 = (x**(i + self.n1)) * ( (1.0 - x)**(self.n - i + self.n2 - 1.0)) theta_2_p_1 = (x**(i + self.n1)) * (self.n - i + self.n2 - 1.0) * ( (1.0 - x)**(self.n - i + self.n2 - 2.0)) * -1.0 theta_2_p_2 = (i + self.n1) * (x**(i + self.n1 - 1.0)) * ( (1.0 - x)**(self.n - i + self.n2 - 1.0)) theta_2_p = theta_2_p_1 + theta_2_p_2 omega_2 = cos**self.exp omega_2_p = -self.exp * (cos**(self.exp - 1.0)) * sin # 3 ------------------ theta_3 = (x**(i + self.n1 - 1.0)) * ( (1.0 - x)**(self.n - i + self.n2)) theta_3_p_1 = (x**(i + self.n1 - 1.0)) * (self.n - i + self.n2) * ( (1.0 - x)**(self.n - i + self.n2 - 1.0)) * -1.0 theta_3_p_2 = (i + self.n1 - 1.0) * (x**(i + self.n1 - 2)) * ( (1.0 - x)**(self.n - i + self.n2)) theta_3_p = theta_3_p_1 + theta_3_p_2 omega_3 = cos**self.exp # SAME AS OMEGA_2 omega_3_p = -self.exp * (cos**(self.exp - 1.0)) * sin # SAME AS OMEGA_2_P # Summation ---------- term_1 = self.exp * ((theta_1 * omega_1_p) + (theta_1_p * omega_1)) term_2 = (self.n - i + self.n2) * ((theta_2 * omega_2_p) + (theta_2_p * omega_2)) term_3 = (i + self.n1) * ((theta_3 * omega_3_p) + (theta_3_p * omega_3)) r[i] = a[i] * k * self.delta_frac * (-term_1 - term_2 + term_3) return r
def perm(N, k, exact=0): return comb(N, k, exact) * fact(k, exact)
def three_j_symbol(jm1, jm2, jm3): j1, m1 = jm1 j2, m2 = jm2 j3, m3 = jm3 if (m1 + m2 + m3 != 0 or m1 < -j1 or m1 > j1 or m2 < -j2 or m2 > j2 or m3 < -j3 or m3 > j3 or j3 > j1 + j2 or j3 < abs(j1 - j2)): return .0 result = -1.0 if (j1 - j2 - m3) % 2 else 1.0 result *= sqrt( fact(j1 + j2 - j3) * fact(j1 - j2 + j3) * fact(-j1 + j2 + j3) / fact(j1 + j2 + j3 + 1)) result *= sqrt( fact(j1 - m1) * fact(j1 + m1) * fact(j2 - m2) * fact(j2 + m2) * fact(j3 - m3) * fact(j3 + m3)) t_min = max(j2 - j3 - m1, j1 - j3 + m2, 0) t_max = min(j1 - m1, j2 + m2, j1 + j2 - j3) t_sum = 0 for t in range(t_min, t_max + 1): t_sum += (-1.0 if t % 2 else 1.0) / ( fact(t) * fact(j3 - j2 + m1 + t) * fact(j3 - j1 - m2 + t) * fact(j1 + j2 - j3 - t) * fact(j1 - m1 - t) * fact(j2 + m2 - t)) result *= t_sum return result
def three_j_symbol(jm1, jm2, jm3): r""" Calculate the three-j symbol .. math:: \begin{pmatrix} l_1 & l_2 & l_3\\ m_1 & m_2 & m_3 \end{pmatrix}. Parameters ---------- jm1 : tuple of integers (j_1 m_1) jm2 : tuple of integers (j_2 m_2) jm3 : tuple of integers (j_3 m_3) Returns ------- three_j_sym : scalar Three-j symbol. """ j1, m1 = jm1 j2, m2 = jm2 j3, m3 = jm3 if (m1+m2+m3 != 0 or m1 < -j1 or m1 > j1 or m2 < -j2 or m2 > j2 or m3 < -j3 or m3 > j3 or j3 > j1 + j2 or j3 < abs(j1-j2)): return .0 three_j_sym = -1.0 if (j1-j2-m3) % 2 else 1.0 three_j_sym *= sqrt(fact(j1+j2-j3)*fact(j1-j2+j3)*fact(-j1+j2+j3)/fact(j1+j2+j3+1)) three_j_sym *= sqrt(fact(j1-m1)*fact(j1+m1)*fact(j2-m2)*fact(j2+m2)*fact(j3-m3)*fact(j3+m3)) t_min = max(j2-j3-m1,j1-j3+m2,0) t_max = min(j1-m1,j2+m2,j1+j2-j3) t_sum = 0 for t in range(t_min,t_max+1): t_sum += (-1.0 if t % 2 else 1.0)/(fact(t)*fact(j3-j2+m1+t)*fact(j3-j1-m2+t)*fact(j1+j2-j3-t)*fact(j1-m1-t)*fact(j2+m2-t)) three_j_sym *= t_sum return three_j_sym
def three_j_symbol(jm1, jm2, jm3): r""" Calculate the three-j symbol .. math:: \begin{pmatrix} l_1 & l_2 & l_3\\ m_1 & m_2 & m_3 \end{pmatrix}. Parameters ---------- jm1 : tuple of integers (j_1 m_1) jm2 : tuple of integers (j_2 m_2) jm3 : tuple of integers (j_3 m_3) Returns ------- three_j_sym : scalar Three-j symbol. """ j1, m1 = jm1 j2, m2 = jm2 j3, m3 = jm3 if (m1 + m2 + m3 != 0 or m1 < -j1 or m1 > j1 or m2 < -j2 or m2 > j2 or m3 < -j3 or m3 > j3 or j3 > j1 + j2 or j3 < abs(j1 - j2)): return .0 three_j_sym = -1.0 if (j1 - j2 - m3) % 2 else 1.0 three_j_sym *= np.sqrt(fact(j1+j2-j3)*fact(j1-j2+j3)* \ fact(-j1+j2+j3)/fact(j1+j2+j3+1)) three_j_sym *= np.sqrt(fact(j1-m1)*fact(j1+m1)*fact(j2-m2)* \ fact(j2+m2)*fact(j3-m3)*fact(j3+m3)) t_min = max(j2 - j3 - m1, j1 - j3 + m2, 0) t_max = min(j1 - m1, j2 + m2, j1 + j2 - j3) t_sum = 0 for t in range(t_min, t_max + 1): t_sum += (-1.0 if t % 2 else 1.0)/(fact(t)*fact(j3-j2+m1+t)* \ fact(j3-j1-m2+t)*fact(j1+j2-j3-t)*fact(j1-m1-t)*fact(j2+m2-t)) three_j_sym *= t_sum return three_j_sym
X = linspace(0.0, 1.0, 2*small.shape[0],endpoint=False) Y = linspace(0.0, 1.0, 2*small.shape[1],endpoint=False) T =[] for i in X: for j in Y: T.append([i,j]) T = array(T) m = 3 d = 2 def len(x1, x2): return sqrt((x1[0]-x2[0])**2 + (x1[1] - x2[1])**2) Econst = (-1)**(d/2 + m + 1)/(2**(2*m-1)*pi**(d/2)*fact(m-1)*fact(m - d/2)) def E(s, t): l = len(s,t) if l == 0: l = 1 res = Econst*l**(2*m-d) * log(l) return res K = np.zeros((T.shape[0], t.shape[0])) print K.shape for i in xrange(K.shape[0]): for j in xrange(K.shape[1]): print i,j