Example #1
0
def plot_axes(fig):
    # create some data to use for the plot
    dt = 0.001
    t = arange(0.0, 10.0, dt)
    r = exp(-t[:1000]/0.05)               # impulse response
    x = randn(len(t))
    s = convolve(x,r,mode=2)[:len(x)]*dt  # colored noise

    # the main axes is subplot(111) by default
    axes = fig.gca()
    axes.plot(t, s)
    axes.set_xlim((0, 1))
    axes.set_ylim((1.1*min(s), 2*max(s)))
    axes.set_xlabel('time (s)')
    axes.set_ylabel('current (nA)')
    axes.set_title('Gaussian colored noise')

    # this is an inset axes over the main axes
    a = fig.add_axes([.65, .6, .2, .2], axisbg='y')
    n, bins, patches = a.hist(s, 400, normed=1)
    a.set_title('Probability')
    a.set_xticks([])
    a.set_yticks([])

    # this is another inset axes over the main axes
    a = fig.add_axes([.2, .6, .2, .2], axisbg='y')
    a.plot(t[:len(r)], r)
    a.set_title('Impulse response')
    a.set_xlim((0, 0.2))
    a.set_xticks([])
    a.set_yticks([])
Example #2
0
    def findNoisyArea(self):
        """
        Argument :
            - None
        Return :
            - None

        Use to detect the noisy area (the area without atoms) by an edge
        detection technique.
        """
        OD = self.computeFirstOD()
        yProfile = py.sum(OD, axis=1)
        derivative = py.gradient(yProfile)
        N = 10
        # because the derivative is usually very noisy, a sliding average is
        # performed in order to smooth the signal. This is done by a
        # convolution with a gate function of size "N".
        res = py.convolve(derivative, py.ones((N, )) / N, mode='valid')
        mean = res.mean()
        # index of the maximum value of the signal.
        i = res.argmax()
        while res[i] >= mean:
            # once "i" is greater or equal to the mean of the derivative,
            # we have found the upper bound of the noisy area.
            i -= 1
        # index of the minimum value of the signal.
        upBound = i - 50
        i = res.argmin()
        while res[i] < mean:
            # once "i" is smaller or equal to the mean of the derivative,
            # we have found the lower bound of the noisy area.
            i += 1
        downBound = i + 50
        self.setNoisyArea((upBound, downBound))
        return OD
Example #3
0
def slidingAverage(x, N):
    tmp = convolve(
        x,
        ones((N, )) / N,
        mode='valid',
    )
    return r_[tmp[0] * ones(N / 2), tmp, tmp[-1] * ones(N / 2 - 1 + N % 2)]
def fairness(principal_list,xlabel,ylabel,output_filename):
    '''
    @param {list} principal_list --- Each element is either a 0 or a
    1.  0 if transaction by principal a, 1 if by principal b.
    '''
    
    # note: I have little idea how the following code works.  It was
    # mostly copied from the previous paper's scripts.  Check there if
    # confused.
    float_princ_list = map(
        lambda princ_num : float(princ_num), principal_list)
    window = pylab.ones(10)/10.0
    rate = pylab.convolve(float_princ_list, window, 'same')


    _fairness_plot_set_defaults()
    plt.plot(rate, color='red')
    yticks = [-.1, 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.1]
    ylabels = ['', '0%', '20%', '40%', '60%', '80%', '100%', '']

    plt.yticks(yticks, ylabels, fontsize=12)
    # plt.xticks(xtiks, xlabels, fontsize=7)
    plt.xlabel(xlabel, fontsize=16, verticalalignment='top')
    plt.ylabel(ylabel, fontsize=18)
    
    plt.savefig(output_filename)
Example #5
0
def psp_parameter_estimate_fixmem(time, value):
    smoothing_kernel = 10
    smoothed_value = p.convolve(
        value,
        p.ones(smoothing_kernel) / float(smoothing_kernel),
        "same")

    mean_est_part = int(len(value) * .1)
    mean_estimate = p.mean(smoothed_value[-mean_est_part:])
    noise_estimate = p.std(value[-mean_est_part:])

    integral = p.sum(smoothed_value - mean_estimate) * (time[1] - time[0])

    f = 1.

    A_estimate = (max(smoothed_value) - mean_estimate) / (1. / 4.)

    min_A = noise_estimate

    if A_estimate < min_A:
        A_estimate = min_A

    t1_est = integral / A_estimate * f
    t2_est = 2 * t1_est

    tmax_est = time[p.argmax(smoothed_value)] + p.log(t2_est / t1_est) * (t1_est * t2_est) / (t1_est - t2_est)

    return p.array([
        tmax_est,
        A_estimate,
        t1_est,
        mean_estimate])
Example #6
0
def _createRmat( h_list, rmat, nstim, ntime ):
    '''
    This function ...
    
    Aguments
    --------
    
    Keyword arguments
    -----------------
    '''
    nsplit = len(h_list)    
    npop, _ = rmat.shape

    Rmat = pl.zeros((nsplit*npop, nstim*ntime))
    
    for istim in xrange(nstim):
        for isplit in xrange(nsplit):
            for ipop in xrange(npop):
                rvec = rmat[ipop, istim*ntime:(istim+1)*ntime]
                h = h_list[isplit]
                tmp_vec= pl.convolve(rvec, h)
                tmp_vec=tmp_vec[:ntime]
                Rmat[ipop+isplit*npop,\
                         istim*ntime:(istim+1)*ntime]=tmp_vec

    return Rmat
Example #7
0
def alpha_psp_parameter_estimate(time, value, smoothing_samples=10):
    t1_est_min = time[1] - time[0]

    mean_est_part = len(value) * .1
    mean_estimate = p.mean(value[-mean_est_part:])
    noise_estimate = p.std(value[-mean_est_part:])

    smoothed_value = p.convolve(
        value - mean_estimate,
        p.ones(smoothing_samples) / float(smoothing_samples),
        "same") + mean_estimate

    integral = p.sum(smoothed_value - mean_estimate) * (time[1] - time[0])

    f = 1.

    height_estimate = (max(smoothed_value) - mean_estimate)

    min_height = noise_estimate

    if height_estimate < min_height:
        height_estimate = min_height

    t1_est = integral / height_estimate * f
    if t1_est < t1_est_min:
        t1_est = t1_est_min
    t2_est = 2 * t1_est

    tmax_est = time[p.argmax(smoothed_value)]
    tstart_est = tmax_est + p.log(t2_est / t1_est) \
        * (t1_est * t2_est) / (t1_est - t2_est)

    return p.array(
        [height_estimate, t1_est, t2_est, tstart_est, mean_estimate])
Example #8
0
def broadgauss(x, y, sigma):
    '''Gaussian function for broadening
    '''

    bla = True
    plot = False
    c = 299792458.

    if bla:
        print " sigma = ", round(sigma, 4), " km/s"

    sigma = sigma * 1.0e3 / c * pl.mean(x)  # sigma in Å

    if bla:
        print " sigma = ", round(sigma, 3), "  Å "

    xk = x - pl.mean(x)

    g = make_gauss(1, 0, sigma)
    yk = [g(i) for i in xk]

    if bla:
        print " Integral of the gaussian function: ", pl.trapz(
            yk, xk).__format__('5.3')

    if plot:
        pl.figure(2)
        pl.plot(xk, yk, '+-')
        pl.show()
    #if bla: print" size y:", y.size
    y = pl.convolve(y, yk, mode='same')
    #if bla: print" size y:", y.size

    return y / max(y)
Example #9
0
def lowpassFIR(data, freq, samp_rate=200, winlen=2048):
    """
    FIR-Lowpass Filter
 
    Filter data by passing data only below a certain frequency.
 
    :param data: Data to filter, type numpy.ndarray.
    :param freq: Data below this frequency pass.
    :param samprate: Sampling rate in Hz; Default 200.
    :param winlen: Window length for filter in samples, must be power of 2; 
        Default 2048
    :return: Filtered data.
    """
    # There is not currently an FIR-filter design program in SciPy.  One
    # should be constructed as it is not hard to implement (of course making
    # it generic with all the options you might want would take some time).
    #
    # What kind of window are you currently using?
    #
    # For your purposes this is what I would do:
    # SRC: Travis Oliphant
    # http://aspn.activestate.com/ASPN/Mail/Message/scipy-user/2009409]
    #
    #winlen = 2**11 #2**10 = 1024; 2**11 = 2048; 2**12 = 4096
    #give frequency bins in Hz and sample spacing
    w = fft.fftfreq(winlen, 1 / float(samp_rate))
    #cutoff is low-pass filter
    myfilter = where((abs(w) < freq), 1., 0.)
    #ideal filter
    h = fft.ifft(myfilter)
    beta = 11.7
    #beta implies Kaiser
    myh = fft.fftshift(h) * get_window(beta, winlen)
    return convolve(abs(myh), data)[winlen / 2:-winlen / 2]
Example #10
0
def plot_axes(fig):
    # create some data to use for the plot
    dt = 0.001
    t = arange(0.0, 10.0, dt)
    r = exp(-t[:1000]/0.05)               # impulse response
    x = randn(len(t))
    s = convolve(x,r,mode=2)[:len(x)]*dt  # colored noise

    # the main axes is subplot(111) by default
    axes = fig.gca()
    axes.plot(t, s)
    axes.set_xlim((0, 1))
    axes.set_ylim((1.1*min(s), 2*max(s)))
    axes.set_xlabel('time (s)')
    axes.set_ylabel('current (nA)')
    axes.set_title('Gaussian colored noise')

    # this is an inset axes over the main axes
    a = fig.add_axes([.65, .6, .2, .2], axisbg='y')
    n, bins, patches = a.hist(s, 400, normed=1)
    a.set_title('Probability')
    a.set_xticks([])
    a.set_yticks([])

    # this is another inset axes over the main axes
    a = fig.add_axes([.2, .6, .2, .2], axisbg='y')
    a.plot(t[:len(r)], r)
    a.set_title('Impulse response')
    a.set_xlim((0, 0.2))
    a.set_xticks([])
    a.set_yticks([])
Example #11
0
    def _shapeStim(self,
                   isi=1,
                   variation=0,
                   width=0.05,
                   weight=10,
                   start=0,
                   finish=1,
                   stimshape='gaussian'):
        from pylab import r_, convolve, shape, exp, zeros, hstack, array, rand

        # Create event times
        timeres = 0.001  # Time resolution = 1 ms = 500 Hz (DJK to CK: 500...?)
        pulselength = 10  # Length of pulse in units of width
        currenttime = 0
        timewindow = finish - start
        allpts = int(timewindow / timeres)
        output = []
        while currenttime < timewindow:
            # Note: The timeres/2 subtraction acts as an eps to avoid later int rounding errors.
            if currenttime >= 0 and currenttime < timewindow - timeres / 2:
                output.append(currenttime)
            currenttime = currenttime + isi + variation * (rand() - 0.5)

        # Create single pulse
        npts = pulselength * width / timeres
        x = (r_[0:npts] - npts / 2 + 1) * timeres
        if stimshape == 'gaussian':
            pulse = exp(-2 * (2 * x / width - 1)**
                        2)  # Offset by 2 standard deviations from start
            pulse = pulse / max(pulse)
        elif stimshape == 'square':
            pulse = zeros(shape(x))
            pulse[int(npts / 2):int(npts / 2) +
                  int(width / timeres)] = 1  # Start exactly on time
        else:
            raise Exception('Stimulus shape "%s" not recognized' % stimshape)

        # Create full stimulus
        events = zeros((allpts))
        events[array(array(output) / timeres, dtype=int)] = 1
        fulloutput = convolve(
            events, pulse, mode='full'
        ) * weight  # Calculate the convolved input signal, scaled by rate
        fulloutput = fulloutput[
            npts / 2 - 1:-npts /
            2]  # Slices out where the convolved pulse train extends before and after sequence of allpts.
        fulltime = (r_[0:allpts] * timeres +
                    start) * 1e3  # Create time vector and convert to ms

        fulltime = hstack(
            (0, fulltime, fulltime[-1] + timeres *
             1e3))  # Create "bookends" so always starts and finishes at zero
        fulloutput = hstack(
            (0, fulloutput,
             0))  # Set weight to zero at either end of the stimulus period
        events = hstack((0, events, 0))  # Ditto
        stimvecs = deepcopy([fulltime, fulloutput,
                             events])  # Combine vectors into a matrix

        return stimvecs
