def campana(f0, A0, I0, duracion, fsampl): ts = pyl.arange(0, duracion, 1 / fsampl) # creo el espacio temporal Tao = duracion / 3 fc = f0 fm = 2 * f0 I_t = I0 * pyl.exp(-ts / Tao) # para la campana A_t = A0 * pyl.exp(-ts / Tao) # para la campana ym = pyl.sin(2 * pyl.pi * fm * ts) # función modulada # Señal FM final con sus componentes que varían en el tiempo yc = A_t * pyl.sin(2 * pyl.pi * fc * ts + (I_t * ym)) return yc
def _make_log_freq_map(self): """ :: For the given ncoef (bands-per-octave) and nfft, calculate the center frequencies and bandwidths of linear and log-scaled frequency axes for a constant-Q transform. """ fp = self.feature_params bpo = float(self.nbpo) # Bands per octave self._fftN = float(self.nfft) hi_edge = float(self.hi) lo_edge = float(self.lo) f_ratio = 2.0**(1.0 / bpo) # Constant-Q bandwidth self._cqtN = float(P.floor(P.log(hi_edge / lo_edge) / P.log(f_ratio))) self._dctN = self._cqtN self._outN = float(self.nfft / 2 + 1) if self._cqtN < 1: print("warning: cqtN not positive definite") mxnorm = P.empty(self._cqtN) # Normalization coefficients fftfrqs = self._fftfrqs #P.array([i * self.sample_rate / float(self._fftN) for i in P.arange(self._outN)]) logfrqs = P.array([ lo_edge * P.exp(P.log(2.0) * i / bpo) for i in P.arange(self._cqtN) ]) logfbws = P.array([ max(logfrqs[i] * (f_ratio - 1.0), self.sample_rate / float(self._fftN)) for i in P.arange(self._cqtN) ]) #self._fftfrqs = fftfrqs self._logfrqs = logfrqs self._logfbws = logfbws self._make_cqt()
def _pvoc(self, X_hat, Phi_hat=None, R=None): """ :: a phase vocoder - time-stretch inputs: X_hat - estimate of signal magnitude [Phi_hat] - estimate of signal phase [R] - resynthesis hop ratio output: updates self.X_hat with modified complex spectrum """ N = self.nfft W = self.wfft H = self.nhop R = 1.0 if R is None else R dphi = (2 * P.pi * H * P.arange(N / 2 + 1)) / N print("Phase Vocoder Resynthesis...", N, W, H, R) A = P.angle(self.STFT) if Phi_hat is None else Phi_hat phs = A[:, 0] self.X_hat = [] n_cols = X_hat.shape[1] t = 0 while P.floor(t) < n_cols: tf = t - P.floor(t) idx = P.arange(2) + int(P.floor(t)) idx[1] = n_cols - 1 if t >= n_cols - 1 else idx[1] Xh = X_hat[:, idx] Xh = (1 - tf) * Xh[:, 0] + tf * Xh[:, 1] self.X_hat.append(Xh * P.exp(1j * phs)) U = A[:, idx[1]] - A[:, idx[0]] - dphi U = U - P.np.round(U / (2 * P.pi)) * 2 * P.pi phs += (U + dphi) t += P.randn() * P.sqrt(PVOC_VAR * R) + R # 10% variance self.X_hat = P.np.array(self.X_hat).T
def _pvoc2(self, X_hat, Phi_hat=None, R=None): """ :: alternate (batch) implementation of phase vocoder - time-stretch inputs: X_hat - estimate of signal magnitude [Phi_hat] - estimate of signal phase [R] - resynthesis hop ratio output: updates self.X_hat with modified complex spectrum """ N, W, H = self.nfft, self.wfft, self.nhop R = 1.0 if R is None else R dphi = P.atleast_2d((2 * P.pi * H * P.arange(N / 2 + 1)) / N).T print("Phase Vocoder Resynthesis...", N, W, H, R) A = P.angle(self.STFT) if Phi_hat is None else Phi_hat U = P.diff(A, 1) - dphi U = U - P.np.round(U / (2 * P.pi)) * 2 * P.pi t = P.arange(0, n_cols, R) tf = t - P.floor(t) phs = P.c_[A[:, 0], U] phs += U[:, idx[1]] + dphi # Problem, what is idx ? Xh = (1 - tf) * Xh[:-1] + tf * Xh[1:] Xh *= P.exp(1j * phs) self.X_hat = Xh
def __call__(self, theta, resp): """Return the 3PL IRF evaluated at `theta` given item response `resp`. Parameters ---------- theta : scalar or array-like of floats The latent traits. resp : scalar or array-like of 0's and 1's Whether the response was correct or not. Returns ------- p : scalar or array-like (following the shape of theta+resp) The conditional probability of `resp` given `theta`. Broadcasting is respected. E.g. if `theta.shape==(n, 1)` and `resp.shape==(1,m)`, then p will have `p.shape==(n,m)`. """ a, b, c = self._params make_tens = T.Tensor in map(type, [a, b, c, theta, resp]) if make_tens: theta = to_tens(theta) resp_temp = to_tens(resp) if make_tens: resp = to_tens(resp) if make_tens: p = c + (1 - c) * 1. / (1 + T.exp(-a * (theta - b))) else: p = c + (1 - c) * 1. / (1 + P.exp(-a * (theta - b))) return resp * p + (1 - resp) * (1 - p)
def splitfit(Ts, Rs, es, a, b, c, d, pguess, eguess, outfile=None): ## Split the data in two parts x1, x2, y1, y2, e1, e2 = [], [], [], [], [], [] for T, R, pe, ee in zip(Ts, Rs, es[0], es[1]): if a < T < b: x1.append(T) y1.append(abs(R)) e1.append(pe) elif c < T < d: x2.append(T) y2.append(abs(R)) e2.append(ee) ## Fit one part with the exponential fit1 = fit_power(x1, y1, e1, pguess) ## Fit one part with the polynomial fit2 = fit_exp(x2, y2, e2, eguess) res1 = fit1.results[0] res2 = fit2.results[0] fct1 = lambda x: res1[0] * (x - res1[1]) fct2 = lambda x: res2[0] * pylab.exp(res2[1]/x) Rs = pylab.array(Rs) Ges = [[[e/R**2] for R, e in zip(Rs, es[i])] for i in range(2)] pylab.clf() make_fig(Ts, Rs, Ges, a, b, c, d, fct1, fct2, outfile) return fit1, fit2
def gauss(d,**parms): # gaussian, f(r) = exp(-(ep r)^2) c = parms.get('centers') #op = parms.get('operator','interp') ep = parms.get('shapeparm',1) DM = dmatrix(d, centers = c) # eps_r = epsilon*r where epsilon may be an array or scalar eps_r = dot(ep*eye(DM.shape[0]),DM) return exp(-(eps_r)**2)
def cons_vac(T): """ consentration is given by n(T)/N (vacant parrticle-spaces divided by total particle-spaces) """ k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant deltaeps=1; #[eV] infitisemial energy for each "particle-jump" exponential = plt.exp( deltaeps/(T*k_b) ); #these values are way large. return 1.0/(exponential);
def heat_capacity(Num,Temp): """ heat capacity is given by the partiaally derived energy on temperature. giving us the function: C_v = (delta_eps)**2*N*exp(-delta_eps/T*k)/(k*T**2) """ k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant deltaeps=1; #[eV] infitisemial energy for each "particle-jump" exponential = plt.exp( -deltaeps/(Temp*k_b) ); #these values are way large. return Num*deltaeps**2*exponential/(k_b*Temp**2);
def gauss_pdf(n, mu=0.0, sigma=1.0): """ :: Generate a gaussian kernel n - number of points to generate mu - mean sigma - standard deviation """ var = sigma**2 return 1.0 / pylab.sqrt(2 * pylab.pi * var) * pylab.exp( -(pylab.r_[0:n] - mu)**2 / (2.0 * var))
def _istftm(self, X_hat=None, Phi_hat=None, pvoc=False, usewin=True, resamp=None): """ :: Inverse short-time Fourier transform magnitude. Make a signal from a |STFT| transform. Uses phases from self.STFT if Phi_hat is None. Inputs: X_hat - N/2+1 magnitude STFT [None=abs(self.STFT)] Phi_hat - N/2+1 phase STFT [None=exp(1j*angle(self.STFT))] pvoc - whether to use phase vocoder [False] usewin - whether to use overlap-add [False] Returns: x_hat - estimated signal """ if not self._have_stft: return None X_hat = self.X if X_hat is None else P.np.abs(X_hat) if pvoc: self._pvoc(X_hat, Phi_hat, pvoc) else: Phi_hat = P.angle(self.STFT) if Phi_hat is None else Phi_hat self.X_hat = X_hat * P.exp(1j * Phi_hat) if usewin: if self.win is None: self.win = P.ones( self.wfft) if self.window == 'rect' else P.np.sqrt( P.hanning(self.wfft)) if len(self.win) != self.nfft: self.win = P.r_[self.win, P.np.zeros(self.nfft - self.wfft)] if len(self.win) != self.nfft: error.BregmanError( "features_base.Features._istftm(): assertion failed len(self.win)==self.nfft" ) else: self.win = P.ones(self.nfft) if resamp: self.win = sig.resample(self.win, int(P.np.round(self.nfft * resamp))) fp = self._check_feature_params() self.x_hat = self._overlap_add(P.real(P.irfft(self.X_hat.T)), usewin=usewin, resamp=resamp) if self.verbosity: print("Extracted iSTFTM->self.x_hat") return self.x_hat
def plotSigmoid(): t = plab.arange(-60.0, 60.3, 0.1) s = 1 / (1 + plab.exp(-t)) ax = plab.subplot(211) ax.plot(t, s) ax.axis([-5, 5, 0, 1]) plt.xlabel('x') plt.ylabel('Sigmoid(x)') ax = plab.subplot(212) ax.plot(t, s) ax.axis([-60, 60, 0, 1]) plt.xlabel('x') plt.ylabel('Sigmoid(x)') plab.show()
def clarinet_funct(attack, sustain, release, sampling_frecuenciy, A0, I0): ta = pyl.arange(0, attack - 1 / sampling_frecuenciy, 1 / sampling_frecuenciy) y1 = pyl.exp(ta / attack * 1.5) - 1 y1 = y1 / max(y1) y1 = np.append(y1, pyl.ones([1, round(sustain * sampling_frecuenciy)])) tr = pyl.arange(0, (release / 2 - 1 / sampling_frecuenciy), 1 / sampling_frecuenciy) y3 = pyl.exp((release / 2 - tr) / release * 3) - 1 y4 = pyl.ones(len(y3)) - y3[::-1] y3 = y3 / max(y3) / 2 y2 = np.append(y1, pyl.ones([1, round(release * sampling_frecuenciy)])) y1 = np.append(y1, y4) y1 = np.append(y1, y3) lenght = min(len(y1), len(y2)) y1 = y1[:lenght] y2 = y2[:lenght] y2 = -I0 * y2 + 4 y1 = A0 * y1 return [y1, y2] # [A(t),I(t)]
def to_dissonance(self, tuning, f0=440., num_harmonics=6): """ :: Convert scale to dissonance values for num_harmonics harmonics. Assume an exponentially decaying harmonic series. Returns dissonance scores for each interval in given tuning system. """ harm = pylab.arange(num_harmonics) + 1 h0 = [f0 * k for k in harm] a = [pylab.exp(-0.5 * k) for k in harm] diss = [ dissonance_fun(h0 + [p * k for k in harm]) for p in self.to_scale_freqs(tuning, f0) ] return diss
def variable_phase_vocoder(D, times_steps, hop_length=None): n_fft = 2 * (D.shape[0] - 1) if hop_length is None: hop_length = int(n_fft // 4) # time_steps = P.arange(0, D.shape[1], rate, dtype=P.double) # time_steps = P.concatenate([ # P.arange(0, D.shape[1]/2, .5, dtype=P.double), # P.arange(D.shape[1]/2, D.shape[1], 2, dtype=P.double) # ]) # Create an empty output array d_stretch = P.zeros((D.shape[0], len(time_steps)), D.dtype, order='F') # Expected phase advance in each bin phi_advance = P.linspace(0, P.pi * hop_length, D.shape[0]) # Phase accumulator; initialize to the first sample phase_acc = P.angle(D[:, 0]) # Pad 0 columns to simplify boundary logic D = P.pad(D, [(0, 0), (0, 2)], mode='constant') for (t, step) in enumerate(time_steps): columns = D[:, int(step):int(step + 2)] # Weighting for linear magnitude interpolation alpha = P.mod(step, 1.0) mag = ((1.0 - alpha) * abs(columns[:, 0]) + alpha * abs(columns[:, 1])) # Store to output array d_stretch[:, t] = mag * P.exp(1.j * phase_acc) # Compute phase advance dphase = (P.angle(columns[:, 1]) - P.angle(columns[:, 0]) - phi_advance) # Wrap to -pi:pi range dphase = dphase - 2.0 * P.pi * P.around(dphase / (2.0 * P.pi)) # Accumulate phase phase_acc += phi_advance + dphase return d_stretch
def _make_cqt(self): """ :: Build a constant-Q transform (CQT) from lists of linear center frequencies, logarithmic center frequencies, and constant-Q bandwidths. """ fftfrqs = self._fftfrqs logfrqs = self._logfrqs logfbws = self._logfbws fp = self.feature_params ovfctr = 0.5475 # Norm constant so CQT'*CQT close to 1.0 tmp2 = 1.0 / (ovfctr * logfbws) tmp = (logfrqs.reshape(1, -1) - fftfrqs.reshape(-1, 1)) * tmp2 self.Q = P.exp(-0.5 * tmp * tmp) self.Q *= 1.0 / (2.0 * P.sqrt((self.Q * self.Q).sum(0))) self.Q = self.Q.T
def harmonics(afun=lambda x: pylab.exp(-0.5 * x), pfun=lambda x: pylab.rand() * 2 * pylab.pi, **params): """ :: Generate a harmonic series using a harmonic weighting function afun - lambda function of one parameter (harmonic index) returning a weight pfun - lambda function of one parameter (harmonic index) returning radian phase offset **params - signal_params dict, see default_signal_params() """ params = _check_signal_params(**params) f0 = params['f0'] x = pylab.zeros(params['num_points']) for i in pylab.arange(1, params['num_harmonics'] + 1): params['f0'] = i * f0 params['phase_offset'] = pfun(i) x += afun(i) * sinusoid(**params) x = balance_signal(x, 'maxabs') return x
def f(x, a, b, c): return a * P.exp(-(x - b)**2.0 / (2 * c**2))
import matplotlib.pylab as plt import sys, os version = sys.argv[0][5] try: nj = int(sys.argv[1]) except: nj = 100 T_theta = plt.array([1e-3, 1, 1e3]) K = lambda j_, u: (2 * j_ + 1.0) * plt.exp(-j_ * (j_ + 1.0) / u) plt.figure("exercise b") plt.hold(True) for t_ in T_theta: J = plt.array(range(nj + 1)) plt.plot(J, K(J, u=t_), label="T/qr=%0.0e" % t_) plt.legend(numpoints=1, loc=1) plt.xlabel("j") plt.ylabel("Z_R") plt.title("Partition function") plt.savefig("exb_v%s_nj%s.png" % (version, nj)) plt.show()
om_area = math.pi * domRadius**2. pm_area_factor = pmt_area / om_area #Evaluate the functions x = [float(i) / 10. for i in range(2800, 6201)] qe = [quantum_efficiency.GetValue(i * I3Units.nanometer) for i in x] glass_abs = [ glass_absorption_length.GetValue(i * I3Units.nanometer) for i in x ] gel_abs = [gel_absorption_length.GetValue(i * I3Units.nanometer) for i in x] om_acc = [om_acceptance.GetValue(i * I3Units.nanometer) for i in x] pm_coll = [pm_collection_efficiency for i in x] area_factor = [pm_area_factor for i in x] #Calculate some more glass_trans = [plt.exp(-(glass_width / i)) if i != 0 else 0 for i in glass_abs] gel_trans = [plt.exp(-(gel_width / i)) if i != 0 else 0 for i in gel_abs] #Make the main plot fig = plt.figure(1, figsize=[8, 10]) fig.canvas.set_window_title("Acceptance properties of an ANTARES OM") plt.subplot(311) plt.xlabel("Wavelength $\\lambda$ [nm]") plt.ylabel("Absorption length [m]") #plt.title("Absorption lengths in an ANTARES OM as function of wavelength") plt.plot(x, glass_abs, label=str(glass_width * 100.) + ' cm Glass') plt.plot(x, gel_abs, label=str(gel_width * 100.) + ' cm Gel') plt.legend(loc='upper left') plt.grid()
def contrast(image, level=1): image = image / 255 image = image - 0.5 image = 255 / (1 + pylb.exp(-5 * level * image)) image = image.astype("uint8") return image
pmt_area = math.pi * (pmt_diameter/2.)**2 domRadius = 0.2159*I3Units.m om_area = math.pi*domRadius**2. pm_area_factor = pmt_area/om_area #Evaluate the functions x = [float(i)/10. for i in range(2800,6201)] qe = [quantum_efficiency.GetValue(i*I3Units.nanometer) for i in x] glass_abs = [glass_absorption_length.GetValue(i*I3Units.nanometer) for i in x] gel_abs = [gel_absorption_length.GetValue(i*I3Units.nanometer) for i in x] om_acc = [om_acceptance.GetValue(i*I3Units.nanometer) for i in x] pm_coll = [pm_collection_efficiency for i in x] area_factor = [pm_area_factor for i in x] #Calculate some more glass_trans = [plt.exp(-(glass_width / i)) if i != 0 else 0 for i in glass_abs] gel_trans = [plt.exp(-(gel_width / i)) if i != 0 else 0 for i in gel_abs] #Make the main plot fig = plt.figure(1, figsize=[8,10]) fig.canvas.set_window_title("Acceptance properties of an ANTARES OM") plt.subplot(311) plt.xlabel("Wavelength $\\lambda$ [nm]") plt.ylabel("Absorption length [m]") #plt.title("Absorption lengths in an ANTARES OM as function of wavelength") plt.plot(x, glass_abs, label=str(glass_width*100.)+' cm Glass') plt.plot(x, gel_abs, label=str(gel_width*100.)+' cm Gel') plt.legend(loc='upper left') plt.grid()
def logistic(t): return (1.0 / (1.0 + pl.exp(-t)))
def logistic(t): return(1.0/(1.0 + pl.exp(-t)))