def Lambda(l,k,n,m,Print=False): ''' ''' p=choose(n-m,k-l)*choose(m,l)*fact(k)*fact(n-k)/(fact(n)) if Print ==True: print(p,l,k,n,m) return p
def probFour(): n = 11 k = 7 p = 0.75 t = [] for i in range(0, k): f = (fact(n) / (fact(i) * fact(n - i))) * p**i * (1 - p)**(n - i) print(f) t.append(f) print(sum(t))
def catState(alpha, parity, dim): n = np.arange(dim) if parity == 'e': N = 1 / np.sqrt(2 * (1 + np.exp(-2 * np.abs(alpha)**2))) coeff = 2 * N * np.exp(-(np.abs(alpha)**2) / 2) state = coeff * alpha**(n) / np.sqrt(fact(n)) * np.mod(n + 1, 2) elif parity == 'o': N = 1 / np.sqrt(2 * (1 - np.exp(-2 * np.abs(alpha)**2))) coeff = 2 * N * np.exp(-(np.abs(alpha)**2) / 2) state = coeff * alpha**(n) / np.sqrt(fact(n)) * np.mod(n, 2) else: raise ValueError("parity must be 'e'(even) or 'o'(odd).") return state
def cat(initState, mode, alpha, parity, cutoff): n = np.arange(cutoff + 1) if parity == 'e': N = 1 / np.sqrt(2 * (1 + np.exp(-2 * np.abs(alpha)**2))) coeff = 2 * N * np.exp(-(np.abs(alpha)**2) / 2) initState[mode, :] = coeff * alpha**(n) / np.sqrt(fact(n)) * np.mod( n + 1, 2) elif parity == 'o': N = 1 / np.sqrt(2 * (1 - np.exp(-2 * np.abs(alpha)**2))) coeff = 2 * N * np.exp(-(np.abs(alpha)**2) / 2) initState[mode, :] = coeff * alpha**(n) / np.sqrt(fact(n)) * np.mod( n, 2) return initState
def FockWignerElement(xmat, pmat, l, m): start = time.time() A = np.max(np.dstack([l, m]), axis=2) B = np.abs(l - m) C = np.min(np.dstack([l, m]), axis=2) R0 = xmat**2 + pmat**2 xmat = xmat[:, :, np.newaxis, np.newaxis] pmat = pmat[:, :, np.newaxis, np.newaxis] R = xmat**2 + pmat**2 X = xmat + np.sign(l-m) * 1j * pmat W = 2 * (-1)**C * np.sqrt(2**(B) * fact(C) / fact(A)) W = W * np.exp(-R) * X**(B) S = Sonin(C, B, 2 * R0) return W * S
def hermite_1d(p, x): ''' evaluates 1D Hermite polynomial on [-1,1]. Ported directly from MATLAB code written by Dr. A. Doostan. p is the max total order of the PC x is a d-dimensional array of eval points [-1,1] ''' d = len(x) Her = np.zeros([p + 1, d]) if p == 0: Her[p, :] = np.ones(d) elif p == 1: Her[p - 1, :] = np.ones(d) Her[p, :] = x else: Her[0, :] = np.ones(d) Her[1, :] = x for ord in range(2, p + 1): Her[ord, :] = x * Her[ord - 1, :] - (ord - 1) * Her[ord - 2, :] # now normalize for i in range(p + 1): Her[i, :] = Her[i, :] / np.sqrt(fact(i)) return Her
def _Sonin(n, alpha, x): n = _to_2d_ndarray(n) alpha = _to_2d_ndarray(alpha) x = _to_2d_ndarray(x) a = fact(n + alpha) k0 = np.arange(np.max(n) + 1) k0 = k0[:, np.newaxis, np.newaxis] k = k0 * np.ones([np.max(n) + 1, n.shape[0], n.shape[0]], dtype=np.int) mask = np.ones(k.shape, dtype=np.int) for i in range(k.shape[0]): ind = (np.ones(n.shape) * i) > n mask[i, ind] = 0 k *= mask S = mask * (-1)**k * a / fact(n - k) / fact(k + alpha) / fact(k) X = x**k0 S = S[:, np.newaxis, np.newaxis, :, :] * X[:, :, :, np.newaxis, np.newaxis] return np.sum(S, axis=0)
def compute_shapley_mod(inputs, model, baseline=None, input_sparse=None): """ :param inputs: input data :param model: keras model :param baseline: baseline (if None then it is set to 0) :param input_sparse: input data for sparse model :return: Shapley values """ if baseline is None: baseline = np.zeros_like(inputs) results = np.zeros_like(inputs) n = inputs.shape[0] assert inputs.shape == (n,), inputs.shape # create mask mask = vec_bin_array(np.arange(2 ** (n - 1)), n - 1) # check dimensions assert mask.shape == (2 ** (n - 1), n - 1) coef = (fact(mask.sum(1)) * fact(n - mask.sum(1) - 1)) / fact(n) for index in range(n): # Copy mask and set the current player active mask_wo_index = np.insert(mask, index, np.zeros(2 ** (n - 1)), axis=1) mask_wi_index = np.insert(mask, index, np.ones(2 ** (n - 1)), axis=1) assert mask_wo_index.shape == (2 ** (n - 1), n), 'Mask shape does not match' assert np.max(mask_wo_index) == 1, np.max(mask_wo_index) assert np.min(mask_wo_index) == 0, np.min(mask_wo_index) # Calculate number of baselines n_baseline_x_feature = int(np.size(baseline, 0) / n) if n_baseline_x_feature > 1: # Kron on mask mask_wo_index_new = np.kron(np.ones(n_baseline_x_feature), mask_wo_index) mask_wi_index_new = np.kron(np.ones(n_baseline_x_feature), mask_wi_index) # Kron on input if input_sparse is None: inputs_new = np.kron(np.ones(n_baseline_x_feature), inputs) else: inputs_new = input_sparse.copy() else: inputs_new = inputs mask_wo_index_new = mask_wo_index mask_wi_index_new = mask_wi_index run_wo_i = model(inputs_new * mask_wo_index_new + baseline * (1 - mask_wo_index_new)) # run all masks at once run_wi_i = model(inputs_new * mask_wi_index_new + baseline * (1 - mask_wi_index_new)) # run all masks at once r = (run_wi_i - run_wo_i) * coef results[index] = r.sum() return results
def _Wigner_Moyal(rho, xmat, pmat, tol): dim = rho.shape[0] [l, m] = np.indices([dim, dim]) A = np.max(np.dstack([l, m]), axis=2) B = np.abs(l - m) C = np.min(np.dstack([l, m]), axis=2) R0 = xmat**2 + pmat**2 xmat = xmat[:, :, np.newaxis, np.newaxis] pmat = pmat[:, :, np.newaxis, np.newaxis] R = xmat**2 + pmat**2 X = xmat - np.sign(l - m) * 1j * pmat W = 2 * (-1)**C * np.sqrt(2**(B) * fact(C) / fact(A)) W = W * np.exp(-R) * X**(B) S = _Sonin(C, B, 2 * R0) W = W * S W = rho * W W = np.sum(np.sum(W, axis=-1), axis=-1) if np.max(np.imag(W)) < tol: W = np.real(W) else: raise ValueError("Wigner plot has imaginary value.") return W
def Q2Om(Q, kT, m, ret_redmass=False): '''Computes the paramters Omega_i,j^(l,s) as in Janssen's PhD page 93 (see also hirschfelder page 526 and Ema's INFN book, page 29 left), [Q2Om means: "convert Q to Omega"]''' Om = np.zeros(Q.shape) mu = np.zeros(Q.shape[2:4]) for ll, ss in it.product(range(Q.shape[0]), range(Q.shape[1])): for ii, jj in it.product(range(Q.shape[2]), range(Q.shape[3])): l = ll + 1 s = ss + 1 mu[ii, jj] = m[ii] * m[jj] / (m[ii] + m[jj]) # reduced mass Om[ll, ss, ii, jj] = Q[ll, ss, ii, jj] * 0.5 * fact(s + 1) * ( 1 - 0.5 * (1 + (-1)**l) / (1 + l)) / np.sqrt(2 * np.pi * mu[ii, jj] / kT) if ret_redmass: return Om, mu return Om
def eta(jj, ii, kk): eta = 0 for i in range(2 * kk + 1): if 2 * kk - i > jj: comb1 = 0 if 2 * kk - i <= jj: comb1 = fact(jj) / fact(2 * kk - i) / fact(jj - (2 * kk - i)) if i > ii: comb2 = 0 if i <= ii: comb2 = fact(ii) / fact(i) / fact(ii - i) eta += comb1 * comb2 * (-1)**i return eta
def coherent(initState, mode, alpha, cutoff): n = np.arange(cutoff + 1) state = np.exp(-0.5 * np.abs(alpha)**2) / np.sqrt(fact([n])) * alpha**n initState[mode, :] = state return initState
tau = 5 / (5 + j) # Среднее время обработки сообщений print( "Количество каналов передачи n = {}\nСообщений в минуту λ = {}\nСреднее время обработки сообщений τ = {}" .format(n, lambd, tau)) mu = 1 / tau # Интенсивность потока обслуживания ro = lambd / mu # Приведенная интенсивность потока заявок (интенсивность нагрузки) print( "Интенсивность потока обслуживания μ = {}\nПриведенная интенсивность потока ρ = {}\n" .format(mu, ro)) P = [ 0 ] # Предельные вероятности (среднее относительное время, которое канал занят (p0 - все свободны)) for i in range(0, n + 1): P[0] += (ro**i) / fact(i) P[0] = P[0]**-1 for i in range(1, n + 1): P.append((ro**i) / fact(i) * P[0]) print("Предельные вероятности P = {}\n".format(P)) P_o = (ro**n) / fact(n) * P[0] # Вероятность отказа (все каналы заняты) Q = 1 - P_o # Относительная пропускная способность A = lambd * Q # Абсолютная пропускная способность k = 0 # Среднее число занятых каналов for i in range(0, n + 1): k += i * P[i] print("Теоретические значения:") print("Относительная пропускная способность Q = ", Q) print("Абсолютная пропускная способность A = ", A)
def choose(n, k): return fact(n) / (fact(n - k) * fact(k))
tau = 5 / (5 + j) # Среднее время обработки сообщений print("Дано:") print("i = {}, j = {}".format(i, j)) print( "Количество каналов передачи n = {}, Сообщений в минуту λ = {}, Среднее время обработки сообщений τ = {}" .format(n, lmb, tau)) mu = 1 / tau # Интенсивность потока обслуживания ro = lmb / mu # Приведенная интенсивность потока print( "Интенсивность потока обслуживания μ = {}, Приведенная интенсивность потока ρ = {}" .format(mu, ro)) P = [] # Предельные вероятности P.append(1 + ro) for i in range(2, n + 1): P[0] += (ro**i) / fact(i) P[0] = P[0]**-1 P.append(ro * P[0]) for i in range(2, n + 1): P.append((ro**i) / fact(i) * P[0]) print("P = {}".format(P)) P_otk = (ro**n) / fact(n) * P[ 0] # Вероятность отказа, т. е. того, что заявка покинет СМО не обслуженной Q = 1 - P_otk # Относительная пропускная способность A = lmb * Q # Абсолютная пропускная способность k = 0 # Среднее число занятых каналов for i in range(0, n + 1): k += i * P[i]
def choose(n,k): ''' This function returns the combinations of choosing n out of k ''' return fact(n)/(fact(n-k)*fact(k))
def pascal_pyramid(n): p = np.zeros((n + 1, n + 1)) p = [[(fact(n) / (fact(n - i - j) * fact(i) * fact(j))) if j < n + 1 - i else 0 for j in range(n + 1)] for i in range(n + 1)] return p
def poisson(n, mean): return np.exp(-mean) * (mean**n) / fact(n)
cpsi = np.sqrt(1 / psipre[:, :, None] / (1 - psirat[:, :, None] * ceiwt2)) cf = -(wg[-3:, None] * (1 - ceiwt)) / (wp[:, :, None] - wm[:, :, None] * ceiwt) cesum = rat[:, :, None] * cf * delta[:, -3:, None] / ca cherm = np.ones((2, 3, 9, ntime)) cherm[:, :, 1] = 2 * np.real(cesum) for i in range(2): for j in range(3): for k in range(2, 9): cherm[i, j, k] = 2 * (np.real(cesum[i, j]) * cherm[i, j, k - 1] - (k - 1) * cherm[i, j, k - 2]) c0 = cpsi * np.exp(delta2[:, -3:, None] * cf) covlp = np.zeros((2, 3, 6, 4, ntime), dtype=complex) pre = 1 / np.sqrt( fact(time_points[:4])[:, None] * fact(time_points[:6]) * 2**(time_points[:4, None] + time_points[:6])) kstar = (time_points[:4, None] + time_points[:6]) // 2 kstar = np.rint(kstar).astype(int) d1 = du[-3:] / np.sqrt(2) d2 = d1**2 si = np.sqrt(time_points[:3]) sip = np.sqrt(time_points[1:4]) jj = np.arange(1, 4) jj = jj[:, None] + jj - 1 sf = np.sqrt(jj - 1) sfp = np.sqrt(jj) covlp2 = np.zeros((2, 3, 3, 3, ntime), dtype=complex)
def coherentState(alpha, dim): n = np.arange(dim) state = np.exp(-0.5 * np.abs(alpha)**2) / np.sqrt(fact([n])) * alpha**n return state
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
tau = 5 / (5 + j) # Среднее время обработки сообщений print( "Количество каналов передачи n = {}\nРазмер очереди m = {}\nСообщений в минуту λ = {}\nСреднее время обработки сообщений τ = {}" .format(n, m, lambd, tau)) mu = 1 / tau # Интенсивность потока обслуживания ro = lambd / mu # Приведенная интенсивность потока заявок (интенсивность нагрузки) print( "Интенсивность потока обслуживания μ = {}\nПриведенная интенсивность потока ρ = {}\n" .format(mu, ro)) P = [ 0 ] # Предельные вероятности (среднее относительное время, которое канал занят (p0 - все свободны)) for i in range(0, n + 1): P[0] += (ro**i) / fact(i) P[0] += (ro**(n + 1)) * (1 - (ro / n)**m) / (fact(n) * (n - ro)) P[0] = P[0]**-1 for i in range(1, n + 1): P.append((ro**i) / fact(i) * P[0]) for r in range(1, m + 1): P.append((ro**(n + r)) / (n**r * fact(n)) * P[0]) print("Предельные вероятности P = {}\n".format(P)) P_o = P[n + m] # Вероятность отказа (все каналы заняты) Q = 1 - P_o # Относительная пропускная способность A = lambd * Q # Абсолютная пропускная способность k = ro * (1 - ((ro**(n + m)) / (n**m * fact(n))) * P[0]) # Среднее число занятых каналов # Средняя длина очереди L_och = (ro**(n + 1) * P[0] * (1 - (m + 1 - m * ro / n) *