Example #12
0
def broadgauss(x, y, sigma):
    '''Gaussian function for broadening
    '''

    bla = True
    plot = False
    c = 299792458.

    if bla:
        print " sigma = ", round(sigma, 4), " km/s"

    sigma = sigma * 1.0e3/c * pl.mean(x)   # sigma in Å

    if bla:
        print " sigma = ", round(sigma, 3), "  Å "

    xk = x - pl.mean(x)

    g = make_gauss(1, 0, sigma)
    yk = [g(i) for i in xk]

    if bla:
        print " Integral of the gaussian function: ", pl.trapz(yk, xk).__format__('5.3')

    if plot:
        pl.figure(2)
        pl.plot(xk, yk, '+-')
        pl.show()
    #if bla: print" size y:", y.size
    y = pl.convolve(y, yk, mode='same')
    #if bla: print" size y:", y.size

    return y/max(y)
Example #13
0
    def SVMAF(self,freq,n,l):
        #Apply the SVMAF filter to the material parameters
        runningMean=lambda x,N: py.hstack((x[:N-1],py.convolve(x,py.ones((N,))/N,mode='same')[N-1:-N+1],x[(-N+1):]))
        #calculate the moving average of 3 points
        n_smoothed=runningMean(n,3)
        #evaluate H_smoothed from n_smoothed
        H_smoothed=self.H_theory(freq,[n_smoothed.real,n_smoothed.imag],l)
        
        H_r=H_smoothed.real
        H_i=H_smoothed.imag
        f=1
        #the uncertainty margins
        lb_r=self.H.getFReal()-self.H.getFRealUnc()*f
        lb_i=self.H.getFImag()-self.H.getFImagUnc()*f
        ub_r=self.H.getFReal()+self.H.getFRealUnc()*f
        ub_i=self.H.getFImag()+self.H.getFImagUnc()*f
        
        #ix=all indices for which after smoothening n H is still inbetwen the bounds        
        ix=py.all([H_r>=lb_r,H_r<ub_r,H_i>=lb_i,H_i<ub_i],axis=0)
#        #dont have a goood idea at the moment, so manually:
        for i in range(len(n_smoothed)):
            if ix[i]==0:
                n_smoothed[i]=n[i]
        print("SVMAF changed the refractive index at " + str(sum(ix)) + " frequencies")
        return n_smoothed      
Example #14
0
 def getmovingAveragedData(self,window_size_GHz=-1):
     #so far unelegant way of convolving the columns one by one
     #even not nice, improvement possible?
     if window_size_GHz<0.5e9:
         window_size=int(self.getEtalonSpacing()/self.getfbins())
     else:
         window_size=int(window_size_GHz/self.getfbins())
           
     window_size+=window_size%2+1
     window=py.ones(int(window_size))/float(window_size)
     
     dataabs=py.convolve(self.getFAbs(), window, 'valid')
     dataph=py.convolve(self.getFPh(), window, 'valid')
     one=py.ones((window_size-1)/2,)
     dataabs=py.concatenate((dataabs[0]*one,dataabs,dataabs[-1]*one))
     dataph=py.concatenate((dataph[0]*one,dataph,dataph[-1]*one))
     return py.column_stack((self.fdData[:,:3],dataabs,dataph,self.fdData[:,5:]))
def smooth(x,window_len=11,window='hanning'):
    """smooth the data using a window with requested size.
    
    This method is based on the convolution of a scaled window with the signal.
    The signal is prepared by introducing reflected copies of the signal 
    (with the window size) in both ends so that transient parts are minimized
    in the begining and end part of the output signal.

    Copied and modified from http://scipy-cookbook.readthedocs.io/items/SignalSmooth.html  (16/10/2017 - RProux)
    
    input:
        x: the input signal 
        window_len: the dimension of the smoothing window; should be an odd integer
        window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
            flat window will produce a moving average smoothing.

    output:
        the smoothed signal
        
    example:

    t=linspace(-2,2,0.1)
    x=sin(t)+randn(len(t))*0.1
    y=smooth(x)
    
    see also: 
    
    numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
    scipy.signal.lfilter
 
    TODO: the window parameter could be the window itself if an array instead of a string
    NOTE: the window_len parameter should always be odd for reliable output (will shift slightly the data if even)
    """

    if x.ndim != 1:
        raise ValueError("smooth only accepts 1 dimension arrays.")

    if x.size < window_len:
        raise ValueError("Input vector needs to be bigger than window size.")

    if window_len < 3:
        return x

    if window not in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError("Window is one of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")


    s = pl.r_[x[window_len-1:0:-1],x,x[-2:-window_len-1:-1]]
    print(s)
    print(len(s))
    if window == 'flat': #moving average
        w = pl.ones(window_len, 'd')
    else:
        w = eval('pl.{}(window_len)'.format(window))

    y = pl.convolve(w / w.sum(), s, mode='valid')

    return y[int(pl.floor(window_len/2)) : -int(pl.ceil(window_len/2) - 1)]
Example #16
0
def smooth(x, beta):
    """ kaiser window smoothing """
    window_len = 11
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = pylab.r_[x[window_len - 1:0:-1], x, x[-1:-window_len:-1]]
    w = pylab.kaiser(window_len, beta)
    y = pylab.convolve(w / w.sum(), s, mode='valid')
    return y[5:len(y) - 5]
Example #17
0
def smooth(x,beta):
    """ kaiser window smoothing """
    window_len=11
    # extending the data at beginning and at the end
    # to apply the window at the borders
    s = pylab.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
    w = pylab.kaiser(window_len,beta)
    y = pylab.convolve(w/w.sum(),s,mode='valid')
    return y[5:len(y)-5]
def zMeasures(current, v, delay, sampr, f1, bwinsz=1):
    ## zero padding
    current = current[int(delay * sampr - 0.5 * sampr +
                          1):-int(delay * sampr - 0.5 * sampr)]
    current = np.hstack((np.repeat(current[0], int(delay * sampr)), current,
                         np.repeat(current[-1], int(delay * sampr))))
    current = current - np.mean(current)
    v = v[int(delay * sampr - 0.5 * sampr) +
          1:-int(delay * sampr - 0.5 * sampr)]
    v = np.hstack((np.repeat(v[0], int(delay * sampr)), v,
                   np.repeat(v[-1], int(delay * sampr))))
    v = v - np.mean(v)

    ## input and transfer impedance
    f_current = (fft(current) / len(current))[0:int(len(current) / 2)]
    f_cis = (fft(v) / len(v))[0:int(len(v) / 2)]
    z = f_cis / f_current

    ## impedance measures
    Freq = np.linspace(0.0, sampr / 2.0, len(z))
    zAmp = abs(z)
    zPhase = np.arctan2(np.imag(z), np.real(z))
    zRes = np.real(z)
    zReact = np.imag(z)

    ## smoothing
    fblur = np.array([1.0 / bwinsz for i in range(bwinsz)])
    zAmp = convolve(zAmp, fblur, 'same')
    zPhase = convolve(zPhase, fblur, 'same')

    ## trim
    mask = (Freq >= 0.5) & (Freq <= f1)
    Freq, zAmp, zPhase, zRes, zReact = Freq[mask], zAmp[mask], zPhase[
        mask], zRes[mask], zReact[mask]

    ## resonance
    zResAmp = np.max(zAmp)
    zResFreq = Freq[np.argmax(zAmp)]
    Qfactor = zResAmp / zAmp[0]
    fVar = np.std(zAmp) / np.mean(zAmp)

    return Freq, zAmp, zPhase, zRes, zReact, zResAmp, zResFreq, Qfactor, fVar
Example #19
0
def makestim(isi=1,
             variation=0,
             width=0.05,
             weight=10,
             start=0,
             finish=1,
             stimshape='gaussian'):
    from pylab import r_, convolve, shape

    # Create event times
    timeres = 0.005  # Time resolution = 5 ms = 200 Hz
    pulselength = 10  # Length of pulse in units of width
    currenttime = 0
    timewindow = finish - start
    allpts = int(timewindow / timeres)
    output = []
    while currenttime < timewindow:
        if currenttime >= 0 and currenttime < timewindow:
            output.append(currenttime)
        currenttime = currenttime + isi + variation * (rand() - 0.5)

    # Create single pulse
    npts = min(pulselength * width / timeres,
               allpts)  # Calculate the number of points to use
    x = (r_[0:npts] - npts / 2 + 1) * timeres
    if stimshape == 'gaussian':
        pulse = exp(-(x / width * 2 - 2)**
                    2)  # Offset by 2 standard deviations from start
        pulse = pulse / max(pulse)
    elif stimshape == 'square':
        pulse = zeros(shape(x))
        pulse[int(npts / 2):int(npts / 2) +
              int(width / timeres)] = 1  # Start exactly on time
    else:
        raise Exception('Stimulus shape "%s" not recognized' % stimshape)

# Create full stimulus
    events = zeros((allpts))
    events[array(array(output) / timeres, dtype=int)] = 1
    fulloutput = convolve(
        events, pulse, mode='same'
    ) * weight  # Calculate the convolved input signal, scaled by rate
    fulltime = (r_[0:allpts] * timeres +
                start) * 1e3  # Create time vector and convert to ms
    fulltime = hstack(
        (0, fulltime, fulltime[-1] + timeres *
         1e3))  # Create "bookends" so always starts and finishes at zero
    fulloutput = hstack(
        (0, fulloutput,
         0))  # Set weight to zero at either end of the stimulus period
    events = hstack((0, events, 0))  # Ditto
    stimvecs = [fulltime, fulloutput, events]  # Combine vectors into a matrix

    return stimvecs
Example #20
0
File: misc.py Project: MMaus/mutils
 def mov_avg(data, tailLength):
     """
     returns the moving average for a 1D array data
     """
     data1 = concatenate((data[tailLength:0:-1],data,data[-tailLength:]))
     #print "mov avg idat shape:", data1.shape, "tailLength:", tailLength
     avgFilter = array([1./(2.*tailLength+1.),]*(2*tailLength + 1))
     #print "avgFilter:", avgFilter.shape
     res = convolve(data1,avgFilter)[2*tailLength:-2*tailLength]
     #print "mov avg shape:", res.shape
     return res
Example #21
0
 def getDR(self):
     #this function should return the dynamic range
     #this should be the noiselevel of the fft
     noiselevel=py.sqrt(py.mean(abs(py.fft(self._tdData.getAllPrecNoise()[0]))**2))
     #apply a moving average filter on log
     window_size=5
     window=py.ones(int(window_size))/float(window_size)
     hlog=py.convolve(20*py.log10(self.getFAbs()), window, 'valid')
     one=py.ones((2,))
     hlog=py.concatenate((hlog[0]*one,hlog,hlog[-1]*one))
     return hlog-20*py.log10(noiselevel)         
