Esempio n. 1
1
 def IgorLoad(self,Source):
     from igor import binarywave,igorpy
     Waves={}
     Variables={}
     
     if Source[-3:] == 'ibw':
         Waves[binarywave.load(Source)['wave']['wave_header']['bname']]=binarywave.load(Source)['wave']['wData']
         Variables['SampleInterval']=1
     elif Source[-3:] == 'pxp':
         #tree=igorpy.load(Source).format()
         #print tree
         #print '#############'
         b=igorpy.load(Source)
         for i in b:
             if isinstance(i, igorpy.Wave):
                 Waves[str(i.name)]=i.data
             elif isinstance(i, igorpy.Variables):
                 Variables=i.uservar    
     elif Source[-3:] == 'txt':
         b=numpy.loadtxt(Source)
         Waves[Source.split("/")[-1].replace('.txt','').replace('.','_')]=b
         Variables=None 
     elif Source[-3:] == 'csv':
         b=numpy.loadtxt(Source)
         Waves[Source.split("/")[-1].replace('.txt','').replace('.','_')]=b
         Variables=None 
     elif Source[-3:] == 'wcp':
         print "not supported yet, but you can import an igor file" 
         b,c=self.read_block(Source)
         for i,j in enumerate(b):
             Waves[str(j[0])+str(i)]=numpy.array(j[1])
         for i in c:
             Variables[i]=c[i]  
     try:     
         return Waves,Variables
     except UnboundLocalError:
         msgBox = QtGui.QMessageBox()
         msgBox.setText(
         """
         <b>Filtype not Supported</b>
         <p>Only txt, ibw and pxp files are supported
         """)
         msgBox.exec_()
         return None, None
Esempio n. 2
0
def main(input_filename, output_filename):
    track = audio.LocalAudioFile(input_filename)
    sections, segments = track.analysis.sections, track.analysis.segments
    fsegs, i = [], 0
    for section in sections:
        while segments[i].start <= section.start:
            i = i + 1
        fsegs.append(segments[i - 1])
    ssmp, ssmt, p1, p2, t1, t2 = [], [], [], [], [], []
    for s1 in fsegs:
        p1, t1 = s1.pitches, s1.timbre
        for s2 in fsegs:
            p2, t2 = s2.pitches, s2.timbre
            distp, distt = 0, 0
            for j in range(len(p1)):
                distp = distp + (p2[j] - p1[j])**2
            for k in range(len(t1)):
                distt = distt + (t2[k] - t1[k])**2
            ssmp.append(distp**0.5)
            ssmt.append(distt**0.5)
    ssmp = numpy.array(ssmp).reshape(len(fsegs), len(fsegs))
    ssmt = numpy.array(ssmt).reshape(len(fsegs), len(fsegs))
    plt.imshow(ssmp, 'gray')
    plt.title('Section SSM (Pitches)')
    plt.colorbar()
    plt.savefig(output_filename + '_pitch')
    plt.show()
    plt.imshow(ssmt, 'gray')
    plt.title('Section SSM (Timbre)')
    plt.colorbar()
    plt.savefig(output_filename + '_timbre')
    plt.show()
Esempio n. 3
0
def plotData(fileName):
    xVals, yVals = getData(fileName)
    xVals = numpy.array(xVals)
    yVals = numpy.array(yVals)
    xVals = xVals * 9.81  #acc. due to gravity
    numpy.plot(xVals, yVals, 'bo', label='Measured displacements')
    labelPlot()
Esempio n. 4
0
def get_test_dataset():
    x_return_test = np.zeros((117, size, size, size))
    x_name_test = pd.read_csv("test.csv")['Id']
    filenum = 0
    for i in range(117):
        x_file_temp = os.path.join(x_test_path, x_name_test[i] + '.npz')
        x_voxel = np.array(np.load(x_file_temp)['voxel'])
        x_seg = np.array(np.load(x_file_temp)['seg'])
        x_temp = x_voxel * x_seg * 0.8 + x_voxel * 0.2
        s = x_seg * x_voxel
        sign = np.array(np.nonzero(s))
        min1, low1, len1 = get_rec(sign, 0)
        min2, low2, len2 = get_rec(sign, 1)
        min3, low3, len3 = get_rec(sign, 2)
        i_temp = 0
        for i in range(low1, low1+len1):
            j_temp = 0
            for j in range(low2, low2+len2):
                k_temp = 0
                for k in range(low3, low3+len3):
                    x_return_test[filenum, i, j, k] = x_temp[min1 + i_temp, min2 + j_temp, min3 + k_temp]
                    k_temp += 1
                j_temp += 1
            i_temp += 1
        filenum += 1
    return  x_return_test