Example #22
0
    def findAreaOfInterest(self):
        """
        Argument :
            - None
        Return :
            - None

        Use to detect the AOI by an edge detection technique.
        """
        OD = self.findNoisyArea()
        max = 0
        bestAngle = None
        for angle in range(-10, 10, 1):
            # the best angle is the one for wich the maximum peak is reached
            # on the yProfile (integral on the horizontal direction) ...
            image = rotate(OD, angle)
            yProfile = py.sum(image, axis=1)
            newMax = yProfile.max()
            if newMax > max:
                max = newMax
                bestAngle = angle
        # ... once found, the resulting OD image is kept and used to find the
        # the top and bottom bounds by edge detection.
        bestOD = rotate(OD, bestAngle)
        YProfile = py.sum(bestOD, axis=1)
        derivative = py.gradient(YProfile)
        N = 10
        # because the derivative is usually very noisy, a sliding average is
        # performed in order to smooth the signal. This is done by a
        # convolution with a gate function of size "N".
        res = py.convolve(derivative, py.ones((N, )) / N, mode='valid')
        mean = res.mean()
        # index of the maximum value of the signal.
        i = res.argmax()
        while res[i] > mean:
            # once "i" is greater or equal to the mean of the derivative,
            # we have found the upper bound of the AOI.
            i -= 1
        # for security we take an extra 50 pixels.
        y0 = int(i - 50)
        # index of the minimum value of the signal.
        i = res.argmin()
        while res[i] < mean:
            # once "i" is smaller or equal to the mean of the derivative,
            # we have found the lower bound of the AOI.
            i += 1
        # Again, for security, we take an extra 50 pixels.
        y1 = int(i + 50)
        # The horizontal bound are taken to be maximal, but for security, we
        # take an extra 50 pixels.
        x0 = 50
        x1 = py.shape(OD)[0] - 50
        self.setAreaOfInterest(area=(x0, x1, y0, y1), angle=bestAngle)
        return bestOD[y0:y1, x0:x1]
Example #23
0
File: misc.py Project: MMaus/mutils
 def mov_avg(data, tailLength):
     """
     returns the moving average for a 1D array data
     """
     data1 = concatenate((data[tailLength:0:-1], data, data[-tailLength:]))
     #print "mov avg idat shape:", data1.shape, "tailLength:", tailLength
     avgFilter = array([
         1. / (2. * tailLength + 1.),
     ] * (2 * tailLength + 1))
     #print "avgFilter:", avgFilter.shape
     res = convolve(data1, avgFilter)[2 * tailLength:-2 * tailLength]
     #print "mov avg shape:", res.shape
     return res
Example #24
0
def decoder(data,code,iflip):
    """convolves each data profile with the code sequence"""
    times=py.shape(data)[0]
    hts=py.shape(data)[1]
    codelength=py.shape(code)[0]
    code_rev=code[::-1] #decoding requires using the inverse of the code
    deflip=1
    #pdb.set_trace()
    for i in range (times):
        temp=py.convolve(data[i,:],code_rev)
        data[i,:]=deflip*temp[codelength-1:codelength+hts]
        deflip=deflip*iflip #call with iflip=-1 if tx has flip
        #pdb.set_trace()
    return data
Example #25
0
def decoder(data, code, iflip):
    """convolves each data profile with the code sequence"""
    times = py.shape(data)[0]
    hts = py.shape(data)[1]
    codelength = py.shape(code)[0]
    code_rev = code[::-1]  #decoding requires using the inverse of the code
    deflip = 1
    #pdb.set_trace()
    for i in range(times):
        temp = py.convolve(data[i, :], code_rev)
        data[i, :] = deflip * temp[codelength - 1:codelength + hts]
        deflip = deflip * iflip  #call with iflip=-1 if tx has flip
        #pdb.set_trace()
    return data
Example #26
0
def smooth(x,window_len=11,window='hanning'):
    if x.ndim != 1:
        raise ValueError, "smooth only accepts 1 dimension arrays."
    if x.size < window_len:
        raise ValueError, "Input vector needs to be bigger than window size."
    if window_len<3:
        return x
    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError, "Window is one of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
    s=p.r_[2*x[0]-x[window_len-1::-1],x,2*x[-1]-x[-1:-window_len:-1]]
    if window == 'flat': #moving average
        w=p.ones(window_len,'d')
    else:
        w=eval('p.'+window+'(window_len)')
    y=p.convolve(w/w.sum(),s,mode='same')
    return y[window_len:-window_len+1]
Example #27
0
def match(Signal=None, Window=None):
    """
		.

		Parameters
		__________
		Signal : ndarray
			Input signal data.
		Window : 

		Returns
		_______
		kwrvals : dict
			A keyworded return values dict is returned with the following keys: 
			Event : 
		

		See Also
		________
			pl.convolve

		Notes
		_____


		Example
		_______

		
	"""
    # Check
    if Signal is None:
        raise TypeError, "An input signal is needed."
    #
    lw = len(Window)
    lx = len(Signal)

    if lw > lx:
        raise AttributeError(
            "Window length must be less or equal to the length of the input signal."
        )

    kwrvals = {}
    #kwrvals['dt']=pl.array(map(lambda i: pl.sqrt(sum((Signal[i+lw]-Window)**2)), pl.arange(0, lx-lw))).argmin()
    kwrvals['dt'] = pl.convolve(Window, Signal).argmax()

    return kwrvals
Example #28
0
def decoder_ht(data, code, iflip=1., dropheights=False):
    """convolves each data profile with the code sequence"""
    times = data.shape[2]
    hts = data.shape[1]
    chs = data.shape[0]
    numcodes = code.shape[0]
    codelength = code.shape[1]
    code_rev = code[:, ::-1]  #decoding requires using the inverse of the code
    deflip = iflip
    for ch in range(chs):
        for i in range(times):
            if i % numcodes == 0:
                deflip = deflip * iflip  #call with iflip=-1 if tx has flip
            code_i = i % numcodes
            temp = py.convolve(data[ch, :, i], code_rev[code_i, :])
            data[ch, :, i] = deflip * temp[codelength - 1:codelength + hts]
    return data
Example #29
0
def decoder_ht(data,code, iflip = 1., dropheights = False):
    """convolves each data profile with the code sequence"""
    times = data.shape[2]
    hts = data.shape[1]
    chs = data.shape[0]
    numcodes = code.shape[0]
    codelength= code.shape[1]
    code_rev=code[:,::-1] #decoding requires using the inverse of the code
    deflip = iflip
    for ch in range(chs):
        for i in range (times):
            if i % numcodes == 0 :
                deflip=deflip*iflip #call with iflip=-1 if tx has flip
            code_i = i % numcodes
            temp=py.convolve(data[ch,:,i],code_rev[code_i,:])
            data[ch,:,i]=deflip*temp[codelength-1:codelength+hts]
    return data
Example #30
0
def smoothed_histogram_window(ax, pdf, bins):

    wsize = 20
    bins = 0.5 * (bins[:-1] + bins[1:])
    
    # for wsize in range(5, 30, 5):
    # extending the data at beginning and at the end
    # to apply the window at the borders
    ps = plt.r_[pdf[wsize-1:0:-1], pdf, pdf[-1:-wsize:-1]]
    w = plt.hanning(wsize)
    pc = plt.convolve(w/w.sum(), ps, mode='valid')
    pc = pc[wsize/2:len(ps)-wsize/2]
    pc = pc[0:len(bins)]
    # plt.plot(bins, pc)
    # plt.fill_between(bins, 0, pc, alpha=0.1)

    return pc, bins
Example #31
0
def make_graphs(stats, fileout):
	Gaussian = scipy.signal.gaussian(WindowSize, 2)
	Gaussian = Gaussian / sum(Gaussian)
	fontP = FontProperties()
	fontP.set_size('small')

	perRoundStats = [['Turns per round', 'Time per round'], ['Created nodes per round', 'Cumulative nodes per round'], ['Pulses per round']]
	for i, subset in enumerate(perRoundStats):
		plt.subplot(len(perRoundStats), 1, i + 1)
		for pr in subset:
			plot = stats[pr]
			if i == 0 and smoothed: plot = pylab.convolve(plot, Gaussian, 'same')
			plt.plot(plot, label=pr) # drawstyle = 'steps'
		plt.xlabel('Round')
		plt.legend(prop = fontP)

	if fileout == 'show': plt.show()
	else: plt.savefig(fileout)
def create_band(band, res, plt=False, high=0, conv=False):
  '''
  print, "create_band, band, res, /bw, /plt, high=high, /conv"
  print, "This program will create a top hat band convolved with a gaussain of sigma = res with freq data spaced from 0 to 1000 (default) GHz"
  print, "band = bandpass region in GHz"
  print, "res = freq. spacing in GHz"
  print, "/plt plot bandpass"
  print, "high=high upper GHz region"
  print, "r = create_band([140, 160], 2.0, /bw, high=500.0)"
  return, 0
  '''

  npts = pl.ceil(4000.0)
  if high : npts = pl.ceil(high*1.0/.25)
  freq = pl.arange(npts)*.25 
  response = pl.zeros(len(freq))

  inb = pl.where((freq < band[1]) & (freq > band[0]))[0]
  if band[0] == band[1] : inb = pl.where_closest(freq, band(0))[0]
  if inb[0] == -1:
    print "Band not between 0-1000 GHZ"
    return 0

  response[inb] = 1

  #let's convolve the band with our resolution. 
  if conv:
    xx = .25*pl.arange(6*res/.25+1)-3*res
    con =pl.exp(-xx**2/(2*res**2))/pl.sqrt(2*pl.pi)/res
    normalization=1./sum(abs(con))
    response = pl.convolve(response, con,'same')*normalization
  

  if plt:
    pl.figure()
    pl.plot(freq, response,'D')
    pl.xlabel('Freq(GHz)')
    pl.ylabel('Reponse')
    pl.xlim(band[0] - 3*res, band[1] + 3*res)


  result = {'Freq': freq, 'resp': response}

  return result
Example #33
0
def Errorline_faded ( x, y, e, al, **kwargs ):
    """An Errorline that fades

    Similar to an Error line but fades out according to al.
    IMPORTANT: This line is going to be made up of lots of small lines and
    small rectangular patches.

    :Parameters:
        *x*
            x values of the line
        *y*
            y values of the line. If y.shape == 2, then se is called for
            every sample of y to derive an upper and lower limit
        *e*
            error (in y direction) This could take either a scalar giving the
            (constant) error, an array of scalar errors, or an array of
            observations. In the latter case, se is applied to every sample
            of e
        *al*
            alpha values for the different line segments
        *color*,*edgecolor*,*facecolor*,*ax*
            see Errorline()
    """
    c = dvis.color.colorsequence ( kwargs.setdefault ( 'color', [0,0,0]))[0]
    kwargs.setdefault ( 'edgecolor', dvis.color.cmix ( c, 'w', 3 ) )
    kwargs.setdefault ( 'facecolor', dvis.color.cmix ( c, 'w', 1.5 ) )
    ax = kwargs.setdefault ( 'ax', pl.gca() )

    fade = pl.convolve ( [.5,.5], al, 'valid' )
    yup = y+e
    ydown = y-e
    n = len(fade)
    l,f = [],[]
    for i in xrange ( n ):
        f += ax.fill (
                [x[i],x[i+1],x[i+1],x[i]],
                [yup[i],yup[i+1],ydown[i+1],ydown[i]],
                ec='none', fc=kwargs['facecolor'], alpha=fade[i] )
        l += ax.plot ( x[i:i+2], y[i:i+2], color=c, alpha=fade[i] )

    return l,f
Example #34
0
    def broaden(self, fwhm=1e-10, linetype=1, eta=[]):
        output = Spectrum(self.wavelengths)
        window = max(output.wavelengths) - min(output.wavelengths)
        center = max(output.wavelengths) - window/2

        if fwhm <= 0:
            raise ValueError('The linewidth must be positive and nonzero.')

        # Trapezoidal 
        elif linetype is 0:
            pass

        # Gaussian
        elif linetype is 1:
            sigma = fwhm / (2 * log(2)**0.5)
            slit = exp(-(output.wavelengths - center)**2/(2 * sigma**2))

        # Lorentzian
        elif linetype is 2:
            gamma = fwhm
            slit = 0.5 * (gamma / ((output.wavelengths - center)**2 \
                                    + 0.25 * gamma**2)) / pi

        # Pseudo-Voigt
        elif linetype is 3:
            if not eta:
                print "Eta required for pseudo-Voigt profile, quitting"
                sys.exit(0)
            sigma = fwhm
            sigma_g = fwhm / (2 * log(2)**0.5)
            g = exp(-(output.wavelengths - center)**2/(2 * sigma_g**2)) \
                / (sigma_g * (2*pi)**0.5)
            l = (0.5 * sigma / pi) \
                / ((output.wavelengths - center)**2 + .25 * sigma**2)
            slit = eta * l + (1 - eta) * g


        output.intensities = pylab.convolve(self.intensities, slit, 'same')

        return output
Example #35
0
# step 2 : calculate psp. Its maximum is used below as a fudge-factor for the psp amplitude
psp =  ( Cm * pF ) / ( tau_s * ms ) * (1/( Cm * pF )) * (e/( tau_s * ms ) ) * \
     (  ((-t_psp * exp(-t_psp/(tau_s * ms) )) / (1/( tau_s * ms )-1 / ( tau_m * ms ) )) +\
        (exp(-t_psp/( tau_m * ms )) - exp(-t_psp/( tau_s * ms ))) / ((1/( tau_s * ms ) - 1/( tau_m * ms ))**2)  )

# step 3: normalize to amplitude 1, thereby obtaining the maximum
fudge = 1 / numpy.max(psp)  # fudge is also used below
psp *= fudge

# step 4: pad with zeros on the left side. Avoids offsets when using convolution
tmp = numpy.zeros(2 * len(psp))
tmp[len(psp) - 1:-1] += psp
psp = tmp
del tmp

P = a * weight * pylab.convolve(gauss, psp)

l = len(P)
t_P = convolution_resolution * numpy.linspace(
    -l / 2., l / 2., l) + pulsetime + 1.  # one ms delay

#########################################################################
# simulation section

nest.ResetKernel()

nest.SetStatus([0], [{'resolution': simulation_resolution}])
J = Cm * weight / tau_s * fudge
nest.SetDefaults('static_synapse', {'weight': J})