Esempio n. 5
0
def plotLIE(trainSet):
    
    x=np.array([ i['Gexp'] for i in trainSet ])
    y=np.array([ i['Gcalc'] for i in trainSet ])

    minAxi=min([x.min(), y.min()])
    maxAxi=max([x.max(), y.max()])
    minAxi= 5*((minAxi//5))
    maxAxi= 5*((maxAxi//5)+1)
    
    fig = plt.figure()       
    ax = fig.add_subplot(111, aspect='equal')
    plt.setp(ax.get_xticklabels(), rotation='horizontal', fontsize=20)
    plt.setp(ax.get_yticklabels(), rotation='horizontal', fontsize=20)

    plt.xlabel('$\Delta$G$_{obs}$', fontsize=20, color='black')
    plt.ylabel(r'$\Delta$G$_{calc}$', fontsize=20, color='black')
    plt.axis([minAxi,maxAxi, minAxi, maxAxi])
    plt.plot(x,y, 'ro')
    plt.plot([minAxi,maxAxi],[minAxi,maxAxi],color='black', linestyle='-')
    plt.plot([minAxi,maxAxi-5],[minAxi+5,maxAxi],color='black', linestyle='-.')
    plt.plot([minAxi+5,maxAxi],[minAxi,maxAxi-5],color='black', linestyle='-.')

    for i,(x,y) in enumerate(zip(x,y)):
        ax.annotate(i+1,xy=(x,y),xytext=(5,0),textcoords='offset points')
    
    plt.tight_layout()
    imgdata = BytesIO()
   
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)  # rewind the data

    return imgdata
Esempio n. 6
0
def load_traindata():
    x_return = np.zeros((495, size, size, size))
    x_name = pd.read_csv("train_val.csv")[
        'Id']  # 此处[' ']内填写的是train_val.csv内的第一列表头
    count_file = 0
    for i in range(len(traindata_list)):
        x_file_temp = os.path.join(traindata_path, x_name[i] + '.npz')
        x_voxel = np.array(np.load(x_file_temp)['voxel'])
        x_mask = np.array(np.load(x_file_temp)['seg'])
        x_temp = x_voxel * x_mask * 0.8 + x_voxel * 0.2

        list_xx = x_mask * x_voxel
        list_xx_nz = np.array(np.nonzero(list_xx))
        coor1min = list_xx_nz[0, :].min()
        coor1max = list_xx_nz[0, :].max()
        coor1len = coor1max - coor1min + 1
        coor1bigger = coor1len - size
        if coor1bigger > 0:
            coor1min += coor1bigger // 2
            coor1max -= coor1bigger - coor1bigger // 2
            coor1len = size
        coor1low = (size // 2) - (coor1len // 2)
        coor1high = coor1low + coor1len
        coor2min = list_xx_nz[1, :].min()
        coor2max = list_xx_nz[1, :].max()
        coor2len = coor2max - coor2min + 1
        coor2bigger = coor2len - size
        if coor2bigger > 0:
            coor2min += coor2bigger // 2
            coor2max -= coor2bigger - coor2bigger // 2
            coor2len = size
        coor2low = (size // 2) - (coor2len // 2)
        coor2high = coor2low + coor2len
        coor3min = list_xx_nz[2, :].min()
        coor3max = list_xx_nz[2, :].max()
        coor3len = coor3max - coor3min + 1
        coor3bigger = coor3len - size
        if coor3bigger > 0:
            coor1min += coor3bigger // 2
            coor3max -= coor3bigger - coor3bigger // 2
            coor3len = size
        coor3low = (size // 2) - (coor3len // 2)
        coor3high = coor3low + coor3len
        coorlist1 = 0
        for coor1 in range(coor1low, coor1high):
            coorlist2 = 0
            for coor2 in range(coor2low, coor2high):
                coorlist3 = 0
                for coor3 in range(coor3low, coor3high):
                    x_return[count_file, coor1, coor2,
                             coor3] = x_temp[coor1min + coorlist1,
                                             coor2min + coorlist2,
                                             coor3min + coorlist3]
                    coorlist3 += 1
                coorlist2 += 1
            coorlist1 += 1
        count_file += 1
    return x_return
Esempio n. 7
0
def load_testdata():
    x_return = np.zeros((117, size, size, size))
    x_name = pd.read_csv("sampleSubmission.csv")[
        'Id']  # 此处[' ']内填写的是sampleSubmission.csv内的第一列表头
    filenum = 0
    for i in range(117):
        x_file_temp = os.path.join(x_test_path, x_name[i] + '.npz')
        x_voxel = np.array(np.load(x_file_temp)['voxel'])
        x_mask = np.array(np.load(x_file_temp)['seg'])
        x_temp = x_voxel * x_mask * 0.8 + x_voxel * 0.2
        list_xx_test = x_voxel * x_mask
        list_xx_nz_test = np.array(np.nonzero(list_xx_test))
        coor1min = list_xx_nz_test[0, :].min()
        coor1max = list_xx_nz_test[0, :].max()
        coor1len = coor1max - coor1min + 1
        coor1bigger = coor1len - size
        if coor1bigger > 0:
            coor1min += coor1bigger // 2
            coor1max -= coor1bigger - coor1bigger // 2
            coor1len = size
        coor1low = (size // 2) - (coor1len // 2)
        coor1high = coor1low + coor1len
        coor2min = list_xx_nz_test[1, :].min()
        coor2max = list_xx_nz_test[1, :].max()
        coor2len = coor2max - coor2min + 1
        coor2bigger = coor2len - size
        if coor2bigger > 0:
            coor2min += coor2bigger // 2
            coor2max -= coor2bigger - coor2bigger // 2
            coor2len = size
        coor2low = (size // 2) - (coor2len // 2)
        coor2high = coor2low + coor2len
        coor3min = list_xx_nz_test[2, :].min()
        coor3max = list_xx_nz_test[2, :].max()
        coor3len = coor3max - coor3min + 1
        coor3bigger = coor3len - size
        if coor3bigger > 0:
            coor1min += coor3bigger // 2
            coor3max -= coor3bigger - coor3bigger // 2
            coor3len = size
        coor3low = (size // 2) - (coor3len // 2)
        coor3high = coor3low + coor3len
        # print(file, coor1low, coor1high, coor2low, coor2high, coor3low, coor3high)
        coorlist1 = 0
        for coor1 in range(coor1low, coor1high):
            coorlist2 = 0
            for coor2 in range(coor2low, coor2high):
                coorlist3 = 0
                for coor3 in range(coor3low, coor3high):
                    x_return[filenum, coor1, coor2,
                             coor3] = x_temp[coor1min + coorlist1,
                                             coor2min + coorlist2,
                                             coor3min + coorlist3]
                    coorlist3 += 1
                coorlist2 += 1
            coorlist1 += 1
        filenum += 1
    return x_return
Esempio n. 8
0
def fitData1(fileName):
    xVals, yVals = getData(fileName)
    xVals = numpy.array(xVals)
    yVals = numpy.array(yVals)
    xVals = xVals * 9.81  #get force
    numpy.plot(xVals, yVals, 'bo', label='Measured points')
    labelPlot()
    model = numpy.polyfit(xVals, yVals, 1)
    estYVals = numpy.polyval(model, xVals)
    numpy.plot(xVals,
               estYVals,
               'r',
               label='Linear fit, k = ' + str(round(1 / model[0], 5)))
    numpy.legend(loc='best')
Esempio n. 9
0
def fitData(fileName):
    xVals, yVals = getData(fileName)
    xVals = numpy.array(xVals)
    yVals = numpy.array(yVals)
    xVals = xVals * 9.81  #get force
    numpy.plot(xVals, yVals, 'bo', label='Measured points')
    labelPlot()
    a, b = numpy.polyfit(xVals, yVals, 1)
    estYVals = a * numpy.array(xVals) + b
    print('a =', a, 'b =', b)
    numpy.plot(xVals,
               estYVals,
               'r',
               label='Linear fit, k = ' + str(round(1 / a, 5)))
    numpy.legend(loc='best')
Esempio n. 10
0
    def many(self, inputimages, clobber=True, depth=-1, limit=25, single=True, **options):
        '''Display a bunch of images in ds9, each in its own frame.'''
        images = np.array(inputimages)
        if clobber:
          self.window.set("frame delete all")

        if single:
            self.window.set('single')
        else:
            self.window.set('tile')

        # is the "cube" really just a 1D or 2D image?
        if len(images.shape) <= 2:
          self.one(images, clobber=clobber)
          return

        # loop through the "depth" axis, which is by default the final one
        if len(images.shape) == 3:

            # only display up to a certain number of images
            if images.shape[-1] > limit:
                self.speak("going to display only {0:.0f} images, for impatience's sake".format(limit))

            # display all the images
            for i in range(np.minimum(images.shape[depth], limit)):
                self.replace(images.take(i,axis=depth).astype(np.float), i)
                self.applyOptionsToFrame(**options)
            return

        self.speak('Uh-oh! Image array seems to have a dimension other than 1, 2, or 3!')
Esempio n. 11
0
    def geometricMeanFilter(self, img):

        img = img.convert('RGB')
        px = img.load()
        width, height = img.size
        result = np.array(img)

        kernel_dim = 1  #(*2+1)

        # kernel 3x3
        for i in range(kernel_dim, height - kernel_dim):
            for j in range(kernel_dim, width - kernel_dim):
                prod_red, prod_green, prod_blue = (1, 1, 1)
                for n in range(i - kernel_dim, i + kernel_dim + 1):
                    for m in range(j - kernel_dim, j + kernel_dim + 1):
                        r, g, b = px[m, n]
                        prod_red *= r
                        prod_green *= g
                        prod_blue *= b

                div = (kernel_dim * 2 + 1)**2
                result[i, j] = tuple([
                    prod_red**(1 / div), prod_green**(1 / div),
                    prod_blue**(1 / div)
                ])

        img = Image.fromarray(result)
        return img
Esempio n. 12
0
    def harmonicMeanFilter(self, img):

        img = img.convert('RGB')
        px = img.load()
        width, height = img.size
        result = np.array(img)

        kernel_dim = 1  # (*2+1)

        # kernel 3x3
        for i in range(kernel_dim, height - kernel_dim):
            for j in range(kernel_dim, width - kernel_dim):
                sum_red, sum_green, sum_blue = (0, 0, 0)
                for n in range(i - kernel_dim, i + kernel_dim + 1):
                    for m in range(j - kernel_dim, j + kernel_dim + 1):
                        r, g, b = px[m, n]
                        if r == 0: r = 1
                        if g == 0: g = 1
                        if b == 0: b = 1
                        sum_red += 1 / r
                        sum_green += 1 / g
                        sum_blue += 1 / b

                num = (kernel_dim * 2 + 1)**2
                result[i, j] = tuple([
                    int(num / sum_red),
                    int(num / sum_green),
                    int(num / sum_blue)
                ])

        img = Image.fromarray(result)
        return img
Esempio n. 13
0
    def contrastFilter(self, index, img):

        img = img.convert('RGB')
        open_cv_image = np.array(img)

        # Select the three different channels
        red = open_cv_image[:, :, 0]
        green = open_cv_image[:, :, 1]
        blue = open_cv_image[:, :, 2]

        # factor used to apply the contrast function
        factor = (259.0 * (index + 255.0)) / (255.0 * (259.0 - index))

        # Calculate the new value for each pixel in the channel
        red = factor * (red - 128.0) + 128.0
        green = factor * (green - 128.0) + 128.0
        blue = factor * (blue - 128.0) + 128.0

        # Ensure that the value of pixels not go out of RGB range
        red[red >= 255] = 255
        red[red <= 0] = 0
        green[green >= 255] = 255
        green[green <= 0] = 0
        blue[blue >= 255] = 255
        blue[blue <= 0] = 0

        # Set the matrix image with the new arrays
        open_cv_image[:, :, 0] = red
        open_cv_image[:, :, 1] = green
        open_cv_image[:, :, 2] = blue

        # Convert the matrix to a PIL image that will show in the label
        img = Image.fromarray(open_cv_image)
        return img
Esempio n. 14
0
    def arithmeticMeanFilter(self, img):

        img = img.convert('RGB')
        im = np.array(img)
        red = im[:, :, 0]
        green = im[:, :, 1]
        blue = im[:, :, 2]
        w = 2

        for i in range(w, im.shape[0] - w):
            for j in range(w, im.shape[1] - w):
                block_red = red[i - w:i + w + 1, j - w:j + w + 1]
                m_r = np.mean(block_red, dtype=np.float32)
                red[i][j] = int(m_r)

                block_green = green[i - w:i + w + 1, j - w:j + w + 1]
                m_g = np.mean(block_green, dtype=np.float32)
                green[i][j] = int(m_g)

                block_blue = blue[i - w:i + w + 1, j - w:j + w + 1]
                m_r = np.mean(block_blue, dtype=np.float32)
                blue[i][j] = int(m_r)

        im[:, :, 0] = red
        im[:, :, 1] = green
        im[:, :, 2] = blue
        img = Image.fromarray(im)
        img = img.convert('RGB')
        return img
Esempio n. 15
0
    def medianFilter(self, img):

        img = img.convert('RGB')
        im = np.array(img)

        ''' SLOW OLD IMPLEMENTATION
        red = im[:, :, 0]
        green = im[:, :, 1]
        blue = im[:, :, 2]
        w = 1

        for i in range(w, im.shape[0] - w):
            for j in range(w, im.shape[1] - w):
                block_red = red[i - w:i + w + 1, j - w:j + w + 1]
                m_r = np.median(block_red)
                red[i][j] = int(m_r)

                block_green = green[i - w:i + w + 1, j - w:j + w + 1]
                m_g = np.median(block_green)
                green[i][j] = int(m_g)

                block_blue = blue[i - w:i + w + 1, j - w:j + w + 1]
                m_r = np.median(block_blue)
                blue[i][j] = int(m_r)

        im[:, :, 0] = red
        im[:, :, 1] = green
        im[:, :, 2] = blue
        '''
        im = cv2.medianBlur(im, 11)
        img = Image.fromarray(im)
        img = img.convert('RGB')
        return img
Esempio n. 16
0
    def drogEdgeDetectorFilter(self, img, ret_grad=False, pillow=True):

        if pillow:
            img = img.convert('L')
        open_cv_image = np.array(img)
        width, height = 0, 0
        if not pillow:
            height, width = img.shape

        else:
            width, height = img.size

        cv2.GaussianBlur(open_cv_image, (15, 15), 0)

        # Create sobel x and y matrix
        sobel_x = np.array([[-1, 0, 1],
                            [-2, 0, 2],
                            [-1, 0, 1]])

        sobel_y = np.array([[-1, -2, -1],
                            [0, 0, 0],
                            [1, 2, 1]])

        kernel1 = np.zeros(open_cv_image.shape)
        kernel1[:sobel_x.shape[0], :sobel_x.shape[1]] = sobel_x
        kernel1 = np.fft.fft2(kernel1)

        kernel2 = np.zeros(open_cv_image.shape)
        kernel2[:sobel_y.shape[0], :sobel_y.shape[1]] = sobel_y
        kernel2 = np.fft.fft2(kernel2)


        im = np.array(open_cv_image)
        fim = np.fft.fft2(im)
        Gx = np.real(np.fft.ifft2(kernel1 * fim)).astype(float)
        Gy = np.real(np.fft.ifft2(kernel2 * fim)).astype(float)

        open_cv_image = abs(Gx/4) + abs(Gy/4)
        img = Image.fromarray(open_cv_image)
        img = img.convert('L')
        if ret_grad:
            return Gx, Gy
        return img
Esempio n. 17
0
    def scaling(self, img, index, resize=False):

        img = img.convert('RGB')
        im = np.array(img)
        red = im[:, :, 0]
        green = im[:, :, 1]
        blue = im[:, :, 2]

        width, height = img.size

        # Calculate the second index value to maintain the aspect ratio
        aspect_ratio = width / height
        index1 = index

        index2 = int((index1 + width - (aspect_ratio * height)) / aspect_ratio)

        new_img = img.resize((width - index1, height - index2))
        new_img = np.array(new_img)

        new_red = np.zeros((height - index2, width - index1))
        new_green = np.zeros((height - index2, width - index1))
        new_blue = np.zeros((height - index2, width - index1))

        if index > 0:
            new_red[:, :] = red[0:height - index2, 0:width - index1]
            new_green[:, :] = green[0:height - index2, 0:width - index1]
            new_blue[:, :] = blue[0:height - index2, 0:width - index1]
        else:
            new_red[0:height, 0:width] = red[:, :]
            new_green[0:height, 0:width] = green[:, :]
            new_blue[0:height, 0:width] = blue[:, :]

        new_img[:, :, 0] = new_red
        new_img[:, :, 1] = new_green
        new_img[:, :, 2] = new_blue
        if not resize:
            img = Image.fromarray(new_img)
            img = img.resize((width, height))

        else:
            img = img.resize((width + index1, height + index2))

        return img
Esempio n. 18
0
    def statisticalRegionMerging(self, img, n_sample):

        img = img.convert('RGB')
        image = np.array(img)

        srm = SRM(image, n_sample)
        segmented = srm.run()
        segmented = np.array(segmented).astype(int)

        red = segmented[:, :, 0]
        green = segmented[:, :, 1]
        blue = segmented[:, :, 2]

        image[:, :, 0] = red
        image[:, :, 1] = green
        image[:, :, 2] = blue

        img = Image.fromarray(image)
        return img
Esempio n. 19
0
def getDiffs(population, sampleSizes):
    popStd = numpy.std(population)
    diffsFracs = []
    for sampleSize in sampleSizes:
        diffs = []
        for t in range(100):
            sample = random.sample(population, sampleSize)
            diffs.append(abs(popStd - numpy.std(sample)))
        diffMean = sum(diffs)/len(diffs)
        diffsFracs.append(diffMean/popStd)
    return numpy.array(diffsFracs)*100
Esempio n. 20
0
def fitData(fileName):
    xVals, yVals = getData(fileName)
    xVals = numpy.array(xVals)
    yVals = numpy.array(yVals)
    xVals = xVals*9.81 #get force
    numpy.plot(xVals, yVals, 'bo',
               label = 'Measured points')                 
    model = numpy.polyfit(xVals, yVals, 1)
    xVals = xVals + [2]
    yVals = yVals + []
    estYVals = numpy.polyval(model, xVals)
    numpy.plot(xVals, estYVals, 'r',
               label = 'Linear fit, r**2 = '
               + str(round(rSquared(yVals, estYVals), 5)))                
    model = numpy.polyfit(xVals, yVals, 2)
    estYVals = numpy.polyval(model, xVals)
    numpy.plot(xVals, estYVals, 'g--',
               label = 'Quadratic fit, r**2 = '
               + str(round(rSquared(yVals, estYVals), 5)))
    numpy.title('A Linear Spring')
    labelPlot()
    numpy.legend(loc = 'best')
Esempio n. 21
0
def fftdc(compressed):
    file_for_decompression = compressed

    col_idft = np.transpose(file_for_decompression)
    col_idft = [np.fft.ifft(row) for row in col_idft]
    row_idft = np.transpose(col_idft)
    row_idft = [np.fft.ifft(row) for row in row_idft]

    # file_for_decompression = np.array([shuffle(row) for row in row_idft])
    # file_for_decompression = np.transpose(file_for_decompression)
    # file_for_decompression = np.array([shuffle(row) for row in file_for_decompression])
    # file_for_decompression = np.transpose(file_for_decompression)
    return np.array(row_idft)
Esempio n. 22
0
def plot_RMSD_histo(plotFilePath, plotFilePath2, dots, plotTitle):
    rmsd = np.array(dots)[:, 1]
    xlabel = None
    ylabel = None

    meanX, stdX = HGM.helpers.compute_list_statistics(rmsd)
    minX = min(rmsd)
    maxX = max(rmsd)
    title   = plotTitle+\
            "range:[{3:.2f},{4:.2f}]\n size:{0:d} E{1:.2f}: s{2:.2f}:".format(len(rmsd),meanX,stdX,minX,maxX)
    HGM.helpersPlot.plot_histogram_with_margins(plotFilePath2, rmsd, nbBins,
                                                xlabel, ylabel, title)
    HGM.helpersPlot.plot_histogram(plotFilePath, rmsd, nbBins, xlabel, ylabel,
                                   title)
Esempio n. 23
0
def shuffle(row):
    N = math.ceil(math.log2(len(row)))
    new_row = np.array([0] * 2**N)
    for i in range(len(row)):
        formated = format(i, '0' + str(N) + 'b')
        reversed_string = [
            formated[len(formated) - 1 - k] for k in range(len(formated))
        ]
        formated = ''
        for j in reversed_string:
            formated += j
        formated = int(formated, 2)
        new_row[formated] = int(row[i])
    return new_row
Esempio n. 24
0
    def saturationFilter(self, index, img):

        img = img.convert('RGB')
        open_cv_image = np.array(img)

        # Same logic of luminance filter
        hsv = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2HSV).astype("float32")
        s = hsv[:, :, 1]
        s += index
        s[s >= 255] = 255
        s[s <= 0] = 0

        hsv[:, :, 1] = s
        img = cv2.cvtColor(hsv.astype("uint8"), cv2.COLOR_HSV2RGB)
        img = Image.fromarray(img)
        return img
def graph_plotting(dict_of_data, A, B, X_title, Y_title):
    x = dict_of_data.get('x')
    dx = dict_of_data.get('dx')
    y = dict_of_data.get('y')
    dy = dict_of_data.get('dy')

    x_array = num.array(x)
    lin_fun = A * x_array + B

    #graph plotting with errorbars
    pyplot.plot(x_array, lin_fun, 'r')
    pyplot.errorbar(x, y, dx, dy, fmt=none, ecolor='b')
    pyplot.xlabel(x_title)
    pyplot.ylabel(y_title)
    pyplot.show()
    pyplot.savefig('linear_fit.svg')
Esempio n. 26
0
    def luminanceFilter(self, index, img):

        img = img.convert('RGB')
        open_cv_image = np.array(img)

        # Change color space to use the Value of HSV to manipulate the luminance
        # the rest of code is similar to other color filter
        hsv = cv2.cvtColor(open_cv_image, cv2.COLOR_RGB2HSV).astype("float32")
        v = hsv[:, :, 2]
        v += index
        v[v >= 255] = 255
        v[v <= 0] = 0

        hsv[:, :, 2] = v
        img = cv2.cvtColor(hsv.astype("uint8"), cv2.COLOR_HSV2RGB)
        img = Image.fromarray(img)
        return img
Esempio n. 27
0
    def translate(self, img, x, y):
        img = img.convert('RGB')
        open_cv_image = np.array(img)

        red = open_cv_image[:, :, 0]
        green = open_cv_image[:, :, 1]
        blue = open_cv_image[:, :, 2]

        x = -x
        red = np.roll(red, x, axis=0)
        if x >= 0: red[:x, :] = 0
        else: red[img.height + x:, :] = 0

        red = np.roll(red, y, axis=1)
        if y >= 0: red[:, :y] = 0
        else: red[:, img.width + y:] = 0

        green = np.roll(green, x, axis=0)
        if x >= 0: green[:x, :] = 0
        else: green[img.height + x:, :] = 0

        green = np.roll(green, y, axis=1)
        if y >= 0: green[:, :y] = 0
        else: green[:, img.width + y:] = 0

        blue = np.roll(blue, x, axis=0)
        if x >= 0: blue[:x, :] = 0
        else: blue[img.height + x:, :] = 0

        blue = np.roll(blue, y, axis=1)
        if y >= 0: blue[:, :y] = 0
        else: blue[:, img.width + y:] = 0

        open_cv_image[:, :, 0] = red
        open_cv_image[:, :, 1] = green
        open_cv_image[:, :, 2] = blue

        open_cv_image = abs(open_cv_image)
        img = Image.fromarray(open_cv_image)
        return img
Esempio n. 28
0
    def arithmeticMeanFilter(self, img):

        img = img.convert('RGB')
        im = np.array(img)

        ''' SLOW OLD IMPLEMENTATION
        red = im[:, :, 0]
        green = im[:, :, 1]
        blue = im[:, :, 2]
        w = 2

        for i in range(w, im.shape[0] - w):
            for j in range(w, im.shape[1] - w):
                block_red = red[i - w:i + w + 1, j - w:j + w + 1]
                m_r = np.mean(block_red, dtype=np.float32)
                red[i][j] = int(m_r)

                block_green = green[i - w:i + w + 1, j - w:j + w + 1]
                m_g = np.mean(block_green, dtype=np.float32)
                green[i][j] = int(m_g)

                block_blue = blue[i - w:i + w + 1, j - w:j + w + 1]
                m_r = np.mean(block_blue, dtype=np.float32)
                blue[i][j] = int(m_r)

        im[:, :, 0] = red
        im[:, :, 1] = green
        im[:, :, 2] = blue
        '''

        kernel = np.ones((11, 11), np.float32) / 121
        im = cv2.filter2D(im, -1, kernel)

        img = Image.fromarray(im)
        img = img.convert('RGB')
        return img
Esempio n. 29
0
def showErrorBars(population, sizes, numTrials):
    xVals = []
    sizeMeans, sizeSDs = [], []
    for sampleSize in sizes:
        xVals.append(sampleSize)
        trialMeans = []
        for t in range(numTrials):
            sample = random.sample(population, sampleSize)
            popMean, sampleMean, popSD, sampleSD =\
               getMeansAndSDs(population, sample)
            trialMeans.append(sampleMean)
        sizeMeans.append(sum(trialMeans)/len(trialMeans))
        sizeSDs.append(numpy.std(trialMeans))
    print(sizeSDs)
    numpy.errorbar(xVals, sizeMeans,
                   yerr = 1.96*numpy.array(sizeSDs), fmt = 'o',
                   label = '95% Confidence Interval')
    numpy.title('Mean Temperature ('
                + str(numTrials) + ' trials)')
    numpy.xlabel('Sample Size')
    numpy.ylabel('Mean')
    numpy.axhline(y = popMean, color ='r', label = 'Population Mean')
    numpy.xlim(0, sizes[-1] + 10)
    numpy.legend()
Esempio n. 30
0
    def Update_Navigate(self):
        #Resetting Sequence
        try:
            RecordA0=Navigate.ArrayList[0]
        except IndexError:
            msgBox = QtGui.QMessageBox()
            msgBox.setText(
            """
            <b>No Data</b>
            <p>No data match your filter paramterers
            Caution, Filtering is case-sensitive
            """)
            msgBox.exec_()  
            return
        Requete.url=None
        Requete.Current_Signal=RecordA0
        
        
        #if Navigate.VarList.has_key("sampling_rate") == True:
        #    Navigate.VarList["sampling_rate"]=Navigate.VarList["sampling_rate"]*1000.
        #    Navigate.VarList["SampleInterval"]=Navigate.VarList["sampling_rate"]
        try:    
            if self.FileType == "Neuromatic":#Navigate.VarList.has_key("SampleInterval") == True:
                Requete.timescale=(Navigate.VarList["SampleInterval"])*numpy.array(range(len(RecordA0[0])))
                Requete.Analogsignal_sampling_rate=list([1000./Navigate.VarList["SampleInterval"]]*len(Navigate.ArrayList))
            elif self.FileType=="Synaptics":#Navigate.VarList.has_key("sampling_rate") == True:
                Requete.timescale=(1./Navigate.VarList["sampling_rate"])*numpy.array(range(len(RecordA0[0])))
                Requete.Analogsignal_sampling_rate=list([1000.*Navigate.VarList["sampling_rate"]]*len(Navigate.ArrayList))
            elif self.FileType=="WinWCP":#Navigate.VarList.has_key("sampling_rate") == True:
                Requete.timescale=(1000./Navigate.VarList["sampling_rate"])*numpy.array(range(len(RecordA0[0])))
                Requete.Analogsignal_sampling_rate=list([Navigate.VarList["sampling_rate"]]*len(Navigate.ArrayList))
        except KeyError:
            val, ok = QtGui.QInputDialog.getText(self,'Sampling rate not found', 
                'Please enter sampling interval (ms per point)')
            val=float(val)                
            Navigate.VarList["SampleInterval"] = val
            Requete.timescale = val*numpy.array(range(len(RecordA0[0])))
            Requete.Analogsignal_sampling_rate=list([len(Requete.Current_Signal[0])]*len(Navigate.ArrayList)) 
            msgBox = QtGui.QMessageBox()
            msgBox.setText(
            """
            <b>NeuroMatic Import Error</b>
            <p>Sampling rate not found, and set to %s
            """ %val)
            msgBox.exec_()        
        #else:
            # TODO : Add manual SR input
            #print "filtype not identified, Auto sampling rate ignored"
            #Navigate.VarList["SampleInterval"] = 1.
            #Requete.timescale = 1.*numpy.array(range(len(RecordA0)))
            #Requete.Analogsignal_sampling_rate=list([len(Requete.Current_Signal)]*len(Navigate.ArrayList))

        
        Requete.Shortest_Sweep_Length=(Requete.timescale[-1]+(Requete.timescale[1]-Requete.timescale[0]))/1000. #in s
        if Navigate.VarList.has_key("sampling_rate") == True:
            Navigate.Points_by_ms = Navigate.VarList["sampling_rate"]
            Requete.BypassedSamplingRate=Navigate.VarList["sampling_rate"]
            Navigate.VarList["SampleInterval"]=1000./Navigate.VarList["sampling_rate"]
        else:
            Navigate.Points_by_ms = 1000./ Navigate.VarList["SampleInterval"]    
            Requete.BypassedSamplingRate=1000./Navigate.VarList["SampleInterval"]
            Navigate.VarList["sampling_rate"]=1000/Navigate.VarList["SampleInterval"]
        
        Requete.Current_Sweep_Number=0
        Requete.Block_ids=list([[0]*Requete.NumberofChannels]*len(Navigate.ArrayList))
        Requete.Block_date=list([[None]*Requete.NumberofChannels]*len(Navigate.ArrayList))
        Requete.Segment_ids=[[x]*Requete.NumberofChannels for x in range(len(Navigate.ArrayList))]
        Requete.Analogsignal_ids=[[x]*Requete.NumberofChannels for x in range(len(Navigate.ArrayList))]#range(len(Navigate.ArrayList))
        Requete.Analogsignal_name=list([None]*len(Navigate.ArrayList))
        Requete.tag={}
        
        new=[]
        for i in range(len(Requete.Analogsignal_ids)):
            new.append([0]*int(Requete.NumberofChannels))            
        Requete.tag["Selection"]=new
        for i in range(len(Requete.Analogsignal_ids)):
            for j in range(Requete.NumberofChannels):
                Requete.tag["Selection"][i][j]=0
        
        #Requete.tag["Selection"]=[[0]*int(Requete.NumberofChannels)]*len(Requete.Analogsignal_ids)
        
        Requete.Analogsignal_channel=list([range(Requete.NumberofChannels)]*len(Navigate.ArrayList))
        Requete.Block_fileOrigin=list([None]*len(Navigate.ArrayList))
        Requete.Block_Info=list([[None]*Requete.NumberofChannels]*len(Navigate.ArrayList))
        if Navigate.VarList.has_key("SamplesPerWave") == True:
            Requete.Analogsignal_signal_shape=list([int(Navigate.VarList["SamplesPerWave"])]*len(Navigate.ArrayList))
        else:
            Requete.Analogsignal_signal_shape=list([int(len(Requete.Current_Signal)*Requete.Shortest_Sweep_Length)]*len(Navigate.ArrayList))
        
        Main.slider.setRange(0, len(Requete.Analogsignal_ids)-1) #definit le range du slider sweepnb
        Requete.Spiketrain_ids=list([None]*len(Navigate.ArrayList))
        Requete.Spiketrain_neuron_name=list([None]*len(Navigate.ArrayList))
        Requete.Spiketrain_t_start=list([None]*len(Navigate.ArrayList))
        Requete.Spiketrain_Neuid=list([None]*len(Navigate.ArrayList))  

        for i in [Mapping.X_Start_Field,
                  Mapping.X_End_Field,
                  Mapping.X_Step_Field,
                  Mapping.Y_Start_Field,
                  Mapping.Y_End_Field,
                  Mapping.Y_Step_Field]:
                i.setEnabled(True)
        Mapping.Scanning_Direction_Mode = None
        
        
        Main.To.setText(str(len(Requete.Analogsignal_ids)-1))
        Navigate.Check_From_To()
        Main.MainFigure.canvas.fig.clf()
        Navigate.Display_First_Trace()
Esempio n. 31
0
    def Update_Graph(self,sender):
        sender=str(sender)
        
        if 'Button_Min' in sender:
            value=eval(sender).text()   
            pos=int(sender[-1])
            try:
                self.MinGuess[pos]=float(value)
            except ValueError:
                self.MinGuess[pos]=None
                pass
            
        if 'Button_Max' in sender:
            value=eval(sender).text()   
            pos=int(sender[-1])
            try:
                self.MaxGuess[pos]=float(value)
            except ValueError:
                self.MaxGuess[pos]=None
                pass   

        elif 'Button_Guess' in sender:
            value=eval(sender).text()   
            pos=int(sender[-1])
            try:
                self.param_list[pos]=float(value)
            except ValueError:
                self.param_list[pos]=None
                pass

        elif 'Display_' in sender:
            value=eval(sender).text()   
            pos=int(sender[-1])
            try:
                self.display_range[pos]=float(value)
            except ValueError:
                self.display_range[pos]=1.0
                pass  
            
        elif 'Range' in sender:
            value=eval(sender).text()   
            pos=int(sender[-1])
            try:
                self.range[pos]=float(value)
            except ValueError:
                self.range[pos]=1.0
                pass     
        else:
            pass
            
        #fitting function is set
        function=eval('self.'+str(self.List_of_Functions.currentText()).lower())
        #Graph is cleared
        self.Fit_Example.canvas.axes.clear()

        timescale=1.
        
        if str(self.Data_Wave.currentText()) != 'None':
            y=numpy.array(eval(str(self.Data_Wave.currentText())))
            if str(self.Data_Wave_Axes.currentText()) == 'None':
                x=numpy.arange(len(y))
            else:
                try:
                    x=numpy.array(eval(str(self.Data_Wave_Axes.currentText())))
                except SyntaxError: #should be corrected
                    x=numpy.arange(len(y))
            timescale=abs(x[1]-x[0])
            A,=self.Fit_Example.canvas.axes.plot(x,y,'g')
        else:
            print 'No Data Wave defined (yet)'
            return


        Bounds=[]
        for i in range(10):
            Bounds.append([self.MinGuess[i],self.MaxGuess[i]])
            
        fit=self.Fit(x,X=x,function=str(self.List_of_Functions.currentText()).lower(),Guess=self.param_list,StartX=self.range[0],EndX=self.range[1],Number_of_points=len(x),Rendering = False,Bounds=Bounds,Model=True)
        B,=self.Fit_Example.canvas.axes.plot(x,fit,'r') #The fitting guess
        self.Fit_Example.canvas.axes.legend([A,B], ["Data", "Model"], loc='best',fancybox=True)
        
        self.Fit_Example.canvas.axes.axvspan(self.range[0], self.range[1], -2000, 2000,color='r',alpha=0.1)

            

        if self.fixed_range.checkState()==2:
            self.Fit_Example.canvas.axes.set_xbound(self.display_range[0],self.display_range[1])
            self.Fit_Example.canvas.axes.set_ybound(self.display_range[2],self.display_range[3])
        else:
            self.Display_Range_0.setText(str(self.Fit_Example.canvas.axes.get_xbound()[0]))
            self.Display_Range_1.setText(str(self.Fit_Example.canvas.axes.get_xbound()[1]))
            self.Display_Range_2.setText(str(self.Fit_Example.canvas.axes.get_ybound()[0]))
            self.Display_Range_3.setText(str(self.Fit_Example.canvas.axes.get_ybound()[1])) 
            self.display_range[0]=self.Fit_Example.canvas.axes.get_xbound()[0]
            self.display_range[1]=self.Fit_Example.canvas.axes.get_xbound()[1]
            self.display_range[2]=self.Fit_Example.canvas.axes.get_ybound()[0]
            self.display_range[3]=self.Fit_Example.canvas.axes.get_ybound()[1]

        self.Fit_Example.canvas.draw()
Esempio n. 32
0
 def find_indexes(Source,Min,Max):
 	c=abs(numpy.array(Source)-Min)
 	Min_index=list(c).index(min(c))
 	c=abs(numpy.array(Source)-Max)
 	Max_index=list(c).index(min(c))
 	return Min_index,Max_index    
Esempio n. 33
0
    def Fit(self,Source,X=None,function='line',Guess=numpy.ones(10),Show_Residuals=True,StartP=None,EndP=None,StartX=None,EndX=None,Show_Guess=False,Figure=None,Rendering=True,RAW_Data=True,Color='r',Show_Parameters=True,Number_of_points=1000.,Bounds=[[None,None]]*10,Model=False):
        """
        Source is the signal to fit
        X is the XScale
        function is the fitting function.
        Avaible functions are : line,
                                poly2,
                                poly3,
                                poly4,
                                gauss,
                                exp,
                                double_exp,
                                double_exp_xoffset,
                                sin,
                                hill,
                                sigmoid,
                                power,
                                beta
        p0 are the intitial guesses (default is a list of 1.)
        StartP and EndP are the start point and the End point of the fit (in points)
        StartX and EndX are the start point and the End point of the fit (in timescale units)
        """
        
        def find_indexes(Source,Min,Max):
        	c=abs(numpy.array(Source)-Min)
        	Min_index=list(c).index(min(c))
        	c=abs(numpy.array(Source)-Max)
        	Max_index=list(c).index(min(c))
        	return Min_index,Max_index    

        begin=X[0] #original begin and end points are stored here, so the final plot will be displayed in the original workspace
        end=X[-1]        
        if (StartP == None) and (StartX == None) :
            StartP=0
            StartX=0
        if (EndP == None) and (EndX == None) == None:
            EndP=len(Source)-1   
            EndX=len(Source)-1 
        
        if (StartP == None) or (EndP == None) :
            StartP,EndP=find_indexes(X,StartX,EndX) 
        else:
            StartX=X[StartP]
            EndX=X[EndP]


        Source=numpy.array(Source[StartP:EndP]) #if not using the whole range for the fit, truncated wave is created here
        X=numpy.array(X[StartP:EndP]) #if not using the whole range for the fit, truncated timescale is created here


    	# Data and Xscale
        Source = numpy.array(Source)
        if X==None or (len(Source) != len(X)):
            X = numpy.array(range(len(Source)))
            # create a set of Parameters

        Function=eval("self."+function) #the fitting function
        Formula=eval("self."+function.capitalize())[0] #the fitting formula
        Parameters_Names=eval("self."+function.capitalize())[1] ##list of the fitting parameters            
            



        for i,j in enumerate(Bounds):
            if Bounds[i][0] != None:
                Bounds[i][0]=numpy.float32(Bounds[i][0])
            if Bounds[i][1] != None:
                Bounds[i][1]=numpy.float32(Bounds[i][1])
        
        #print Bounds
        
        p0 = Parameters()

       
        # do fit, here with leastsq model
        if Model == False:
           
            for i,j in enumerate(Parameters_Names):
                #For each paramters, you can set value, min & max. i.e. p0.add('omega', value= 0.0, min=-numpy.pi/2., max=numpy.pi/2)
                if j != '0':
                    if Bounds[i][0] != None and Bounds[i][1]!=None:
                        p0.add(j,value=Guess[i],min=Bounds[i][0],max=Bounds[i][1])
                    elif Bounds[i][0] !=None and Bounds[i][1]==None:
                        p0.add(j,value=Guess[i],min=Bounds[i][0])     
                    elif Bounds[i][0] == None and Bounds[i][1] != None:
                        p0.add(j,value=Guess[i],max=Bounds[i][1])
                    else:
                        p0.add(j,value=Guess[i])            
            print 'Fitting in process ...'
            try:
                result = minimize(Function, p0, args=(X, Source))
                RenderingX=numpy.linspace(float(X[0]),float(X[-1]),num=Number_of_points)
                fit = Function(result.params,RenderingX) #Rendering, with Popt, the best fitting parameters
            except:
                print 'Fitting failed, try other parameters or constraints'
                return
            print 'Fitting performed between points ',StartP,' and ',EndP, ' (',len(X),' points)'
            print 'in units between: ',StartX,' and ',EndX
            print '######### FITTING RESULTS ############'
            print 'Parameters are :' 
            res=[]
            for i in list(result.params):
                print i, result.params[i].value  
                res.append(result.params[i].value)
            
        elif Model== True:
            for i,j in enumerate(Parameters_Names):
                if j != '0':
                    p0.add(j,value=Guess[i])             
            RenderingX=numpy.linspace(float(X[0]),float(X[-1]),num=Number_of_points)
            fit = Function(p0,RenderingX) #Rendering, with Popt, the best fitting parameters            

#        if Show_Parameters == True:
#            for i in range(len(popt)):
#                if List[i][0] != '0':
#                    try:
#                        pyplot.text(begin+((end-begin)/10), max(fit)-(i+1)*abs((max(fit)-min(fit))/(10)), r"%s = {%s} +/- {%s}" % ((str(List[i][0])),str(float(popt[i])),str(float((pcov[i][i])**0.5))))# .format(popt[i], (pcov[i][i])**0.5))
#                    except:
#                        pyplot.text(begin+((end-begin)/10), max(fit)-(i+1)*abs((max(fit)-min(fit))/(10)),'test')

        #if Show_Error_Bars == True: to do
            #pyplot.errorbar(X, Source, yerr = y_sigma, fmt = 'o')    

        
#        if Show_Guess == True:
#            guess=Function(X,*p0)
#            G,=pyplot.plot(X, guess, label='Test data',marker='o',color='g') 
#            if RAW_Data == True:
#                pyplot.legend([S, G, F], ["Data", "initial guess", "Fit"], loc='best',fancybox=True)
#            else:
#                pyplot.legend([G, F], ["initial guess", "Fit"], loc='best',fancybox=True)
#        else:
#            if RAW_Data == True:
#                pyplot.legend([S, F], ["Data", "Fit"], loc='best',fancybox=True)
#            else:
#                pyplot.legend([F], ["Fit"], loc='best',fancybox=True)

        if Rendering == True:
            pyplot.rc('axes',fc='white')
            if Figure == None: #Creation of the figure. If Figure is not None, the fit is integrated in pre-existing figure
                fig=pyplot.figure(facecolor='white')
            else:
                fig = Figure   
                
            pyplot.title('Fitting completed')        
            if RAW_Data == True:
                S,=pyplot.plot(X, Source,color='b')
                
            try:
                if Show_Residuals == True:
                    final = Source + result.residual
                    pyplot.plot(X, final, 'r')
            except UnboundLocalError: #Should be only in the Plugin, at first launch.
                print 'No results'
                
            F,=pyplot.plot(RenderingX, fit, linestyle='--',color=Color)
            
            pyplot.xlim([begin,end])
            pyplot.grid(True) 
            pyplot.show()
            return fit,res,fig
        else:
            return fit
Esempio n. 34
0
def main(input_one, input_two, output_name):
	trackone = audio.LocalAudioFile(input_one)
	tracktwo = audio.LocalAudioFile(input_two)
	sectionsone, segmentsone = trackone.analysis.sections, trackone.analysis.segments
	fsegsone, i = [], 0
	for section in sectionsone:
		while segmentsone[i].start + segmentsone[i].duration < section.start:
			i = i + 1
		fsegsone.append(segmentsone[i])
	sectionstwo, segmentstwo = tracktwo.analysis.sections, tracktwo.analysis.segments
	fsegstwo, i = [], 0
	for section in sectionstwo:
		while segmentstwo[i].start + segmentstwo[i].duration < section.start:
			i = i + 1
		fsegstwo.append(segmentstwo[i])
	ssmone, ssmtwo, ssmonetwo = [], [], []
	for i in range(len(sectionsone)):
		p1, t1, lb1, lm1, d1 = fsegsone[i].pitches, fsegsone[i].timbre, fsegsone[i].loudness_begin, fsegsone[i].loudness_max, fsegsone[i].duration
		tp1, k1, m1, ts1, ln1 = sectionsone[i].tempo, sectionsone[i].key, sectionsone[i].mode, sectionsone[i].time_signature, sectionsone[i].loudness
		for j in range(len(sectionsone)):
			p2, t2, lb2, lm2, d2 = fsegsone[j].pitches, fsegsone[j].timbre, fsegsone[j].loudness_begin, fsegsone[j].loudness_max, fsegsone[j].duration
			tp2, k2, m2, ts2, ln2 = sectionsone[j].tempo, sectionsone[j].key, sectionsone[j].mode, sectionsone[j].time_signature, sectionsone[j].loudness
			dp, dt, db, dm, dd = 0, 0, abs(lb2 - lb1), abs(lm2 - lm1), abs(d2 - d1)
			dtp, dk, dm, dts, dln = abs(tp2 - tp1), min(abs(k2 - k1), 12 - abs(k2 - k1)), abs(m2 - m1), 1/fractions.gcd(ts2, ts1), abs(ln2 - ln1)
			for k in range(12):
				dp = dp + (p2[k] - p1[k])**2
				dt = dt + (t2[k] - t1[k])**2
			dist = (dp**0.5)*10 + (dt**0.5) + db + dm + dd*100 + dtp*10 + dk*100 + dm + dts + dln
			ssmone.append(dist)
	for i in range(len(sectionstwo)):
		p1, t1, lb1, lm1, d1 = fsegstwo[i].pitches, fsegstwo[i].timbre, fsegstwo[i].loudness_begin, fsegstwo[i].loudness_max, fsegstwo[i].duration
		tp1, k1, m1, ts1, ln1 = sectionstwo[i].tempo, sectionstwo[i].key, sectionstwo[i].mode, sectionstwo[i].time_signature, sectionstwo[i].loudness
		for j in range(len(sectionstwo)):
			p2, t2, lb2, lm2, d2 = fsegstwo[j].pitches, fsegstwo[j].timbre, fsegstwo[j].loudness_begin, fsegstwo[j].loudness_max, fsegstwo[j].duration
			tp2, k2, m2, ts2, ln2 = sectionstwo[j].tempo, sectionstwo[j].key, sectionstwo[j].mode, sectionstwo[j].time_signature, sectionstwo[j].loudness
			dp, dt, db, dm, dd = 0, 0, abs(lb2 - lb1), abs(lm2 - lm1), abs(d2 - d1)
			dtp, dk, dm, dts, dln = abs(tp2 - tp1), min(abs(k2 - k1), 12 - abs(k2 - k1)), abs(m2 - m1), 1/fractions.gcd(ts2, ts1), abs(ln2 - ln1)
			for k in range(12):
				dp = dp + (p2[k] - p1[k])**2
				dt = dt + (t2[k] - t1[k])**2
			dist = (dp**0.5)*10 + (dt**0.5) + db + dm + dd*100 + dtp*10 + dk*100 + dm + dts + dln
			ssmtwo.append(dist)
	for i in range(len(sectionsone)):
		p1, t1, lb1, lm1, d1 = fsegsone[i].pitches, fsegsone[i].timbre, fsegsone[i].loudness_begin, fsegsone[i].loudness_max, fsegsone[i].duration
		tp1, k1, m1, ts1, ln1 = sectionsone[i].tempo, sectionsone[i].key, sectionsone[i].mode, sectionsone[i].time_signature, sectionsone[i].loudness
		for j in range(len(sectionstwo)):
			p2, t2, lb2, lm2, d2 = fsegstwo[j].pitches, fsegstwo[j].timbre, fsegstwo[j].loudness_begin, fsegstwo[j].loudness_max, fsegstwo[j].duration
			tp2, k2, m2, ts2, ln2 = sectionstwo[j].tempo, sectionstwo[j].key, sectionstwo[j].mode, sectionstwo[j].time_signature, sectionstwo[j].loudness
			dp, dt, db, dm, dd = 0, 0, abs(lb2 - lb1), abs(lm2 - lm1), abs(d2 - d1)
			dtp, dk, dm, dts, dln = abs(tp2 - tp1), min(abs(k2 - k1), 12 - abs(k2 - k1)), abs(m2 - m1), 1/fractions.gcd(ts2, ts1), abs(ln2 - ln1)
			for k in range(12):
				dp = dp + (p2[k] - p1[k])**2
				dt = dt + (t2[k] - t1[k])**2
			dist = (dp**0.5)*10 + (dt**0.5) + db + dm + dd*100 + dtp*10 + dk*100 + dm + dts + dln
			ssmonetwo.append(dist)
	ssmone = numpy.array(ssmone).reshape(len(fsegsone), len(fsegsone))
	ssmtwo = numpy.array(ssmtwo).reshape(len(fsegstwo), len(fsegstwo))
	ssmonetwo = numpy.array(ssmonetwo).reshape(len(fsegsone), len(fsegstwo))
	plt.imshow(ssmone, 'gray')
	plt.title('Section Distance Within ' + input_one)
	plt.colorbar()
	plt.savefig(output_name+'_one')
	plt.show()
	plt.imshow(ssmtwo, 'gray')
	plt.title('Section Distance Within ' + input_two)
	plt.colorbar()
	plt.savefig(output_name+'_two')
	plt.show()
	plt.imshow(ssmonetwo, 'gray')
	plt.title('Section Distance Between ' + input_one + ' and ' + input_two)
	plt.colorbar()
	plt.savefig(output_name+'_onetwo')
	plt.show()
Esempio n. 35
0
 def ScaleAxis(self):
     self.Sorted_X_Coordinates_Scaled=numpy.array(self.Sorted_X_Coordinates)*self.Scaling_Factor
     self.Sorted_Y_Coordinates_Scaled=numpy.array(self.Sorted_Y_Coordinates)*self.Scaling_Factor 
Esempio n. 36
0
    def on_listWidgetFiles_dropped(self, filePaths):
        self.FileType=None
        #TODO : Add wcp and igor SweepA
        #       Solve missing sweep bug. (counter will not increment)
        for filePath in filePaths:
            if os.path.exists(filePath):
                Array,Var=self.IgorLoad(filePath)
                if Array == None and Var == None:
                    return
                
                Suggestion=self.Suggest(Array) #Find the most likely suggestion for filter
                
                
                Filter,ok = QtGui.QInputDialog.getText(Main.FilteringWidget, 'To filter names, add text here', 
                "",QtGui.QLineEdit.Normal,Suggestion)
                
                
                #Split Filter if multiple inputs detected
                if ';' in Filter:
                    Filter = Filter.split(';')
                else:
                    Filter=[str(Filter)]
                
                #Split Filter if multiple inputs detected
                tempkeys=[]
                for i in Array:
                    tempkeys.append(i)
                tempkeys=sorted(tempkeys, key=self.splitgroups)
                
                #Detect the number of channels
                NewFilterList=[]
                for s in tempkeys:
                    #for f in Filter: #if f in s:
                    if s.startswith(tuple(Filter)):
                        NewFilterList.append(''.join([i for i in s if not i.isdigit()]))
                            
                #NewFilterList=[x for x in NewFilterList if "C_Record" not in x] 
                Requete.NumberofChannels = len(list(set(NewFilterList)))

                OriginalSweepNames=[]
                FormatedSweepNames=[]                
                for Filter in list(set(NewFilterList)):
                    counter=0
                    for originalName in tempkeys:
                        if Filter in originalName:
                            if len(Navigate.ArrayList) <= counter:
                                Navigate.ArrayList.append([])
                                
                            formatedName=originalName
                            Main.LoadedList.append(originalName)
                            
                            if "Record" in Filter:
                                shortname=originalName[originalName.index('d')+2:]
                                shortname=shortname.zfill(4)
                                formatedName=Filter+shortname
                                self.FileType="Neuromatic"
        
                            elif "sweep" in Filter:
                                shortname=originalName[originalName.index('p')+2:]
                                shortname=shortname.zfill(4)
                                formatedName=Filter+shortname   
                                self.FileType="Synaptics"
                            
                            else:
                                wcp=False
                                for letter in list(string.ascii_uppercase):
                                    if Filter == letter:
                                        wcp=True
                                        shortname=originalName[originalName.index(letter)+1:]
                                        shortname=shortname.zfill(4)
                                        formatedName=letter+shortname
                                        self.FileType="WinWCP"  
                                if wcp == False:
                                    print 'Filetype not supported yet or not tested'
                                    return
                                        
                                
                            OriginalSweepNames.append(originalName)    
                            FormatedSweepNames.append(formatedName)
                            exec("Analysis."+formatedName+"= Array[originalName]")
                            Navigate.ArrayList[counter].append(numpy.array(eval("Analysis."+formatedName),dtype=float64))
                            counter+=1 

                if Var != None:
                    for i in Var:
                        exec("Analysis."+i+"= Var[i]")
                        Navigate.VarList[i]=eval("Analysis."+i)                      
                #else:
                   # exec("Analysis.Data = Array")
                Main.AnalysisWidget.setEnabled(True)
                Main.NavigationWidget.setEnabled(True)
                Main.MappingWidget.setEnabled(True)
                
                
                
                if len(Navigate.ArrayList[0][0]) > 200000:
                    savename, ok = QtGui.QInputDialog.getText(QtCore.QObject().sender().parent(), 'Long file',''' 
                        The signal looks very long and could be
                        a concatenated signal or a continuous recording.
                        Do you want to reslice it?''') 
                    if ok:
                        print 'more than 200 000 points per sweep, original trace was auto-resliced'
                        if Navigate.VarList.has_key("sampling_rate") == True:
                            sr = int(1000.*Navigate.VarList["sampling_rate"])
                        elif Navigate.VarList.has_key("SampleInterval") == True:
                            sr = int(1000./Navigate.VarList["SampleInterval"])
                        else:
                            sr = 50000
                        counter=0
                        temp=[None]*int(len(Navigate.ArrayList[0][0])/sr)
                        for Slice in range(len(temp)):
                            temp[Slice]=[None]*Requete.NumberofChannels
                            print 'reslicing slice ',Slice
                            for n in range(Requete.NumberofChannels):
                                temp[Slice][n]=numpy.array(Navigate.ArrayList[0][n][0:sr])
                                del Navigate.ArrayList[0][n][0:sr]
    
                        Navigate.ArrayList=temp
                        del temp

                self.Update_Navigate()
                Requete.Add_Dictionnary_Arrays()
                Infos.Actualize()
                
                #QtGui.QListWidgetItem(filePath+" added as self."+filePath.split("/")[-1][:-4], self.listWidgetFiles)
                QtGui.QListWidgetItem(filePath+" opened", self.listWidgetFiles)
                 
                for i in range(len(OriginalSweepNames)):
                    QtGui.QListWidgetItem("         Igor Wave "+OriginalSweepNames[i]+" loaded as Analysis."+FormatedSweepNames[i], self.listWidgetFiles)
        
        Requete.SpikeTrainfromLocal={}
        Requete.AmpSpikeTrainfromLocal={} 
        Requete.Spiketrain_ids=numpy.copy(Requete.Analogsignal_ids)
        Main.Current_or_Average.setCurrentIndex(int(Main.Current_or_Average.findText('Navigate.si')))
Esempio n. 37
0
context.useClock(0, "/#[TYPE=PulseGen]")
context.useClock(1, "/#[TYPE=Table]")
context.setClock(0, SIMDT)
context.setClock(1, SIMDT)
context.reset()
context.step(RUNTIME)

plot0.dumpFile("pulse0.plot")
plot1.dumpFile("pulse1.plot")
plot2.dumpFile("pulse2.plot")
plotGate.dumpFile("gate.plot")
plotTrig.dumpFile("trig.plot")
if has_pylab:
    fig = pylab.figure()
    pylab.subplot(511)
    pylab.plot(numpy.array(plot0))
    pylab.title('Free Run')
    pylab.subplot(512)
    pylab.plot(numpy.array(plot1))
    pylab.title('Triggered (below)')
    pylab.subplot(513)
    pylab.plot(numpy.array(plotTrig))
    pylab.title('Free Running Trigger')
    pylab.subplot(514)
    pylab.plot(numpy.array(plot2))
    pylab.title('Gated (below)')
    pylab.subplot(515)
    pylab.plot(numpy.array(plotGate))
    pylab.title('Free Running Gate')
    pylab.show()
print '----------------------------------------------------------'