n = nest.Create(
Example #36
0
# step 2 : calculate psp. Its maximum is used below as a fudge-factor for the psp amplitude
psp =  ( Cm * pF ) / ( tau_s * ms ) * (1/( Cm * pF )) * (e/( tau_s * ms ) ) * \
     (  ((-t_psp * exp(-t_psp/(tau_s * ms) )) / (1/( tau_s * ms )-1 / ( tau_m * ms ) )) +\
        (exp(-t_psp/( tau_m * ms )) - exp(-t_psp/( tau_s * ms ))) / ((1/( tau_s * ms ) - 1/( tau_m * ms ))**2)  )

# step 3: normalize to amplitude 1, thereby obtaining the maximum
fudge = 1/numpy.max(psp) # fudge is also used below
psp *= fudge

# step 4: pad with zeros on the left side. Avoids offsets when using convolution
tmp = numpy.zeros(2*len(psp))
tmp[len(psp)-1:-1] += psp
psp = tmp
del tmp

P = a * weight * pylab.convolve(gauss, psp)

l   = len(P)
t_P = convolution_resolution * numpy.linspace( -l/2., l/2., l) + pulsetime + 1. # one ms delay



#########################################################################
# simulation section

nest.ResetKernel()

nest.SetStatus([0],[{'resolution':simulation_resolution}])
J = Cm*weight/tau_s*fudge
nest.SetDefaults('static_synapse', {'weight':J} )
Example #37
0
def main():
    import optparse
    from numpy import sum

    # Parse command line
    parser = optparse.OptionParser(usage=USAGE)
    parser.add_option("-p",
                      "--plot",
                      action="store_true",
                      help="Generate pdf with IR-spectrum")
    parser.add_option("-i",
                      "--info",
                      action="store_true",
                      help="Set up/ Calculate vibrations & quit")
    parser.add_option("-s",
                      "--suffix",
                      action="store",
                      help="Call suffix for binary e.g. 'mpirun -n 4 '",
                      default='')
    parser.add_option("-r",
                      "--run",
                      action="store",
                      help="path to FHI-aims binary",
                      default='')
    parser.add_option("-x",
                      "--relax",
                      action="store_true",
                      help="Relax initial geometry")
    parser.add_option("-m",
                      "--molden",
                      action="store_true",
                      help="Output in molden format")
    parser.add_option("-w",
                      "--distort",
                      action="store_true",
                      help="Output geometry distorted along imaginary modes")
    parser.add_option("-t",
                      "--submit",
                      action="store",
                      help="""\
Path to submission script, string <jobname>
will be replaced by name + counter, string 
                            <outfile> will be replaced by filename""")
    parser.add_option("-d",
                      "--delta",
                      action="store",
                      type="float",
                      help="Displacement",
                      default=0.0025)

    options, args = parser.parse_args()
    if options.info:
        print __doc__
        sys.exit(0)
    if len(args) != 2:
        parser.error("Need exactly two arguments")

    AIMS_CALL = options.suffix + ' ' + options.run
    hessian_thresh = -1
    name = args[0]
    mode = args[1]
    delta = options.delta

    run_aims = False
    if options.run != '': run_aims = True

    submit_script = options.submit is not None

    if options.plot:
        import matplotlib as mpl
        mpl.use('Agg')
        from pylab import figure

    if options.plot or mode == '1':
        from pylab import savetxt, transpose, eig, argsort, sort,\
            sign, pi, dot, sum, linspace, argmin, r_, convolve

    # Constant from scipy.constants
    bohr = constants.value('Bohr radius') * 1.e10
    hartree = constants.value('Hartree energy in eV')
    at_u = constants.value('atomic mass unit-kilogram relationship')
    eV = constants.value('electron volt-joule relationship')
    c = constants.value('speed of light in vacuum')
    Ang = 1.0e-10
    hbar = constants.value('Planck constant over 2 pi')
    Avo = constants.value('Avogadro constant')
    kb = constants.value('Boltzmann constant in eV/K')
    hessian_factor = eV / (at_u * Ang * Ang)
    grad_dipole_factor = (eV / (1. / (10 * c))) / Ang  #(eV/Ang -> D/Ang)
    ir_factor = 1

    # Asign all filenames
    inputgeomerty = 'geometry.in.' + name
    inputcontrol = 'control.in.' + name
    atomicmasses = 'masses.' + name + '.dat'
    xyzfile = name + '.xyz'
    moldenname = name + '.molden'
    hessianname = 'hessian.' + name + '.dat'
    graddipolename = 'grad_dipole.' + name + '.dat'
    irname = 'ir.' + name + '.dat'
    deltas = array([-delta, delta])
    coeff = array([-1, 1])
    c_zero = -1. / (2. * delta)

    f = open('control.in', 'r')  # read control.in template
    template_control = f.read()
    f.close

    if submit_script:
        f = open(options.submit, 'r')  # read submission script template
        template_job = f.read()
        f.close

    folder = ''  # Dummy
    ########### Central Point ##################################################
    if options.relax and mode == '0':
        # First relax input geometry
        filename = name + '.out'
        folder = name + '_relaxation'
        if not os.path.exists(folder): os.mkdir(folder)  # Create folder
        shutil.copy('geometry.in', folder + '/geometry.in')  # Copy geometry
        new_control = open(folder + '/control.in', 'w')
        new_control.write(template_control +
                          'relax_geometry trm 1E-3\n')  # Relax!
        new_control.close()
        os.chdir(folder)  # Change directoy
        print 'Central Point'
        if run_aims:
            os.system(AIMS_CALL + ' > ' +
                      filename)  # Run aims and pipe the output

#  into a file named 'filename'
        if submit_script: replace_submission(template_job, name, 0, filename)
        os.chdir('..')

    ############################################################################
    # Check for relaxed geometry
    if os.path.exists(folder + '/geometry.in.next_step'):
        geometry = open(folder + '/geometry.in.next_step', 'r')
    else:
        geometry = open('geometry.in', 'r')

    # Read input geometry
    n_line = 0
    struc = structure()
    lines = geometry.readlines()

    for line in lines:
        n_line = n_line + 1
        if line.rfind('set_vacuum_level') != -1:  # Vacuum Level
            struc.vacuum_level = float(split_line(line)[-1])
        if line.rfind('lattice_vector') != -1:  # Lattice vectors and periodic
            lat = split_line(line)[1:]
            struc.lattic_vector = append(struc.lattic_vector,
                                         float64(array(lat))[newaxis, :],
                                         axis=0)
            struc.periodic = True
        if line.rfind('atom') != -1:  # Set atoms
            line_vals = split_line(line)
            at = Atom(line_vals[-1], line_vals[1:-1])
            if n_line < len(lines):
                nextline = lines[n_line]
                if nextline.rfind(
                        'constrain_relaxation') != -1:  # constrained?
                    at = Atom(line_vals[-1], line_vals[1:-1], True)
                else:
                    at = Atom(line_vals[-1], line_vals[1:-1])
            struc.join(at)
    geometry.close()
    n_atoms = struc.n()
    n_constrained = n_atoms - sum(struc.constrained)

    # Atomic mass file
    mass_file = open(atomicmasses, 'w')
    mass_vector = zeros([0])
    for at_unconstrained in struc.atoms[struc.constrained == False]:
        mass_vector = append(mass_vector,
                             ones(3) * 1. / sqrt(at_unconstrained.mass()))
        line = '{0:10.5f}'.format(at_unconstrained.mass())
        for i in range(3):
            line = line + '{0:11.4f}'.format(at_unconstrained.coord[i])
        line = line + '{0:}\n'.format(at_unconstrained.kind)
        mass_file.writelines(line)
    mass_file.close()

    # Init
    dip = zeros([n_constrained * 3, 3])
    hessian = zeros([n_constrained * 3, n_constrained * 3])
    index = 0
    counter = 1

    # Set up / Read folders for displaced atoms
    for atom in arange(n_atoms)[struc.constrained == False]:
        for coord in arange(3):
            for delta in deltas:
                filename=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\
                 str(delta)+'.out'
                folder=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\
                 str(delta)
                if mode == '0':  # Put new geometry and control.in into folder
                    struc_new = copy.deepcopy(struc)
                    struc_new.atoms[atom].coord[coord]=\
                                                struc_new.atoms[atom].coord[coord]+delta
                    geoname='geometry.i_atom_'+str(atom)+'.i_coord_'+str(coord)+\
                            '.displ_'+str(delta)+'.in'
                    if not os.path.exists(folder): os.mkdir(folder)
                    new_geo = open(folder + '/geometry.in', 'w')
                    newline='#\n# temporary structure-file for finite-difference '+\
                     'calculation of forces\n'
                    newline=newline+'# displacement {0:8.4f} of \# atom '.format(delta)+\
                      '{0:5} direction {1:5}\n#\n'.format(atom,coord)
                    new_geo.writelines(newline + struc_new.to_str())
                    new_geo.close()
                    new_control = open(folder + '/control.in', 'w')
                    template_control = template_control.replace(
                        'relax_geometry', '#relax_geometry')
                    new_control.write(template_control+'compute_forces .true. \n'+\
                        'final_forces_cleaned '+\
                        '.true. \noutput dipole \n')
                    new_control.close()
                    os.chdir(folder)  # Change directoy
                    print 'Processing atom: '+str(atom+1)+'/'+str(n_atoms)+', coord.: '+\
                      str(coord+1)+'/'+str(3)+', delta: '+str(delta)
                    if run_aims:
                        os.system(AIMS_CALL + ' > ' +
                                  filename)  # Run aims and pipe the output
                #  into a file named 'filename'
                    if submit_script:
                        replace_submission(template_job, name, counter,
                                           filename)
                    # os.system('qsub job.sh') # Mind the environment variables
                    os.chdir('..')

                if mode == '1':  # Read output
                    forces_reached = False
                    atom_count = 0
                    data = open(folder + '/' + filename)
                    for line in data.readlines():
                        if line.rfind(
                                'Dipole correction potential jump') != -1:
                            dip_jump = float(split_line(line)[-2])  # Periodic
                        if line.rfind('| Total dipole moment [eAng]') != -1:
                            dip_jump = float64(
                                split_line(line)[-3:])  # Cluster
                        if forces_reached and atom_count < n_atoms:  # Read Forces
                            struc.atoms[atom_count].force = float64(
                                split_line(line)[2:])
                            atom_count = atom_count + 1
                            if atom_count == n_atoms:
                                forces_reached = False
                        if line.rfind('Total atomic forces') != -1:
                            forces_reached = True
                    data.close()
                    if struc.periodic:
                        dip[index, 2] = dip[
                            index,
                            2] + dip_jump * coeff[deltas == delta] * c_zero
                    else:
                        dip[index, :] = dip[index, :] + dip_jump * coeff[
                            deltas == delta] * c_zero
                    forces = array([])
                    for at_unconstrained in struc.atoms[struc.constrained ==
                                                        False]:
                        forces = append(
                            forces,
                            coeff[deltas == delta] * at_unconstrained.force)
                    hessian[index, :] = hessian[index, :] + forces * c_zero
                counter = counter + 1
            index = index + 1
    if mode == '1':  # Calculate vibrations
        print 'Entering hessian diagonalization'
        print 'Number of atoms                = ' + str(n_atoms)
        print 'Name of Hessian input file     = ' + hessianname
        print 'Name of grad dipole input file = ' + graddipolename
        print 'Name of Masses  input file     = ' + atomicmasses
        print 'Name of XYZ output file        = ' + xyzfile
        print 'Threshold for Matrix elements  = ' + str(hessian_thresh)
        if (hessian_thresh < 0.0):            print '     All matrix elements are taken'+\
' into account by default\n'
        savetxt(hessianname, hessian)
        savetxt(graddipolename, dip)

        mass_mat = mass_vector[:, newaxis] * mass_vector[newaxis, :]
        hessian[abs(hessian) < hessian_thresh] = 0.0
        hessian = hessian * mass_mat * hessian_factor
        hessian = (hessian + transpose(hessian)) / 2.
        # Diagonalize hessian (scipy)
        print 'Solving eigenvalue system for Hessian Matrix'
        freq, eig_vec = eig(hessian)
        print 'Done ... '
        eig_vec = eig_vec[:, argsort(freq)]
        freq = sort(sign(freq) * sqrt(abs(freq)))
        ZPE = hbar * (freq) / (2.0 * eV)
        freq = (freq) / (200. * pi * c)

        grad_dipole = dip * grad_dipole_factor
        eig_vec = eig_vec * mass_vector[:, newaxis] * ones(
            len(mass_vector))[newaxis, :]
        infrared_intensity = sum(dot(transpose(grad_dipole),eig_vec)**2,axis=0)*\
                             ir_factor
        reduced_mass = sum(eig_vec**2, axis=0)
        norm = sqrt(reduced_mass)
        eig_vec = eig_vec / norm

        # The rest is output, xyz, IR,...
        print 'Results\n'
        print 'List of all frequencies found:'
        print 'Mode number      Frequency [cm^(-1)]   Zero point energy [eV]   '+\
              'IR-intensity [D^2/Ang^2]'
        for i in range(len(freq)):
            print '{0:11}{1:25.8f}{2:25.8f}{3:25.8f}'.format(
                i + 1, freq[i], ZPE[i], infrared_intensity[i])
        print '\n'
        print 'Summary of zero point energy for entire system:'
        print '| Cumulative ZPE               = {0:15.8f} eV'.format(sum(ZPE))
        print '| without first six eigenmodes = {0:15.8f} eV\n'.format(
            sum(ZPE) - sum(ZPE[:6]))
        print 'Stability checking - eigenvalues should all be positive for a '+\
               'stable structure. '
        print 'The six smallest frequencies should be (almost) zero:'
        string = ''
        for zz in ZPE[:6]:
            string = string + '{0:25.8f}'.format(zz)
        print string
        print 'Compare this with the largest eigenvalue, '
        print '{0:25.8f}'.format(freq[-1])

        nums = arange(n_atoms)[struc.constrained == False]
        nums2 = arange(n_atoms)[struc.constrained]
        newline = ''
        newline_ir = '[INT]\n'
        if options.molden:
            newline_molden = '[Molden Format]\n[GEOMETRIES] XYZ\n'
            newline_molden = newline_molden + '{0:6}\n'.format(n_atoms) + '\n'
            for i_atoms in range(n_constrained):
                newline_molden = newline_molden + '{0:6}'.format(
                    struc.atoms[nums[i_atoms]].kind)
                for i_coord in range(3):
                    newline_molden = newline_molden + '{0:10.4f}'.format(
                        struc.atoms[nums[i_atoms]].coord[i_coord])
                newline_molden = newline_molden + '\n'
            newline_molden = newline_molden + '[FREQ]\n'
            for i in range(len(freq)):
                newline_molden = newline_molden + '{0:10.3f}\n'.format(freq[i])
            newline_molden = newline_molden + '[INT]\n'
            for i in range(len(freq)):
                newline_molden = newline_molden + '{0:17.6e}\n'.format(
                    infrared_intensity[i])
            newline_molden = newline_molden + '[FR-COORD]\n'
            newline_molden = newline_molden + '{0:6}\n'.format(n_atoms) + '\n'
            for i_atoms in range(n_constrained):
                newline_molden = newline_molden + '{0:6}'.format(
                    struc.atoms[nums[i_atoms]].kind)
                for i_coord in range(3):
                    newline_molden = newline_molden + '{0:10.4f}'.format(
                        struc.atoms[nums[i_atoms]].coord[i_coord] / bohr)
                newline_molden = newline_molden + '\n'
            newline_molden = newline_molden + '[FR-NORM-COORD]\n'

        for i in range(len(freq)):
            newline = newline + '{0:6}\n'.format(n_atoms)
            if freq[i] > 0:
                newline = newline + 'stable frequency at '
            elif freq[i] < 0:
                newline = newline + 'unstable frequency at '
                if options.distort and freq[i] < -50:
                    struc_new = copy.deepcopy(struc)
                    for i_atoms in range(n_constrained):
                        for i_coord in range(3):
                            struc_new.atoms[i_atoms].coord[i_coord]=\
                            struc_new.atoms[i_atoms].coord[i_coord]+\
                           eig_vec[(i_atoms)*3+i_coord,i]
                    geoname = name + '.distorted.vibration_' + str(
                        i + 1) + '.geometry.in'
                    new_geo = open(geoname, 'w')
                    newline_geo = '#\n# distorted structure-file for based on eigenmodes\n'
                    newline_geo=newline_geo+\
                            '# vibration {0:5} :{1:10.3f} 1/cm\n#\n'.format(i+1,freq[i])
                    new_geo.writelines(newline_geo + struc_new.to_str())
                    new_geo.close()
            elif freq[i] == 0:
                newline = newline + 'translation or rotation '
            newline = newline + '{0:10.3f} 1/cm IR int. is '.format(freq[i])
            newline = newline + '{0:10.4e} D^2/Ang^2; red. mass is '.format(
                infrared_intensity[i])
            newline = newline + '{0:5.3f} a.m.u.; force const. is '.format(
                1.0 / reduced_mass[i])
            newline = newline + '{0:5.3f} mDyne/Ang.\n'.format(
                ((freq[i] *
                  (200 * pi * c))**2) * (1.0 / reduced_mass[i]) * at_u * 1.e-2)
            if options.molden:                newline_molden=newline_molden+\
                                      'vibration {0:6}\n'.format(i+1)
            for i_atoms in range(n_constrained):
                newline = newline + '{0:6}'.format(
                    struc.atoms[nums[i_atoms]].kind)
                for i_coord in range(3):
                    newline = newline + '{0:10.4f}'.format(
                        struc.atoms[nums[i_atoms]].coord[i_coord])
                for i_coord in range(3):
                    newline = newline + '{0:10.4f}'.format(
                        eig_vec[(i_atoms) * 3 + i_coord, i])
                    if options.molden:
                        newline_molden = newline_molden + '{0:10.4f}'.format(
                            eig_vec[(i_atoms) * 3 + i_coord, i] / bohr)
                newline = newline + '\n'
                if options.molden: newline_molden = newline_molden + '\n'
            for i_atoms in range(n_atoms - n_constrained):
                newline = newline + '{0:6}'.format(
                    struc.atoms[nums2[i_atoms]].kind)
                for i_coord in range(3):
                    newline = newline + '{0:10.4f}'.format(
                        struc.atoms[nums2[i_atoms]].coord[i_coord])
                for i_coord in range(3):
                    newline = newline + '{0:10.4f}'.format(0.0)
                newline = newline + '\n'
            newline_ir = newline_ir + '{0:10.4e}\n'.format(
                infrared_intensity[i])
        xyz = open(xyzfile, 'w')
        xyz.writelines(newline)
        xyz.close()
        ir = open(irname, 'w')
        ir.writelines(newline_ir)
        ir.close()
        if options.molden:
            molden = open(moldenname, 'w')
            molden.writelines(newline_molden)
            molden.close()

        if mode == '1' and options.plot:
            x = linspace(freq.min() - 500, freq.max() + 500, 1000)
            z = zeros(len(x))
            for i in range(len(freq)):
                z[argmin(abs(x - freq[i]))] = infrared_intensity[i]
            window_len = 150
            gauss = signal.gaussian(window_len, 10)
            s = r_[z[window_len - 1:0:-1], z, z[-1:-window_len:-1]]
            z_convolve = convolve(gauss / gauss.sum(), s,
                                  mode='same')[window_len - 1:-window_len + 1]
            fig = figure(0)
            ax = fig.add_subplot(111)
            ax.plot(x, z_convolve, 'r', lw=2)
            ax.set_xlim([freq.min() - 500, freq.max() + 500])
            ax.set_ylim([-0.01, ax.get_ylim()[1]])
            ax.set_yticks([])
            ax.set_xlabel('Frequency [1/cm]', size=20)
            ax.set_ylabel('Intensity [a.u.]', size=20)
            fig.savefig(name + '_IR_spectrum.pdf')

        print '\n Done. '
Example #38
0
BO2 = zeros((tmax / avgOn, N2))
Hrv = HRF()

'#####################################################  MAIN  ###########################################################'

'####################  TC_998'
t0 = time()
for i in range(nTC):
    TC1[i * step:(i + 1) * step, :] = np_load(dir_TC1 + dir_sub +
                                              'TC_%i.npy' % i)
print 'TC 998 loaded      : %.2fs' % (time() - t0)

'####################  BO_998'
t0 = time()
for k in range(N1):
    Bk = convolve(TC1[:, k], Hrv)[:tmax]
    for o in range(avgOn):
        BO1[:, k] += Bk[o::avgOn]
BO1 /= avgOn
np_save(dir_BO1 + 'BO_%i_' % N1 + name + '.npy', BO1)
print 'BO 998 generated   : %.2fs' % (time() - t0)

'####################  BO_66, FC_B66, FC_B998'
t0 = time()
for n in range(N1):
    BO2[:, D998_D66[n]] += BO1[:, n]
for t in range(BO1.shape[0]):
    BO2[t, :] /= AvgN_D66
np_save(dir_BO2 + 'BO_%i_' % N2 + name + '.npy', BO2)
FC2 = fastPearsonCorrelation(BO2)
del BO2
def exercise1():
    """ this function gives a visualization of the whole data set
    scatter plots for the different neurons and directions, as well as the mean spikes druing the timeline and the estimated fring rate (by a kernel convolution, window of width 100)"""

    # load data1.
    a1 = scipy.io.loadmat("bootstrap_joe093-3-C3-MO.mat")
    a2 = scipy.io.loadmat("bootstrap_joe108-7-C3-MO.mat")
    a3 = scipy.io.loadmat("bootstrap_joe112-5-C3-MO.mat")
    a4 = scipy.io.loadmat("bootstrap_joe112-6-C3-MO.mat")
    a5 = scipy.io.loadmat("bootstrap_joe145-4-C3-MO.mat")
    data1 = a1["GDFcell"][0]
    data2 = a2["GDFcell"][0]
    data3 = a3["GDFcell"][0]
    data4 = a4["GDFcell"][0]
    data5 = a5["GDFcell"][0]

    # here the binary spike trains of the neurons are stored, for every neuron and every direction
    binary = plt.zeros((5, 6, 2000))
    # and here the spike times, for every neuron, every direction and every trial
    spike_times = [[[[] * 1] * 35] * 6] * 5
    for i in plt.arange(5):  # neuron
        exec "%s=%s" % ("data", "data" + str(i + 1))
        fig = plt.figure()
        ax = plt.axes([0, 0, 1, 1])
        circ = plt.Circle((0.5, 0.48), radius=0.051, edgecolor="k", LineStyle="solid", facecolor="w")
        ax.add_patch(circ)
        plt.text(0.453, 0.465, "Neuron " + str(i + 1))
        ax.set_yticks([])
        ax.set_xticks([])
        for j in plt.arange(6):  # direction
            if j == 0:
                ax = plt.axes([0.3, 0.8, 0.3, 0.1])
            elif j == 1:
                ax = plt.axes([0.6, 0.55, 0.3, 0.1])
            elif j == 2:
                ax = plt.axes([0.6, 0.3, 0.3, 0.1])
            elif j == 3:
                ax = plt.axes([0.3, 0.1, 0.3, 0.1])
            elif j == 4:
                ax = plt.axes([0.1, 0.3, 0.3, 0.1])
            elif j == 5:
                ax = plt.axes([0.1, 0.55, 0.3, 0.1])
            data[j] = data[j].astype(int)
            data[j][:, 1] = data[j][:, 1] - 1000
            for k in plt.arange(35) + 1:  # trials
                indi = plt.find(data[j][:, 0] == k)
                spike_times[i][j][k - 1] = data[j][indi, 1]
                for l in spike_times[i][j][k - 1] + 999:
                    if l < 2000:
                        binary[i][j][l] += 1
                # plots the scatter plots
                plt.plot(data[j][indi, 1], plt.ones(data[j][indi, 1].shape[0]) * k, "b|")
            plt.title("direction" + str(j + 1))
            plt.xlabel("time [ms]")
            plt.ylabel("trial_id")
            plt.xlim([-1000, 1000])
            for tick in ax.yaxis.get_major_ticks():
                tick.label1.set_fontsize(8)
            for tick in ax.xaxis.get_major_ticks():
                tick.label1.set_fontsize(8)
        fig.savefig("neuron" + str(i + 1) + "spikes", format="png")

    # this is the definition of the kernel
    w = 100
    h = 1.0 / w
    k = plt.ones((w,)) * h

    # normalization by the number of trials
    binary = binary / 35.0

    for i in plt.arange(5):
        fig = plt.figure()
        ax = plt.axes([0, 0, 1, 1])
        circ = plt.Circle((0.5, 0.48), radius=0.051, edgecolor="k", LineStyle="solid", facecolor="w")
        ax.add_patch(circ)
        plt.text(0.453, 0.465, "Neuron " + str(i + 1))
        ax.set_yticks([])
        ax.set_xticks([])
        for j in plt.arange(6):
            if j == 0:
                ax = plt.axes([0.3, 0.8, 0.3, 0.1])
            elif j == 1:
                ax = plt.axes([0.6, 0.55, 0.3, 0.1])
            elif j == 2:
                ax = plt.axes([0.6, 0.3, 0.3, 0.1])
            elif j == 3:
                ax = plt.axes([0.3, 0.1, 0.3, 0.1])
            elif j == 4:
                ax = plt.axes([0.1, 0.3, 0.3, 0.1])
            elif j == 5:
                ax = plt.axes([0.1, 0.55, 0.3, 0.1])
            # plots the mean spikes along the timeline of the experiment
            plt.plot(plt.arange(-1000, 1000), binary[i][j])
            plt.ylabel("mean spikes")
            plt.hold(True)
            ax2 = ax.twinx()

            # plots the estimated firing rate on a different y axis
            plt.plot(plt.arange(-1000, 1000), plt.convolve(binary[i][j], k, mode="same"), "g")
            plt.title("direction" + str(j + 1))
            plt.xlabel("time [ms]")
            plt.ylabel("estimated r")
            for tick in ax.yaxis.get_major_ticks():
                tick.label1.set_fontsize(8)
            for tick in ax2.yaxis.get_major_ticks():
                tick.label2.set_fontsize(8)
            for tick in ax.xaxis.get_major_ticks():
                tick.label1.set_fontsize(8)
        fig.savefig("neuron" + str(i + 1) + "rates", format="png")
Example #40
0
out = []
inp = []

with open('../../../measurements/20140610/10Hz_random/scope_5.csv', newline='') as csvfile:
	spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
	ii = 0
	for row in spamreader:
		ii = ii+1
		if ii > 3:
			out.append(float(row[1]))
			inp.append(float(row[2]))


# Filter
filtered_out = pylab.convolve([-1,1], out)

# Sort
high = False

digital_out = []

for o in out:
	if o > 0.05:
		high = False
	elif o < -0.12:
		high = True
	if high:
		digital_out.append(1)
	else:
		digital_out.append(0)
Example #41
0
def build_fft(input_signal,
              filter_coefficients,
              threshold_windows=6,
              boundary=0):
    """generate fast transform fourier by windows
    Params :
        input_signal : the audio signal
        filter_coefficients : coefficients of the chirplet bank
        threshold_windows : calcul the size of the windows
        boundary : manage the bounds of the signal
    Returns :
        fast Fourier transform applied by windows to the audio signal

    """
    num_coeffs = filter_coefficients.size
    #print(n,boundary,M)
    half_size = num_coeffs // 2
    signal_size = input_signal.size
    #power of 2 to apply fast fourier transform
    windows_size = 2**ceil(log2(num_coeffs * (threshold_windows + 1)))
    number_of_windows = floor(signal_size // windows_size)

    if number_of_windows == 0:
        return fft_based(input_signal, filter_coefficients, boundary)

    windowed_fft = empty_like(input_signal)
    #pad with 0 to have a size in a power of 2
    windows_size = int(windows_size)

    zeropadding = np.lib.pad(filter_coefficients,
                             (0, windows_size - num_coeffs),
                             'constant',
                             constant_values=0)

    h_fft = fft(zeropadding)

    #to browse the whole signal
    current_pos = 0

    #apply fft to a part of the signal. This part has a size which is a power
    #of 2
    if boundary == 0:  #ZERO PADDING

        #window is half padded with since it's focused on the first half
        window = input_signal[current_pos:current_pos + windows_size -
                              half_size]
        zeropaddedwindow = np.lib.pad(window, (len(h_fft) - len(window), 0),
                                      'constant',
                                      constant_values=0)
        x_fft = fft(zeropaddedwindow)

    elif boundary == 1:  #SYMMETRIC
        window = concatenate([
            flipud(input_signal[:half_size]),
            input_signal[current_pos:current_pos + windows_size - half_size]
        ])
        x_fft = fft(window)

    else:
        x_fft = fft(input_signal[:windows_size])

    windowed_fft[:windows_size - num_coeffs] = (ifft(
        x_fft * h_fft)[num_coeffs - 1:-1]).real

    current_pos += windows_size - num_coeffs - half_size
    #apply fast fourier transofm to each windows
    while current_pos + windows_size - half_size <= signal_size:

        x_fft = fft(input_signal[current_pos - half_size:current_pos +
                                 windows_size - half_size])
        #Suppress the warning, work on the real/imagina
        windowed_fft[current_pos:current_pos + windows_size -
                     num_coeffs] = (ifft(x_fft * h_fft)[num_coeffs -
                                                        1:-1]).real
        current_pos += windows_size - num_coeffs
    # print(countloop)
    #apply fast fourier transform to the rest of the signal
    if windows_size - (signal_size - current_pos + half_size) < half_size:

        window = input_signal[current_pos - half_size:]
        zeropaddedwindow = np.lib.pad(
            window,
            (0, int(windows_size - (signal_size - current_pos + half_size))),
            'constant',
            constant_values=0)
        x_fft = fft(zeropaddedwindow)
        windowed_fft[current_pos:] = roll(ifft(
            x_fft * h_fft), half_size)[half_size:half_size +
                                       windowed_fft.size - current_pos].real
        windowed_fft[-half_size:] = convolve(input_signal[-num_coeffs:],
                                             filter_coefficients,
                                             'same')[-half_size:]
    else:

        window = input_signal[current_pos - half_size:]
        zeropaddedwindow = np.lib.pad(
            window,
            (0, int(windows_size - (signal_size - current_pos + half_size))),
            'constant',
            constant_values=0)
        x_fft = fft(zeropaddedwindow)
        windowed_fft[current_pos:] = ifft(
            x_fft * h_fft)[num_coeffs - 1:num_coeffs + windowed_fft.size -
                           current_pos - 1].real

    return windowed_fft
Example #42
0
def main():
  import optparse
  from numpy import sum

  # Parse command line
  parser = optparse.OptionParser(usage=USAGE)
  parser.add_option("-p", "--plot", action="store_true",
                    help="Generate pdf with IR-spectrum, broadened with Lorentzian")
  parser.add_option("-i", "--info", action="store_true",
                      help="Set up/ Calculate vibrations & quit")
  parser.add_option("-s", "--suffix", action="store",
                    help="Call suffix for binary e.g. 'mpirun -n 4 '",
                    default='')
  parser.add_option("-r", "--run", action="store",
                    help="path to FHI-aims binary",default='')
  parser.add_option("-x", "--relax", action="store_true",
                    help="Relax initial geometry")
  parser.add_option("-m", "--molden", action="store_true",
                    help="Output in molden format")
  parser.add_option("-w", "--distort", action="store_true",
                    help="Output geometry distorted along imaginary modes")
  parser.add_option("-t", "--submit", action="store",
                    help="""\
Path to submission script, string <jobname>
will be replaced by name + counter, string 
                            <outfile> will be replaced by filename""")
  parser.add_option("-d", "--delta", action="store", type="float",
                    help="Displacement", default=0.0025)
  parser.add_option("-b", "--broadening", action="store", type="float",
                    help="Broadening for IR-spectrum in cm^{-1}", default=5)

  options, args = parser.parse_args()
  if options.info:
      print __doc__
      sys.exit(0)
  if len(args) != 2:
      parser.error("Need exactly two arguments")
  
  AIMS_CALL=options.suffix+' '+options.run
  hessian_thresh = -1
  name=args[0]
  mode=args[1] 
  delta=options.delta
  broadening=options.broadening

  run_aims=False
  if options.run!='': run_aims=True
  
  submit_script = options.submit is not None
  
  if options.plot:
    import matplotlib as mpl
    mpl.use('Agg') 
    from pylab import figure

  if options.plot or mode=='1' or mode=='2':
    from pylab import savetxt, transpose, eig, argsort, sort,\
		      sign, pi, dot, sum, linspace, argmin, r_, convolve
		 
  # Constant from scipy.constants
  bohr=constants.value('Bohr radius')*1.e10
  hartree=constants.value('Hartree energy in eV')
  at_u=constants.value('atomic mass unit-kilogram relationship')
  eV=constants.value('electron volt-joule relationship')
  c=constants.value('speed of light in vacuum')
  Ang=1.0e-10
  hbar=constants.value('Planck constant over 2 pi')
  Avo=constants.value('Avogadro constant')
  kb=constants.value('Boltzmann constant in eV/K')
  pi=constants.pi
  hessian_factor   = eV/(at_u*Ang*Ang) 
  grad_dipole_factor=(eV/(1./(10*c)))/Ang  #(eV/Ang -> D/Ang)
  ir_factor = 1
  
  # Asign all filenames
  inputgeomerty = 'geometry.in.'+name
  inputcontrol  = 'control.in.'+name
  atomicmasses  = 'masses.'+name+'.dat'; 
  xyzfile       = name+'.xyz';
  moldenname    =name+'.molden';
  hessianname   = 'hessian.'+name+'.dat'; 
  graddipolename   = 'grad_dipole.'+name+'.dat'; 
  irname   = 'ir.'+name+'.dat'; 
  deltas=array([-delta,delta])
  coeff=array([-1,1])
  c_zero = - 1. / (2. * delta)


  f=open('control.in','r')                   # read control.in template
  template_control=f.read()
  f.close

  if submit_script:
    f=open(options.submit,'r')               # read submission script template
    template_job=f.read()
    f.close

  folder=''                                  # Dummy
  ########### Central Point ##################################################
  if options.relax and (mode=='0' or mode=='2'):
    # First relax input geometry
    filename=name+'.out'
    folder=name+'_relaxation' 
    if not os.path.exists(folder): os.mkdir(folder)            # Create folder
    shutil.copy('geometry.in', folder+'/geometry.in')          # Copy geometry
    new_control=open(folder+'/control.in','w')
    new_control.write(template_control+'relax_geometry trm 1E-3\n') # Relax!
    new_control.close()
    os.chdir(folder)                             # Change directoy
    print 'Central Point'
    if run_aims:
      os.system(AIMS_CALL+' > '+filename)       # Run aims and pipe the output 
						#  into a file named 'filename'
    if submit_script: replace_submission(template_job, name, 0, filename)
    os.chdir('..') 

  ############################################################################
  # Check for relaxed geometry
  if os.path.exists(folder+'/geometry.in.next_step'):  
    geometry=open(folder+'/geometry.in.next_step','r')
  else:
    geometry=open('geometry.in','r')
    
  # Read input geometry  
  n_line=0
  struc=structure()
  lines=geometry.readlines()

  for line in lines:
    n_line= n_line+1
    if line.rfind('set_vacuum_level')!=-1:   # Vacuum Level
      struc.vacuum_level=float(split_line(line)[-1])
    if line.rfind('lattice_vector')!=-1:    # Lattice vectors and periodic
      lat=split_line(line)[1:]
      struc.lattice_vector=append(struc.lattice_vector,float64(array(lat))
			  [newaxis,:],axis=0)
      struc.periodic=True
    if line.rfind('atom')!=-1:              # Set atoms
      line_vals=split_line(line)
      at=Atom(line_vals[-1],line_vals[1:-1])
      if n_line<len(lines):
	  nextline=lines[n_line]
	  if nextline.rfind('constrain_relaxation')!=-1: # constrained?
	    at=Atom(line_vals[-1],line_vals[1:-1],True)
	  else:
	    at=Atom(line_vals[-1],line_vals[1:-1])
      struc.join(at)         
  geometry.close()  
  n_atoms= struc.n()
  n_constrained=n_atoms-sum(struc.constrained)

  # Atomic mass file
  mass_file=open(atomicmasses,'w')
  mass_vector=zeros([0])
  for at_unconstrained in struc.atoms[struc.constrained==False]:
      mass_vector=append(mass_vector,ones(3)*1./sqrt(at_unconstrained.mass()))
      line='{0:10.5f}'.format(at_unconstrained.mass())
      for i in range(3):
	line=line+'{0:11.4f}'.format(at_unconstrained.coord[i])
      line=line+'{0:}\n'.format(at_unconstrained.kind)
      mass_file.writelines(line)
  mass_file.close()

  # Init
  dip = zeros([n_constrained*3,3])
  hessian = zeros([n_constrained*3,n_constrained*3])
  index=0
  counter=1
  
  # Set up / Read folders for displaced atoms
  for atom in arange(n_atoms)[struc.constrained==False]:
    for coord in arange(3):
      for delta in deltas:
	filename=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\
		str(delta)+'.out'
	folder=name+'.i_atom_'+str(atom)+'.i_coord_'+str(coord)+'.displ_'+\
		str(delta)       
	if mode=='0' or mode=='2':   # Put new geometry and control.in into folder
	  struc_new=copy.deepcopy(struc)
	  struc_new.atoms[atom].coord[coord]=\
	                              struc_new.atoms[atom].coord[coord]+delta
	  geoname='geometry.i_atom_'+str(atom)+'.i_coord_'+str(coord)+\
	          '.displ_'+str(delta)+'.in'
	  if not os.path.exists(folder): os.mkdir(folder)
	  new_geo=open(folder+'/geometry.in','w')
	  newline='#\n# temporary structure-file for finite-difference '+\
		  'calculation of forces\n'
	  newline=newline+'# displacement {0:8.4f} of \# atom '.format(delta)+\
			  '{0:5} direction {1:5}\n#\n'.format(atom,coord)
	  new_geo.writelines(newline+struc_new.to_str())
	  new_geo.close()
	  new_control=open(folder+'/control.in','w')
	  template_control=template_control.replace('relax_geometry',
	                                           '#relax_geometry')
	  new_control.write(template_control+'compute_forces .true. \n'+\
			    'final_forces_cleaned '+\
			    '.true. \n')
	  new_control.close()
	  os.chdir(folder)                                   # Change directoy
	  print 'Processing atom: '+str(atom+1)+'/'+str(n_atoms)+', coord.: '+\
				 str(coord+1)+'/'+str(3)+', delta: '+str(delta)
	  if run_aims:                           
	    os.system(AIMS_CALL+' > '+filename)# Run aims and pipe the output 
						#  into a file named 'filename'
	  if submit_script: replace_submission(template_job, name, counter, 
	                                       filename)
	  # os.system('qsub job.sh') # Mind the environment variables
	  os.chdir('..') 

	if mode=='1' or mode=='2':   # Read output 
	  forces_reached=False
	  atom_count=0
	  data=open(folder+'/'+filename)
	  for line in data.readlines():
	    if line.rfind('Dipole correction potential jump')!=-1:
	      dip_jump = float(split_line(line)[-2]) # Periodic
	    if line.rfind('| Total dipole moment [eAng]')!=-1:
	      dip_jump = float64(split_line(line)[-3:]) # Cluster
	    if forces_reached and atom_count<n_atoms: # Read Forces
	      struc.atoms[atom_count].force=float64(split_line(line)[2:])
	      atom_count=atom_count+1
	      if atom_count==n_atoms:
		forces_reached=False
	    if line.rfind('Total atomic forces')!=-1:
	      forces_reached=True
	  data.close()
	  if struc.periodic:
	    pass
      #dip[index,2]=dip[index,2]+dip_jump*coeff[deltas==delta]*c_zero
	  else:
	    dip[index,:]=dip[index,:]+dip_jump*coeff[deltas==delta]*c_zero
	  forces=array([])
	  for at_unconstrained in struc.atoms[struc.constrained==False]:
	    forces=append(forces,coeff[deltas==delta]*at_unconstrained.force)
	  hessian[index,:]=hessian[index,:]+forces*c_zero
	counter=counter+1
      index=index+1  
  if mode=='1' or mode=='2': # Calculate vibrations
    print 'Entering hessian diagonalization'
    print 'Number of atoms                = '+str(n_atoms)
    print 'Name of Hessian input file     = '+hessianname
    print 'Name of grad dipole input file = '+graddipolename
    print 'Name of Masses  input file     = '+atomicmasses
    print 'Name of XYZ output file        = '+xyzfile
    print 'Threshold for Matrix elements  = '+str(hessian_thresh)
    if (hessian_thresh < 0.0): print '     All matrix elements are taken'+\
				    ' into account by default\n'
    savetxt(hessianname,hessian)
    savetxt(graddipolename,dip)

    mass_mat=mass_vector[:,newaxis]*mass_vector[newaxis,:]
    hessian[abs(hessian)<hessian_thresh]=0.0
    hessian=hessian*mass_mat*hessian_factor
    hessian=(hessian+transpose(hessian))/2.
    # Diagonalize hessian (scipy)
    print 'Solving eigenvalue system for Hessian Matrix'
    freq, eig_vec = eig(hessian)
    print 'Done ... '
    eig_vec=eig_vec[:,argsort(freq)]
    freq=sort(sign(freq)*sqrt(abs(freq)))
    ZPE=hbar*(freq)/(2.0*eV)
    freq = (freq)/(200.*pi*c)
    
    
    grad_dipole = dip * grad_dipole_factor
    eig_vec = eig_vec*mass_vector[:,newaxis]*ones(len(mass_vector))[newaxis,:]
    infrared_intensity = sum(dot(transpose(grad_dipole),eig_vec)**2,axis=0)*\
                         ir_factor
    reduced_mass=sum(eig_vec**2,axis=0)
    norm = sqrt(reduced_mass)
    eig_vec = eig_vec/norm
    
    # The rest is output, xyz, IR,...
    print 'Results\n'
    print 'List of all frequencies found:'
    print 'Mode number      Frequency [cm^(-1)]   Zero point energy [eV]   '+\
          'IR-intensity [D^2/Ang^2]'
    for i in range(len(freq)):
      print '{0:11}{1:25.8f}{2:25.8f}{3:25.8f}'.format(i+1,freq[i],ZPE[i],
                                                       infrared_intensity[i])
    print '\n'
    print 'Summary of zero point energy for entire system:'
    print '| Cumulative ZPE               = {0:15.8f} eV'.format(sum(ZPE))
    print '| without first six eigenmodes = {0:15.8f} eV\n'.format(sum(ZPE)-
                                                                 sum(ZPE[:6]))
    print 'Stability checking - eigenvalues should all be positive for a '+\
           'stable structure. '
    print 'The six smallest frequencies should be (almost) zero:'
    string=''
    for zz in ZPE[:6]: string=string+'{0:25.8f}'.format(zz)
    print string
    print 'Compare this with the largest eigenvalue, '
    print '{0:25.8f}'.format(freq[-1])
    
    nums=arange(n_atoms)[struc.constrained==False]
    nums2=arange(n_atoms)[struc.constrained]
    newline=''
    newline_ir='[INT]\n'
    if options.molden:
      newline_molden='[Molden Format]\n[GEOMETRIES] XYZ\n'
      newline_molden=newline_molden+'{0:6}\n'.format(n_atoms)+'\n'
      for i_atoms in range(n_constrained):
	newline_molden=newline_molden+'{0:6}'.format(
	                                      struc.atoms[nums[i_atoms]].kind)
	for i_coord in range(3):
	  newline_molden=newline_molden+'{0:10.4f}'.format(
	                            struc.atoms[nums[i_atoms]].coord[i_coord])
	newline_molden=newline_molden+'\n'
      newline_molden=newline_molden+'[FREQ]\n'   
      for i in range(len(freq)):
	newline_molden=newline_molden+'{0:10.3f}\n'.format(freq[i])
      newline_molden=newline_molden+'[INT]\n' 
      for i in range(len(freq)):
	newline_molden=newline_molden+'{0:17.6e}\n'.format(
	                                                infrared_intensity[i])
      newline_molden=newline_molden+'[FR-COORD]\n'
      newline_molden=newline_molden+'{0:6}\n'.format(n_atoms)+'\n'
      for i_atoms in range(n_constrained):
	newline_molden=newline_molden+'{0:6}'.format(
	                                      struc.atoms[nums[i_atoms]].kind)
	for i_coord in range(3):
	  newline_molden=newline_molden+'{0:10.4f}'.format(
	                       struc.atoms[nums[i_atoms]].coord[i_coord]/bohr)
	newline_molden=newline_molden+'\n'
      newline_molden=newline_molden+'[FR-NORM-COORD]\n'
    
    for i in range(len(freq)):
      newline=newline+'{0:6}\n'.format(n_atoms)
      if freq[i]>0:
	newline=newline+'stable frequency at '
      elif freq[i]<0:
	newline=newline+'unstable frequency at '
	if options.distort and freq[i]<-50:
	  struc_new=copy.deepcopy(struc)
	  for i_atoms in range(n_constrained):
	    for i_coord in range(3):
	      struc_new.atoms[i_atoms].coord[i_coord]=\
	      struc_new.atoms[i_atoms].coord[i_coord]+\
		    eig_vec[(i_atoms)*3+i_coord,i]                        
	  geoname=name+'.distorted.vibration_'+str(i+1)+'.geometry.in'
	  new_geo=open(geoname,'w')
	  newline_geo='#\n# distorted structure-file for based on eigenmodes\n'
	  newline_geo=newline_geo+\
	          '# vibration {0:5} :{1:10.3f} 1/cm\n#\n'.format(i+1,freq[i])
	  new_geo.writelines(newline_geo+struc_new.to_str())
	  new_geo.close()
      elif freq[i]==0:
	newline=newline+'translation or rotation '
      newline=newline+'{0:10.3f} 1/cm IR int. is '.format(freq[i])
      newline=newline+'{0:10.4e} D^2/Ang^2; red. mass is '.format(
                                                        infrared_intensity[i])
      newline=newline+'{0:5.3f} a.m.u.; force const. is '.format(
                                                          1.0/reduced_mass[i])
      newline=newline+'{0:5.3f} mDyne/Ang.\n'.format(((freq[i]*(200*pi*c))**2)*
	      (1.0/reduced_mass[i])*at_u*1.e-2)
      if options.molden: newline_molden=newline_molden+\
                                               'vibration {0:6}\n'.format(i+1)
      for i_atoms in range(n_constrained):
	newline=newline+'{0:6}'.format(struc.atoms[nums[i_atoms]].kind)
	for i_coord in range(3):
	  newline=newline+'{0:10.4f}'.format(
	                            struc.atoms[nums[i_atoms]].coord[i_coord])
	for i_coord in range(3):
	  newline=newline+'{0:10.4f}'.format(eig_vec[(i_atoms)*3+i_coord,i])
	  if options.molden: newline_molden=newline_molden+'{0:10.4f}'.format(
	                     eig_vec[(i_atoms)*3+i_coord,i]/bohr)
	newline=newline+'\n'
	if options.molden: newline_molden=newline_molden+'\n'
      for i_atoms in range(n_atoms-n_constrained):
	newline=newline+'{0:6}'.format(struc.atoms[nums2[i_atoms]].kind)
	for i_coord in range(3):
	  newline=newline+'{0:10.4f}'.format(
	                           struc.atoms[nums2[i_atoms]].coord[i_coord])
	for i_coord in range(3):
	  newline=newline+'{0:10.4f}'.format(0.0)
	newline=newline+'\n'
      newline_ir=newline_ir+'{0:10.4e}\n'.format(infrared_intensity[i])
    xyz=open(xyzfile,'w')
    xyz.writelines(newline)
    xyz.close()
    ir=open(irname,'w')
    ir.writelines(newline_ir)
    ir.close()
    if options.molden:
      molden=open(moldenname,'w')
      molden.writelines(newline_molden)
      molden.close()
    
    if (mode=='1' or mode=='2') and options.plot:
      x=linspace(freq.min()-500,freq.max()+500,1000)
      z=zeros(len(x))
      for i in range(len(freq)):
	z[argmin(abs(x-freq[i]))]=infrared_intensity[i]
      window_len=150
      lorentzian=lorentz(pi,broadening,arange(250))#signal.gaussian(window_len,broadening)
      s=r_[z[window_len-1:0:-1],z,z[-1:-window_len:-1]]
      z_convolve=convolve(lorentzian/lorentzian.sum(),s,mode='same')[
	                                           window_len-1:-window_len+1]
      fig=figure(0)
      ax=fig.add_subplot(111)
      ax.plot(x,z_convolve,'r',lw=2)
      ax.set_xlim([freq.min()-500,freq.max()+500])
      ax.set_ylim([-0.01,ax.get_ylim()[1]])
      ax.set_yticks([])
      ax.set_xlabel('Frequency [1/cm]',size=20)
      ax.set_ylabel('Intensity [a.u.]',size=20)
      fig.savefig(name+'_IR_spectrum.pdf')
      
    print '\n Done. '
Example #43
0
'''
1d) Now we have all ingredients to compute the membrane potential excursion
(``U``) This calculation implies a convolution of the Gaussian with the
normalized PSP (see Diesmann 2002, eq. 6.9). In order to avoid an offset in
the convolution we need to add a pad of zeros on the left side of the
normalized PSP. Later on we want to compare our analytical results with the
simulation outcome. Therefore we need a time vector (``t_U``) with the correct
temporal resolution, that places the excursion of the potential at the correct
time.
'''

tmp = numpy.zeros(2 * len(psp_norm))
tmp[len(psp_norm) - 1:-1] += psp_norm
psp_norm = tmp
del tmp
U = a * psp_amp * pylab.convolve(gauss, psp_norm)
l = len(U)
t_U = (convolution_resolution * numpy.linspace(-l / 2., l / 2., l) +
       pulsetime + 1.)

'''
2. Simulation. In this section we simulate a network of multiple neurons.
All these neurons receive an individual pulse packet that is drawn from a
Gaussian distribution.
'''
'''
2.1 We reset the Kernel, define the simulation resolution and  set the
verbosity using `set_verbosity()` to suppress info messages.
'''

nest.ResetKernel()
Example #44
0
    def initial_fit_values(self, time, value, smoothing_samples=10,
                           integral_factor=.25, tau_fraction=2):
        """
        Estimate the initial fit values for the given sample data in
        (time, value).

        time : numpy.ndarray
            array of times at which the values are measured

        value : numpy.ndarray
            array of voltage values

        smoothing_samples : int
            width of the box filter used for the convolution

        integral_factor : float
            The time constants are estimated using the integral and
            the height of the given psp. integral_factor is the
            quotient of the maximum of a psp and the integral under
            it, which is 0.25 for tau_fraction = 2 for an ideal psp.

        tau_fraction : float
            The ratio tau_2 / tau_1, which is constant for this
            estimate.
        """
        mean_est_part = int(len(value) * .1)
        mean_estimate = p.mean(value[-mean_est_part:])
        noise_estimate = p.std(value[-mean_est_part:])

        smoothed_value = p.convolve(
            value - mean_estimate,
            p.ones(smoothing_samples) / float(smoothing_samples),
            "same") + mean_estimate

        integral = p.sum(smoothed_value - mean_estimate) * (time[1] - time[0])

        height_estimate = (max(smoothed_value) - mean_estimate)

        min_height = noise_estimate

        if height_estimate < min_height:
            height_estimate = min_height

        t1_est = integral / height_estimate * integral_factor

        # prevent t1 from being smaller than a time step
        t1_est_min = time[1] - time[0]
        if t1_est < t1_est_min:
            t1_est = t1_est_min
        t2_est = tau_fraction * t1_est

        tmax_est = time[p.argmax(smoothed_value)]
        tstart_est = tmax_est + p.log(t2_est / t1_est) \
            * (t1_est * t2_est) / (t1_est - t2_est)

        return dict(
            height=height_estimate,
            tau_1=t1_est,
            tau_2=t2_est,
            start=tstart_est,
            offset=mean_estimate)
Example #45
0
 def hammfilt(x, winsz):
     from pylab import convolve
     from numpy import hamming
     win = hamming(winsz)
     win /= sum(win)
     return convolve(x, win, 'same')
Example #46
0
    insert_params()

    mean = p.mean(psp_voltage, axis=0)
    std = p.std(psp_voltage, axis=0)
    p.figure()
    p.title("mean and standard deviation, ideal trigger")
    p.plot(time, mean, 'r-')
    p.fill_between(time, mean - std, mean + std, alpha=.3)
    p.xlabel("time / AU")
    p.ylabel("voltage / AU")
    insert_params()

    kernel = p.ones(sliding_average_len) / float(sliding_average_len)
    mean_max_index = p.argmax(mean)
    for i in range(len(psp_voltage)):
        smoothed = p.convolve(psp_voltage[i], kernel, "same")
        shift = mean_max_index - p.argmax(smoothed)
        psp_voltage[i] = p.roll(smoothed, shift)

    p.figure()
    p.title("mean and standard deviation, max trigger")
    mean_shifted = p.mean(psp_voltage, axis=0)
    std = p.std(psp_voltage, axis=0)
    p.plot(time, mean_shifted, 'r-')
    p.plot(time, mean, 'k--', alpha=.7)
    p.ylim(offset - height * .2, None)
    p.fill_between(time, mean - std, mean + std, alpha=.3)
    p.xlabel("time / AU")
    p.ylabel("voltage / AU")
    insert_params()