示例#1
0
def applyKernelMA(inputImage, kernelX, kernelY, normalizeMagnitude=False):
    height = len(inputImage)
    width = len(inputImage[0])

    kernelHeight = len(kernelX)
    kerelWidth = len(kernelX[0])

    kernelCentreY = int((kernelHeight - 1) / 2)
    kernelCentreX = int((kerelWidth - 1) / 2)

    # Create images to store the result
    magnitude = createImageF(width, height)
    direction = createImageF(width, height)
    imageX = createImageF(width, height)
    imageY = createImageF(width, height)

    # Convolution with two kernels
    for x,y in itertools.product(range(kernelCentreX, width - kernelCentreX),          \
                                 range(kernelCentreY, height - kernelCentreY)):
        sumKernel = [0.0, 0.0]
        sumKernelWeights = [0.0, 0.0]
        for wx, wy in itertools.product(range(0, kerelWidth),
                                        range(0, kernelHeight)):

            posY = y + wy - kernelCentreY
            posX = x + wx - kernelCentreX

            if posY > -1 and posY < height and posX > -1 and posX < width:
                sumKernel[0] += float(inputImage[posY, posX]) * float(
                    kernelX[wy, wx])
                sumKernelWeights[0] += float(kernelX[wy, wx])

                sumKernel[1] += float(inputImage[posY, posX]) * float(
                    kernelY[wy, wx])
                sumKernelWeights[1] += float(kernelY[wy, wx])

        # If we have to normalize
        if sumKernelWeights[0] != 0.0:
            imageX[y, x] = sumKernel[0] / sumKernelWeights[0]
        else:
            imageX[y, x] = sumKernel[0]

        # If we have to normalize
        if sumKernelWeights[1] != 0.0:
            imageY[y, x] = sumKernel[1] / sumKernelWeights[1]
        else:
            imageY[y, x] = sumKernel[1]

        magnitude[y, x] = sqrt(imageX[y, x] * imageX[y, x] +
                               imageY[y, x] * imageY[y, x])
        direction[y, x] = atan2(imageY[y, x], imageX[y, x])

    if normalizeMagnitude == True:
        maximum, minimum = imageMaxMin(magnitude)

        for x, y in itertools.product(range(0, width), range(0, height)):
            magnitude[y, x] = (magnitude[y, x] - minimum) / float(maximum -
                                                                  minimum)

    return magnitude, direction, imageX, imageY
示例#2
0
def regionSize(backProjImage, newBackProjImage, pos, newPos, sizeReg):
    # Compute geometric moments
    momS = createImageF(3, 3)
    momT = createImageF(3, 3)
    sizeSearch = [int(sizeReg[0] * 1.5), int(sizeReg[1] * 1.5)]
    for deltaX, deltaY in itertools.product(range(-sizeSearch[0], sizeSearch[0]),   \
                                            range(-sizeSearch[1], sizeSearch[1])):
        x, y = pos[0] + deltaX, pos[1] + deltaY
        for m, n in itertools.product(range(0, 3), range(0, 3)):
            momS[n, m] += (x**n) * (y**m) * backProjImage[y, x]

        x, y = newPos[0] + deltaX, newPos[1] + deltaY
        for m, n in itertools.product(range(0, 3), range(0, 3)):
            momT[n, m] += (x**n) * (y**m) * newBackProjImage[y, x]

    xc, yc = momS[1, 0] / momS[0, 0], momS[0, 1] / momS[0, 0]
    a = momS[2, 0] / momS[0, 0] - xc * xc
    b = 2 * (momS[1, 1] / momS[0, 0] - xc * yc)
    c = momS[0, 2] / momS[0, 0] - yc * yc
    sxS = int(sqrt((a + c - sqrt(b * b + (a - c) * (a - c)) / 2)))
    syS = int(sqrt((a + c + sqrt(b * b + (a - c) * (a - c)) / 2)))

    xc, yc = momT[1, 0] / momT[0, 0], momT[0, 1] / momT[0, 0]
    a = momT[2, 0] / momT[0, 0] - xc * xc
    b = 2 * (momT[1, 1] / momT[0, 0] - xc * yc)
    c = momT[0, 2] / momT[0, 0] - yc * yc
    sx = int(sqrt((a + c - sqrt(b * b + (a - c) * (a - c)) / 2)))
    sy = int(sqrt((a + c + sqrt(b * b + (a - c) * (a - c)) / 2)))

    sy = sy * sizeReg[1] / syS
    sx = sx * sizeReg[0] / sxS

    return [int(xc), int(yc)], [int(sx), int(sy)]
示例#3
0
def createLaplacianKernel(kernelSize, sigma):

    # kernel
    kernelLaplacian = createImageF(kernelSize, kernelSize)

    # Create kernel
    s2Inv = 1.0 / (sigma * sigma)
    kernelCentre = (kernelSize - 1) / 2

    # Generate kernel values
    sumValues = 0.0
    for x, y in itertools.product(range(0, kernelSize), range(0, kernelSize)):

        nx2 = float(x - kernelCentre) * float(x - kernelCentre)
        ny2 = float(y - kernelCentre) * float(y - kernelCentre)

        s = 0.5 * (nx2 + ny2) * s2Inv

        kernelLaplacian[y, x] = -s2Inv * s2Inv * (1.0 - s) * exp(-s)

        sumValues += kernelLaplacian[y, x]

    # Normalize
    for x, y in itertools.product(range(0, kernelSize), range(0, kernelSize)):
        kernelLaplacian[y, x] /= sumValues

    return kernelLaplacian
示例#4
0
def fillImageColours(colours, xy, image):
    nfaces = len(xy)
    
    height = len(image)
    width = len(image[0]) 
    
    for faceNum in range(0, nfaces):
        face = xy[faceNum]
        npts = len(face)
        colour = colours[faceNum]
    
        for a,b in itertools.product(range(0, npts-1), range(0, npts-1)):
            
            c0,c1,c2 = face[a][b], face[a+1][b], face[a][b+1]  

            c = colour[a,b];
            
            # Fill output image
            v1 = [c1[0]-c0[0], c1[1]-c0[1]]
            v2 = [c2[0]-c0[0], c2[1]-c0[1]]
            
            lv1 = max(.001,sqrt(v1[0]*v1[0] + v1[1]*v1[1]))
            lv2 = max(.001,sqrt(v2[0]*v2[0] + v2[1]*v2[1]))
            v1N = [v1[0]/lv1, v1[1]/lv1]
            v2N = [v2[0]/lv2, v2[1]/lv2]
            
            for dV1, dV2 in itertools.product(range(0, 4*(1+int(lv1))), range(0, 4*(1+int(lv2)))):
                x = int(c0[0] + v2N[0] * dV2*.25 + v1N[0] * dV1*.25)
                y = int(c0[1] + v2N[1] * dV2*.25 + v1N[1] * dV1*.25)
                if x>0 and x < width and y > 0 and y < height:
                    image[y,x] = c
示例#5
0
def applyKernelF(inputImage, kernelImage):
    height = len(inputImage)
    width = len(inputImage[0])

    kernelHeight = len(kernelImage)
    kernelWidth = len(kernelImage[0])

    kernelCentreY = int((kernelHeight - 1) / 2)
    kernelCentreX = int((kernelWidth - 1) / 2)

    # Create images to store the result
    outputImage = createImageF(width, height)

    for x, y in itertools.product(range(0, width), range(0, height)):
        sumKernel = 0.0
        sumKernelWeights = 0.0
        for wx, wy in itertools.product(range(0, kernelWidth),
                                        range(0, kernelHeight)):
            posY = y + wy - kernelCentreY
            posX = x + wx - kernelCentreX

            if posY > -1 and posY < height and posX > -1 and posX < width:
                sumKernel += float(inputImage[posY, posX]) * float(
                    kernelImage[wy, wx])
                sumKernelWeights += float(kernelImage[wy, wx])

        # If we have to normalize
        if sumKernelWeights != 0.0:
            outputImage[y, x] = sumKernel / sumKernelWeights
        else:
            outputImage[y, x] = sumKernel

    return outputImage
示例#6
0
def densityHistogram(image, position, regionRadius, sigma, histoSize):
    height = len(image)
    width = len(image[0])

    # Quantization scale
    colourScale = 256.0 / histoSize

    histogram = createImageF(histoSize, histoSize)
    sumValue = 0
    for deltaX, deltaY in itertools.product(
            range(-regionRadius[0], regionRadius[0]),
            range(-regionRadius[1], regionRadius[1])):

        x, y = position[0] + deltaX, position[1] + deltaY
        if x > 0 and y > 0 and x < width and y < height:

            w = exp(-(deltaX * deltaX + deltaY * deltaY) / (2 * sigma * sigma))
            rgb = image[y, x] / 256.0

            Cb = int((128 - 37.79 * rgb[0] - 74.203 * rgb[1] + 112 * rgb[2]) /
                     colourScale)
            Cr = int((128 + 112 * rgb[0] - 93.786 * rgb[1] - 18.214 * rgb[2]) /
                     colourScale)

            histogram[Cr, Cb] += w
            sumValue += w

    for r, b in itertools.product(range(0, histoSize), range(0, histoSize)):
        histogram[r, b] /= sumValue

    return histogram
示例#7
0
 def getMoveCombinationAll(self,player,state):
     posL=[]
     lD=[]
     for (r,c,p) in self.getAnts(state,player):
         locc,dir=self.storeMovePosition.getMove((r,c))
         posL.append(locc)
         lD.append(dir)
     return (list(itertools.product(*posL)),list(itertools.product(*lD)))
示例#8
0
def meanShift(inputImage, q, sizeReg, sigma, histoSize, newPos):
    # Weights
    weights = createImageF(2 * sizeReg[0], 2 * sizeReg[1])

    currPos = [0, 0]

    colourScale = 256.0 / histoSize

    while (currPos != newPos):
        currPos = newPos
        qs = densityHistogram(inputImage, currPos, sizeReg, sigma, histoSize)

        # Weights
        for deltaX, deltaY in itertools.product(range(-sizeReg[0],sizeReg[0]),   \
                                                range(-sizeReg[1], sizeReg[1])):

            # Position of the pixel in the image and in the weight array
            x, y = currPos[0] + deltaX, currPos[1] + deltaY
            px, py = deltaX + sizeReg[0], deltaY + sizeReg[1]

            # Features
            Cb, Cr = colourFeature(inputImage[y, x], colourScale)

            # Update
            if qs[Cr, Cb] > 0:
                weights[py, px] = sqrt(q[Cr, Cb] / qs[Cr, Cb])
            else:
                weights[py, px] = sqrt(q[Cr, Cb] / .000000000001)

        # Compute mean shift sums
        meanSum = [0, 0]
        kernelSum = 0
        for deltaX, deltaY in itertools.product(range(-sizeReg[0],sizeReg[0]),   \
                                                range(-sizeReg[1], sizeReg[1])):

            # Position of the pixel in the image
            x, y = currPos[0] + deltaX, currPos[1] + deltaY

            # Kernel parameter
            w = exp(-(deltaX * deltaX + deltaY * deltaY) / (2 * sigma * sigma))

            # Weight index
            px, py = deltaX + sizeReg[0], deltaY + sizeReg[1]

            # Mean sum
            meanSum[0] += w * weights[py, px] * x
            meanSum[1] += w * weights[py, px] * y

            # Kernel sum
            kernelSum += w * weights[py, px]

        # Mean shift
        newPos = [int(meanSum[0] / kernelSum), int(meanSum[1] / kernelSum)]

    return newPos
示例#9
0
def weightedKrawtchoukPolynomials(p, width):

    # Data containers
    sigma = createVectorF(width)
    ro = createVectorF(width)
    K = createImageF(width, width)

    # Coefficient size
    N = width - 1

    # Weight
    for x in range(0, width):
        sigma[x] = nCr(N, x) * pow(p, x) * pow(1 - p, N - x)

    # Scale factor. Commented direct computation and using for to avoid factorial
    #for n in range(0,width):
    #    ro[n] = pow(-1,n) * pow((1-p)/p,n) * (float(factorial(n)) / risingFactorial(-N, n))
    ro[0] = 1
    for n in range(1, N):
        ro[n] = (-1 * ((1.0 - p) / p) * n / (-N + (n - 1))) * ro[n - 1]
    ro[N] = (((1.0 - p) / p) * N) * ro[N - 1]

    # Krawtchouk matrix that store result of the polynomial
    # Each row is a polynomial each column is the polynomial value for an x value
    # Alternatively, we could have used the polynomial generating function
    q = 1.0 / p
    for n, x in itertools.product(range(0, width), range(0, width)):
        for s in range(0, width):
            K[n, x] += pow(-1, s) * nCr(N - x, n - s) * nCr(x, s) * pow(
                q - 1, n - s)

    # Normalize rows for stability
    for n in range(0, width):
        scale = K[n, 0]
        for x in range(0, width):
            K[n, x] /= scale

    # Obtain the coefficients A of the polynomials from K
    # Solve for the coefficients A in A*C = K
    C = createImageF(width, width)
    for n, x in itertools.product(range(0, width), range(0, width)):
        C[n, x] = pow(x, n)

    CT = np.transpose(C)
    KT = np.transpose(K)
    AT = np.linalg.solve(CT,
                         KT)  # solves the equation A*x=b   A*C = k, C'*A' = K'
    A = np.transpose(AT)

    # Product defining the weighted
    w = createImageF(width, width)
    for n, x in itertools.product(range(0, width), range(0, width)):
        w[n, x] = sqrt(sigma[x] / ro[n])

    return K, A, sigma, ro, w
示例#10
0
def backProjection(sourceImage, targetImage, qSource, pSource, pTarget,
                   sizeReg, histoSize):
    height, width = len(sourceImage), len(sourceImage[0])

    colourScale = 256.0 / histoSize

    # Projection
    projectionSource = createImageF(width, height)
    projectionTarget = createImageF(width, height)
    for x, y in itertools.product(range(0, width), range(0, height)):

        Cb, Cr = colourFeature(sourceImage[y, x], colourScale)
        projectionSource[y, x] = qSource[Cr, Cb]

        Cb, Cr = colourFeature(targetImage[y, x], colourScale)
        projectionTarget[y, x] = qSource[Cr, Cb]

    # Compute geometric moments
    momS = createImageF(3, 3)
    momT = createImageF(3, 3)
    sizeSearch = [int(sizeReg[0] * 1.5), int(sizeReg[1] * 1.5)]
    for deltaX, deltaY in itertools.product(range(-sizeSearch[0], sizeSearch[0]),   \
                                            range(-sizeSearch[1], sizeSearch[1])):
        x, y = pSource[0] + deltaX, pSource[1] + deltaY
        for m, n in itertools.product(range(0, 3), range(0, 3)):
            momS[n, m] += (x**n) * (y**m) * projectionSource[y, x]

        x, y = pTarget[0] + deltaX, pTarget[1] + deltaY
        for m, n in itertools.product(range(0, 3), range(0, 3)):
            momT[n, m] += (x**n) * (y**m) * projectionTarget[y, x]

    xc, yc = momS[1, 0] / momS[0, 0], momS[0, 1] / momS[0, 0]
    a = momS[2, 0] / momS[0, 0] - xc * xc
    b = 2 * (momS[1, 1] / momS[0, 0] - xc * yc)
    c = momS[0, 2] / momS[0, 0] - yc * yc
    sxS = int(sqrt((a + c - sqrt(b * b + (a - c) * (a - c)) / 2)))
    syS = int(sqrt((a + c + sqrt(b * b + (a - c) * (a - c)) / 2)))

    xc, yc = momT[1, 0] / momT[0, 0], momT[0, 1] / momT[0, 0]
    a = momT[2, 0] / momT[0, 0] - xc * xc
    b = 2 * (momT[1, 1] / momT[0, 0] - xc * yc)
    c = momT[0, 2] / momT[0, 0] - yc * yc
    sx = int(sqrt((a + c - sqrt(b * b + (a - c) * (a - c)) / 2)))
    sy = int(sqrt((a + c + sqrt(b * b + (a - c) * (a - c)) / 2)))

    sy = sy * sizeReg[1] / syS
    sx = sx * sizeReg[0] / sxS

    return [int(xc), int(yc)], [int(sx), int(sy)]
def csv_format(initial_matrix):
    global nodes
    global temp_nodes
    new_list = []
    zero_list = []
    dir_values = ['fw', 'bw']
    g_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
    f_values = [
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
        20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32
    ]
    #print("h")
    for node in temp_nodes:
        #print("hi")
        if (node.getstate() == 'closed'):
            hdir = node.gethvalue()
            #print(hdir)
            fdir = node.getvalue() + hdir
            new_list.append((node.getdirection(), node.getvalue(), fdir))

    prod_list = list(itertools.product(dir_values, g_values, f_values))
    #zero_list = set(new_list).intersection(set(prod_list))
    for i in prod_list:
        if i not in new_list:
            zero_list.append(i)
    #print(zero_list)

    return new_list, zero_list
示例#12
0
    def plot_peaks(self,
                   qz_lims=[-1e-5, 1],
                   q_para_lim=6,
                   qx_lims=None,
                   qy_lims=None,
                   HKL_lims=[-10, 10],
                   color=(0, 0, 0)):
        HKLs = list(
            itertools.product(np.arange(HKL_lims[0], HKL_lims[1]), repeat=3))
        qs = []
        Is = []
        for HKL in HKLs:
            q = self.lattice.q(HKL)
            if (q_para_lim != None):
                if (q[2] >= qz_lims[0] and q[2] < qz_lims[1]
                        and np.sqrt(q[0]**2 + q[1]**2) <= q_para_lim):
                    qs.append(q)
                    Is.append(self.lattice.I(HKL))
            elif (qx_lims != None and qy_lims != None):
                if (q[0] >= qx_lims[0] and q[0] < qx_lims[1]
                        and q[1] >= qy_lims[0] and q[1] < qy_lims[1]
                        and q[2] >= qz_lims[0] and q[2] < qz_lims[1]):
                    qs.append(q)
                    Is.append(self.lattice.I(HKL))

        qs = np.array(qs)
        qs = np.swapaxes(qs, 0, 1)
        Is = np.array(Is)
        Is /= np.max(Is)
        mlab.points3d(qs[0], qs[1], qs[2], Is, scale_factor=1, color=color)
示例#13
0
 def get_rod_positions(self, qz_lims=[-1e-5,1], q_para_lim=6, qx_lims=None, qy_lims=None, HKL_lims=[-10, 10], color=(0,0,0)): 
     HKLs = list(itertools.product(np.arange(HKL_lims[0],HKL_lims[1]), repeat=3))
     qIs = []
     for HKL in HKLs:
         qI = self.lattice.qI(HKL)
         if(q_para_lim != None):
             if(qI[2] >= qz_lims[0] and qI[2] < qz_lims[1] and np.sqrt(qI[0]**2+qI[1]**2)<= q_para_lim):
                 qIs.append(qI)
         elif(qx_lims != None and qy_lims != None):
             if(qI[0] >= qx_lims[0] and qI[0] < qx_lims[1] and qI[1] >= qy_lims[0] and qI[1] < qy_lims[1] and qI[2] >= qz_lims[0] and qI[2] < qz_lims[1]):
                 qIs.append(qI)
     
     qIs = np.array(qIs)        
     rows = np.where(qIs[:,3] > 1e-20)
     qIs = qIs[rows]
     qIs_filtered = []
     for qI in qIs:
         add_qI = True
         for qI_filtered in qIs_filtered:
             if((abs(qI[0]-qI_filtered[0]) < 0.001) and (abs(qI[1]-qI_filtered[1]) < 0.001)):
                 add_qI = False
                 break
         if(add_qI):
             qIs_filtered.append(qI)
     return qIs_filtered
示例#14
0
    def three_parents(self, utility_node, e, known, known_set):
        result = self.two_generate(e, utility_node)
        table = list(itertools.product([True, False], repeat=2 - len(known)))
        total = 0.0
        if len(known) == 0:
            for tuple in range(len(table)):
                tuple_set = table[tuple]
                total += result[tuple_set]
            return total
        if len(known) == 1:
            for tuple in range(len(table)):
                (i, j) = table[tuple]
                if known_set[0] == True:
                    total += result[(known[0], i, j)]
                if known_set[1] == True:
                    total += result[(i, known[0], j)]
                else:
                    total += result[(i, j, known[0])]

        if len(known) == 2:
            for tuple in range(len(table)):
                (i, ) = table[tuple]
                if known_set[0] == True and known_set[1] == True:
                    total += result[(known[0], known[1], i)]
                if known_set[0] == True and known_set[2] == True:
                    total += result[(known[0], i, known[1])]
                if known_set[1] == True and known_set[2] == True:
                    total += result[(i, known[0], known[1])]

        else:
            total += result[(known[0], known[1], known[2])]

        return total
示例#15
0
    def plot_peaks(self,
                   HKL_lims=[-10, 10],
                   qx_lims=None,
                   qy_lims=None,
                   q_inplane_lim=None,
                   qz_lims=None,
                   mag_q_lims=None,
                   color=(0, 0, 0),
                   scale_factor=1):
        HKL_range = np.arange(HKL_lims[0], HKL_lims[1] + 1)
        HKLs = list(itertools.product(HKL_range, repeat=3))
        qs = []
        Is = []
        for HKL in HKLs:
            q = self.lattice.q(HKL)
            if (self.is_in_limits(q, qx_lims, qy_lims, q_inplane_lim, qz_lims,
                                  mag_q_lims)):
                qs.append(q)
                Is.append(self.lattice.I(HKL))

        qs = np.array(qs)
        qs = np.swapaxes(qs, 0, 1)
        Is = np.array(Is)
        if (len(Is > 0)):
            # Normalize to (0,0,0) intensity and plot the sqrt
            Is /= self.lattice.I([0, 0, 0])
            Is = np.sqrt(Is)
            mlab.points3d(qs[0],
                          qs[1],
                          qs[2],
                          Is,
                          scale_factor=scale_factor,
                          color=color)
示例#16
0
    def get_rod_positions(self,
                          HKL_lims=[-10, 10],
                          qx_lims=None,
                          qy_lims=None,
                          q_inplane_lim=None,
                          qz_lims=None,
                          color=(0, 0, 0)):
        HKL_range = np.arange(HKL_lims[0], HKL_lims[1] + 1)
        HKLs = list(itertools.product(HKL_range, repeat=3))
        qIs = []
        # Find all lattice positions within limits
        for HKL in HKLs:
            q = self.lattice.q(HKL)
            if (self.is_in_limits(q, qx_lims, qy_lims, q_inplane_lim,
                                  qz_lims)):
                qIs.append(self.lattice.qI(HKL))

        # Select all positions with non-zero intensity
        qIs = np.array(qIs)
        rows = np.where(qIs[:, 3] > 1e-20)
        qIs = qIs[rows]

        # We only need one point per (qx, qy) coordinate
        qIs_filtered = []
        for qI in qIs:
            add_qI = True
            for qI_filtered in qIs_filtered:
                if ((abs(qI[0] - qI_filtered[0]) < 0.001)
                        and (abs(qI[1] - qI_filtered[1]) < 0.001)):
                    add_qI = False
                    break
            if (add_qI):
                qIs_filtered.append(qI)
        return qIs_filtered
示例#17
0
def reconstruction(coefficients):
    # Maximum frequency
    maxFrequencyH = int((len(coefficients) - 1) / 2)
    maxFrequencyW = int((len(coefficients[0]) - 1) / 2)

    height = 2 * maxFrequencyH
    width = 2 * maxFrequencyW

    # Adjust the size of the data to be even
    m = float(width)
    n = float(height)
    if width % 2 == 0:
        m = width + 1
    if height % 2 == 0:
        n = height + 1

    # Fundamental frequency
    ww = (2.0 * pi) / float(m)
    wh = (2.0 * pi) / float(n)

    reconstructionImage = createImageF(m, n)
    for x in range(0, width):
        printProgress(x, width - 1)
        for y in range(0, height):
            for kw,kh in itertools.product(range(-maxFrequencyW, maxFrequencyW + 1),             \
                                           range(-maxFrequencyH, maxFrequencyH + 1)):
                indexInArrayW = kw + maxFrequencyW
                indexInArrayH = kh + maxFrequencyH
                reconstructionImage[y,x] += \
                        (coefficients[indexInArrayH, indexInArrayW][0] / (m*n)) * (cos(x * ww * kw) * cos(y * wh * kh) - sin(x * ww * kw) * sin(y * wh * kh)) + \
                        (coefficients[indexInArrayH, indexInArrayW][1] / (m*n)) * (cos(x * ww * kw) * sin(y * wh * kh) + sin(x * ww * kw) * cos(y * wh * kh))

    return reconstructionImage
示例#18
0
    def findPureNash(self):
        nash = []
        bestAnswers = []
        # print self.strategy_profiles
        for players in range(0, len(self.player_names)):
            strategiesOfOtherPlayers = []
            for strategie in range(0, len(self.strategies)):
                if strategie != players:
                    strategiesOfOtherPlayers.append(self.strategies[strategie])
            currentPlayersBestAnswers = []
            for othersStrategies in list(itertools.product(*strategiesOfOtherPlayers)):
                currentBestAnswers = []
                bestPayoff = -sys.maxint - 1
                for strategyOfCurrentPlayer in self.strategies[players]:
                    currentProfile = []
                    currentProfile += othersStrategies
                    currentProfile.insert(players, strategyOfCurrentPlayer)
                    # print currentProfile
                    indexInAllProfiles = list(self.strategy_profiles).index(currentProfile)
                    currentPayoff = self.payoffs[self.outcomes[indexInAllProfiles]][players + 1]
                    if currentPayoff > bestPayoff:
                        currentBestAnswers = [tuple(currentProfile)]
                        bestPayoff = currentPayoff
                    elif currentPayoff == bestPayoff:
                        currentBestAnswers.append(tuple(currentProfile))
                # print "player " + str(players) + ": best answer for " + str(othersStrategies) + " is " + str(bestAnswers)
                # bestAnswers.append(tuple(currentBestAnswers))
                currentPlayersBestAnswers += currentBestAnswers
            bestAnswers.append(currentPlayersBestAnswers)

        nash = set(tuple(bestAnswers[0]))
        for players in range(len(self.player_names)):
            nash = nash & set(tuple(bestAnswers[players]))

        return nash
示例#19
0
    def powder(self, q_max, HKL_lims=[-10, 10]):
        HKL_range = np.arange(HKL_lims[0], HKL_lims[1] + 1)
        HKLs = list(itertools.product(HKL_range, repeat=3))
        qIs = []
        Is = dict()
        # Find all lattice positions within limits
        for HKL in HKLs:
            q = self.q(HKL)
            Q = np.sqrt(q.dot(q))
            if (Q <= q_max):
                if Q in Is:
                    Is[Q] += self.I(HKL)
                else:
                    Is[Q] = self.I(HKL)
        Q = []
        I = []
        for key in Is:
            Q.append(key)
            I.append(Is[key])

        indices = np.argsort(Q)
        Q_sorted = []
        I_sorted = []
        for index in indices:
            Q_sorted.append(Q[index])
            I_sorted.append(I[index])
        Q_sorted = np.array(Q_sorted)
        I_sorted = np.array(I_sorted) / I_sorted[0]

        return (Q_sorted, I_sorted)
示例#20
0
def pixlesList(image, backgroundRange):
    listPixels = []
    height, width = len(image), len(image[0])
    for x, y in itertools.product(range(0, width), range(0, height)):
        if image[y, x] < backgroundRange[0] or image[y,
                                                     x] > backgroundRange[1]:
            listPixels.append((y, x, 1))
    return listPixels
示例#21
0
文件: benchmark.py 项目: makkus/gopy
    def __init__(self, name, go, perf_p=[], perf_cc=[], perf_pp=[]):

        self.name = name
        self.go = go

        if os.path.exists(BENCHMARKS_DIRECTORY + os.sep + name):

            if perf_p or perf_cc or perf_pp:
                raise Exception(
                    'Benchmark "' + name +
                    '" already exists, you can\'t specify performance options')

            with open(BENCHMARKS_DIRECTORY + os.sep + name, 'rb') as f:
                bm = pickle.load(f)
                self.perf_p = bm.perf_p
                self.perf_cc = bm.perf_cc
                self.perf_pp = bm.perf_pp
                self.items = bm.items
                self.series = bm.series
                return
        else:

            if not perf_p and not perf_cc and not perf_pp:
                raise Exception(
                    'Benchmark "' + name +
                    '" does not exist, you need to specify performance options (e.g. --perf-p=1,8,16 --perf-cc=1 --perf-pp=1,16,32)'
                )

            if perf_p:
                self.perf_p = perf_p
            else:
                self.perf_p = [1]

            if perf_cc:
                self.perf_cc = perf_cc
            else:
                self.perf_cc = [1]

            if perf_pp:
                self.perf_pp = perf_pp
            else:
                self.perf_pp = [1]

            self.items = []
            self.series = []

            # first, we always run the "no-option" globus default, to have a comparison
            self.items.append(BenchmarkItem(0, 0, 0))

            combinantions = itertools.product(self.perf_p, self.perf_cc,
                                              self.perf_pp)

            for c in combinantions:
                item = BenchmarkItem(c[0], c[1], c[2])
                self.items.append(item)

            self.save()
示例#22
0
def imageTransform(image, maskImage, T):    
    height, width = len(image), len(image[0])
    centreX, centreY = width/2, height/2
    
    sImage = createImageRGB(width, height)
    for y, x in itertools.product(range(0, height-1), range(0, width-1)):
        # Alpha and colour   
        alpha = maskImage[y,x]/256.0 
        if alpha == 0: 
            continue
        rgb = (image[y,x]/4.0 + image[y+1,x+1]/4.0 + image[y+1,x]/4.0 +  \
               image[y,x+1]/4.0) * alpha
        
        # Transform
        cx, cy = x - centreX, y - centreY
        p0z = T[2][0] * cx + T[2][1] * cy + T[2][2] 
        p1z = T[2][0] * (cx+1) + T[2][1] * cy + T[2][2] 
        p2z = T[2][0] * (cx+1) + T[2][1] * (cy+1) + T[2][2] 
        
        if p0z != 0 and p1z != 0 and p2z !=0:
    
            p0x = int((T[0][0] * cx + T[0][1] * cy + T[0][2]) / p0z + centreX)
            p0y = int((T[1][0] * cx + T[1][1] * cy + T[1][2]) / p0z + centreY) 
        
            p1x = int((T[0][0] * (cx+1) + T[0][1] * cy + T[0][2]) / p1z + centreX)
            p1y = int((T[1][0] * (cx+1) + T[1][1] * cy + T[1][2]) / p1z + centreY) 
        
            p2x = int((T[0][0] * (cx+1) + T[0][1] * (cy+1) + T[0][2]) / p2z + centreX)
            p2y = int((T[1][0] * (cx+1) + T[1][1] * (cy+1) + T[1][2]) / p2z + centreY) 
            
            # Fill output image
            v1, v2 = [p1x - p0x, p1y - p0y], [p2x - p0x, p2y - p0y]
                    
            lv1 = max(.001,sqrt(v1[0]*v1[0] + v1[1]*v1[1]))
            lv2 = max(.001,sqrt(v2[0]*v2[0] + v2[1]*v2[1]))
            v1N = [v1[0]/lv1, v1[1]/lv1]
            v2N = [v2[0]/lv2, v2[1]/lv2]
    
            for dV1, dV2 in itertools.product(range(0, int(lv1)+1), range(0, int(lv2)+1)):
                a,b = int(p0x + dV1 * v1N[0] + dV2 * v2N[0]), int(p0y + dV1 * v1N[1] + dV2 * v2N[1])
                if a>0 and a < width and b > 0 and b < height:
                    sImage[b,a] = rgb
    return sImage   
示例#23
0
def createGaussianKernel(kernelSize):

    sigma = kernelSize / 3.0

    kernelImage = createImageF(kernelSize, kernelSize)
    centre = (kernelSize - 1) / 2
    for x, y in itertools.product(range(0, kernelSize), range(0, kernelSize)):
        kernelImage[y,x] =  exp( -0.5 * (pow((x - centre)/sigma, 2.0) + \
                                         pow((y - centre)/sigma, 2.0)) )

    return kernelImage
示例#24
0
def backProjectionImage(image, q, histoSize):
    height, width = len(image), len(image[0])
    colourScale = 256.0 / histoSize

    # Projection
    projection = createImageF(width, height)
    for x, y in itertools.product(range(0, width), range(0, height)):

        Cb, Cr = colourFeature(image[y, x], colourScale)
        projection[y, x] = q[Cr, Cb]

    return projection
def compareBasicAlphas(resimulate=True,
                       Tf = 2.,
                       tau_chars = [.5,2],
                       mus = [-1,1]):
    sigma = 1.;
    params = array([sigma]);
    amax = 1.0
    alpha_bounds = [-amax, amax];  
    dt = .01; num_nodes = 200;
    
    lSolver = FBSolver(dt, Tf, num_nodes, xmin=-5., xmax=5.)
    
    thetas = list( itertools.product(mus, tau_chars))
     
    pThetas = ones(len (thetas)) / len(thetas);
    
    'ALPHAS::'
    alpha_bang_bang = lambda x: amax* sign(x)
    alpha_null = lambda x: .0*x
    alpha_antibang = lambda x: -sign(x)* amax
    alpha_H1 = lambda x: amax* sign(x)*(abs(x) > 1.)
    
    
#    alpha_tags = ['bang_bang', 'atan_bang_bang',  'null', 'atan_bang_bang']
#    alpha_funcs = [alpha_bang_bang, alpha_atan, alpha_null, alpha_antiatan]
    
    alpha_tags = ['bang_bang', 'anti_bang', 'alpha_null', 'alpha_H1']
    alpha_funcs = [alpha_bang_bang, alpha_antibang, alpha_null, alpha_H1]        
    alpha_fig = figure()
    for alpha_func, alpha_tag in zip(alpha_funcs,
                                      alpha_tags): 
        fb_file_name = 'alpha_'+ alpha_tag;
        if resimulate:
            alphas = lSolver.generateAlphaField(alpha_func);
            xs = lSolver._xs;
            width = 2.0; x_0 = .0;
            pre_ICs = exp(-(xs-x_0)**2 / width**2) / (width * sqrt(pi))
            ICs = pre_ICs / (sum(pre_ICs)*lSolver._dx) 
            xs, ts, fs, ps, J, grad_J = lSolver.solve(thetas, pThetas,
                                           params, alphas, 
                                           ICs,
                                           visualize=False)
            (FBSolution(params, thetas, pThetas, xs, ts,
                         fs, ps, alphas, grad_J, J)).save(fb_file_name)

        fbSoln = FBSolution.load(fb_file_name)
        xs = lSolver._xs;
        ax = alpha_fig.add_subplot(111)
        ax.plot(xs, alpha_func(xs), label=alpha_tag)
        ax.set_ylim((-amax-1,+amax+1))
        ax.legend()
        
        print alpha_tag + 'J=%.3g'%lSolver._calcObjective(fbSoln._fs, fbSoln._pThetas)
def computeHistogram(inputImage):
    height = len(inputImage)
    width = len(inputImage[0])

    # Vector of integers values to store the number of times a pixel value is repeated
    outputHistogram = createVectorI(256)

    # Get the number of times a pixel value is found in the image
    for x, y in itertools.product(range(0, width), range(0, height)):
        pixelValue = inputImage[y, x]
        outputHistogram[pixelValue] += 1

    return outputHistogram
示例#27
0
def geometricInvariantMoments(pixelList, numMoments):
    numPoints = len(pixelList)

    # Compute moments
    M = createImageF(numMoments, numMoments)
    for m, n in itertools.product(range(0, numMoments), range(0, numMoments)):
        for indexPixel in range(0, numPoints):
            y = (pixelList[indexPixel])[0]
            x = (pixelList[indexPixel])[1]
            val = (pixelList[indexPixel])[2]
            M[n, m] += (x**n) * (y**m) * val

    # Geometric central Moments
    xc, yc = M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]

    m11 = M[1, 1] / M[0, 0] - xc * yc
    m20 = M[2, 0] / M[0, 0] - xc**2
    m02 = M[0, 2] / M[0, 0] - yc**2

    if m20 < m02:
        t = -(0.5 * atan(2.0 * m11 / (m20 - m02)) + pi / 2.0)
    else:
        t = -(0.5 * atan(2.0 * m11 / (m20 - m02)))

    # Geometric invariant moments
    v = createImageF(numMoments, numMoments)
    vn = createImageF(numMoments, numMoments)
    for m, n in itertools.product(range(0, numMoments), range(0, numMoments)):
        for indexPixel in range(0, numPoints):
            y = (pixelList[indexPixel])[0]
            x = (pixelList[indexPixel])[1]
            val = (pixelList[indexPixel])[2]
            v[n, m] += ((x - xc) * cos(t) -
                        (y - yc) * sin(t))**n * ((x - xc) * sin(t) +
                                                 (y - yc) * cos(t))**m * val
        l = (1 + ((n + m) / 2.0))
        vn[n, m] = v[n, m] / pow(M[0, 0], l)

    return vn
示例#28
0
 def two_generate(self, e, utility_node):
     varset = deepcopy(self.vars)
     Q = {}
     result = {}
     table = list(itertools.product([True, False], repeat=2))
     for tuple in range(len(table)):
         (i, j) = table[tuple]
         e[utility_node.parents[0]] = i
         e[utility_node.parents[1]] = j
         Q[tuple] = self.enumerate_all(varset, e)
         result[table[tuple]] = Q[tuple] * float(
             utility_node.cpt[table[tuple]])
     return result
示例#29
0
def geometricMoments(pixelList, numMoments):
    numPoints = len(pixelList)

    # Compute moments
    M = createImageF(numMoments, numMoments)
    for m, n in itertools.product(range(0, numMoments), range(0, numMoments)):
        for indexPixel in range(0, numPoints):
            y = (pixelList[indexPixel])[0]
            x = (pixelList[indexPixel])[1]
            val = (pixelList[indexPixel])[2]
            M[n, m] += (x**n) * (y**m) * val

    return M
示例#30
0
文件: benchmark.py 项目: makkus/gopy
    def __init__(self, name, go, perf_p=[], perf_cc=[], perf_pp=[]):
        
        self.name = name
        self.go = go

        if os.path.exists(BENCHMARKS_DIRECTORY+os.sep+name):
            
            if perf_p or perf_cc or perf_pp:
                raise Exception('Benchmark "'+name+'" already exists, you can\'t specify performance options')
            
            with open(BENCHMARKS_DIRECTORY+os.sep+name, 'rb') as f:
                bm = pickle.load(f)
                self.perf_p = bm.perf_p
                self.perf_cc = bm.perf_cc
                self.perf_pp = bm.perf_pp
                self.items = bm.items
                self.series = bm.series
                return 
        else:
        
            if not perf_p and not perf_cc and not perf_pp:
                raise Exception('Benchmark "'+name+'" does not exist, you need to specify performance options (e.g. --perf-p=1,8,16 --perf-cc=1 --perf-pp=1,16,32)')
            
            if perf_p:
                self.perf_p = perf_p
            else:
                self.perf_p = [1]
            
            if perf_cc:
                self.perf_cc = perf_cc
            else:
                self.perf_cc = [1]
                
            if perf_pp:
                self.perf_pp = perf_pp
            else:
                self.perf_pp = [1]

            self.items = []
            self.series = []
            
            # first, we always run the "no-option" globus default, to have a comparison
            self.items.append(BenchmarkItem(0,0,0))
        
            combinantions = itertools.product(self.perf_p, self.perf_cc, self.perf_pp)
        
            for c in combinantions:
                item = BenchmarkItem(c[0], c[1], c[2])
                self.items.append(item)
            
            self.save()
示例#31
0
def computeReferencePoint(edgeImage):
    height, width = len(edgeImage), len(edgeImage[0])

    refPoint = [0, 0]
    edgePoints = []
    for x, y in itertools.product(range(0, width), range(0, height)):
        if edgeImage[y, x] != 0:
            refPoint[0] += y
            refPoint[1] += x
            edgePoints.append((y, x))
    numPts = len(edgePoints)
    refPoint = [int(refPoint[0] / numPts), int(refPoint[1] / numPts)]

    return refPoint, edgePoints
示例#32
0
 def __init__(self, game_title, player_names, strategies, payoffs, outcomes):
     self.game_title = game_title
     self.player_names = player_names
     self.strategies = strategies
     self.payoffs = payoffs
     self.outcomes = outcomes
     self.payoffs.insert(0, ["draw"] + ([0] * len(self.player_names)))
     tmp = self.strategies
     tmp.reverse()
     strategy_profiles = list(itertools.product(*tmp))
     self.strategy_profiles = []
     for (x, y, i) in zip(strategy_profiles, self.outcomes, range(len(strategy_profiles))):
         x = list(x)
         x.reverse()
         self.strategy_profiles.append(x)
def reducer(key, list_of_values):
    # key: order_id
    # value: list of tuples (table, attr)
    recs = {}
    for value in list_of_values:
      table = value[0]
      if not table in recs:
        recs[table] = []
      recs[table].append(value)

    leftTable = recs.values()[0]    
    righTable = recs.values()[1]
    
    for r in itertools.product(leftTable, righTable):
      mr.emit(r[1] + r[0])
示例#34
0
def edgesList(image, shapeImage, backgroundRange):
    edgePixels = []
    height, width = len(image), len(image[0])
    numPoints = len(shapeImage)
    for indexPixel in range(0, numPoints):
        y, x = (shapeImage[indexPixel])[0], (shapeImage[indexPixel])[1]
        edge = False
        for wx, wy in itertools.product(range(-1, 2), range(-1, 2)):
            posX, posY = x + wx, y + wy
            if posY > -1 and posY < height and posX > -1 and posX < width:
                if image[posY, posX] >= backgroundRange[0] and image[
                        posY, posX] <= backgroundRange[1]:
                    edge = True
        if edge:
            edgePixels.append((y, x))
    return edgePixels
示例#35
0
def createSobelKernel(kenrelSize):

    sobelX = createImageF(kenrelSize, kenrelSize)
    sobelY = createImageF(kenrelSize, kenrelSize)

    # Create kernel
    for x, y in itertools.product(range(0, kenrelSize), range(0, kenrelSize)):

        # Smooth
        smoothX = factorial(kenrelSize - 1) / (factorial(kenrelSize - 1 - x) *
                                               factorial(x))
        smoothY = factorial(kenrelSize - 1) / (factorial(kenrelSize - 1 - y) *
                                               factorial(y))

        # Pascal
        if (kenrelSize - 2 - x >= 0):
            p1X = factorial(kenrelSize - 2) / (factorial(kenrelSize - 2 - x) *
                                               factorial(x))
        else:
            p1X = 0

        if (kenrelSize - 2 - y >= 0):
            p1Y = factorial(kenrelSize - 2) / (factorial(kenrelSize - 2 - y) *
                                               factorial(y))
        else:
            p1Y = 0

        # Pascal shift to the right
        xp = x - 1
        if (kenrelSize - 2 - xp >= 0 and xp >= 0):
            p2X = factorial(kenrelSize - 2) / (factorial(kenrelSize - 2 - xp) *
                                               factorial(xp))
        else:
            p2X = 0

        yp = y - 1
        if (kenrelSize - 2 - yp >= 0 and yp >= 0):
            p2Y = factorial(kenrelSize - 2) / (factorial(kenrelSize - 2 - yp) *
                                               factorial(yp))
        else:
            p2Y = 0

        # Sobel
        sobelX[y, x] = smoothX * (p1Y - p2Y)
        sobelY[y, x] = smoothY * (p1X - p2X)

    return sobelX, sobelY
示例#36
0
def computeCoefficients(inputImage):
    height = len(inputImage)
    width = len(inputImage[0])

    # Create coefficients Image. Two floats to represent a complex number
    # Maximum frequency according to sampling
    maxFrequencyW = int(width / 2)
    maxFrequencyH = int(height / 2)
    numCoefficientsW = 1 + 2 * maxFrequencyW
    numCoefficientsH = 1 + 2 * maxFrequencyH
    coefficients = createImageF(numCoefficientsW, numCoefficientsH, 2)

    # Adjust the size of the data to be even
    m = float(width)
    n = float(height)
    if width % 2 == 0:
        m = width + 1
    if height % 2 == 0:
        n = height + 1

    # Fundamental frequency
    ww = (2.0 * pi) / float(m)
    wh = (2.0 * pi) / float(n)

    # Compute values
    for kw in range(-maxFrequencyW, maxFrequencyW + 1):
        printProgress(kw + maxFrequencyW, numCoefficientsW - 1)
        for kh in range(-maxFrequencyH, maxFrequencyH + 1):
            indexInArrayW = kw + maxFrequencyW
            indexInArrayH = kh + maxFrequencyH

            for x, y in itertools.product(range(0, width), range(0, height)):
                coefficients[indexInArrayH,
                             indexInArrayW][0] += inputImage[y, x] * (
                                 cos(x * ww * kw) * cos(y * wh * kh) -
                                 sin(x * ww * kw) * sin(y * wh * kh))
                coefficients[indexInArrayH,
                             indexInArrayW][1] += inputImage[y, x] * (
                                 cos(x * ww * kw) * sin(y * wh * kh) +
                                 sin(x * ww * kw) * cos(y * wh * kh))

    for kw in range(-maxFrequencyW, maxFrequencyW + 1):
        for kh in range(-maxFrequencyH, maxFrequencyH + 1):
            coefficients[indexInArrayH, indexInArrayW][0] /= (m * n)
            coefficients[indexInArrayH, indexInArrayW][1] /= (m * n)

    return coefficients, maxFrequencyW, maxFrequencyH
示例#37
0
def main(subjects):
    import itertools
    encoding = [["F", "L"], "F", "L"]
    level = [["1","2","3"]]
    masks_ = [["L_PPA_enc.nii",  "L_HIPP_enc.nii"], 
              ["L_PPA.nii", "L_FFA.nii"]]
    
    conditions_dict = {
                        "encoding": ["F", "L"],
                        "response": ["C"],
                        "level": ["1"]
                          }
    
    p = itertools.product(masks_, encoding, level)
    
    for opt in p:
        conditions_dict["encoding"] = opt[1]
        conditions_dict["level"] = opt[2]
        mask_name = opt[0]
        
        print opt
        
        analysis(subjects, seed_mask=mask_name, analysis="abs_difference", conditions=conditions_dict)
示例#38
0
def expand(domain,problem,state):
    ret = []
    for (ac_name,action) in domain.actions.items():
        parameters = action.params
        applicable_list = []
        for (p,t) in parameters:
            objects = [po for po,to in problem.objects if to==t] + [po for po,to in domain.constants if to == t]
            applicable_list.append(objects)
        candidates = list(itertools.product(*applicable_list))
        
        for candidate in candidates:
            gpp = {ground(p,action.params,candidate) for p in action.pos_preq}
            gnp = {ground(p,action.params,candidate) for p in action.neg_preq}
            
            check_pos = gpp<=state
            check_neg = len(gnp & state)==0
            applicable = (check_pos and check_neg)
            if applicable:
                gpe = {ground(p,action.params,candidate) for p in action.pos_effects}
                gne = {ground(p,action.params,candidate) for p in action.neg_effects}
                
                n_state = (state | gpe )-gne
                ret.append((ac_name,candidate,n_state))
    return ret
def readIn(fileName):
	inf = open(fileName, "r")
	disNum = int(inf.read(1))
	patNum = int(inf.readline().strip())
	disDict = {} #disDict dict
	sympDict = {} #sympDict dict
	disName=[]
	symName=[]
	
	#reading file, storing diseases and sympDict probabilities
	for i in range(disNum):
		disInfo=inf.readline().split() #String to store disInfo line in a string
		disDict[disInfo[0]]={}  #making disInfo values 0
		disName.append(disInfo[0]); #adding to list of disDict names
		disDict[disInfo[0]]["symp"]=int(disInfo[1])
		disDict[disInfo[0]]["prob"]=float(disInfo[2])
		#print(disDict)
		S4DList=eval(inf.readline()) #making list of symp
		posProb=eval(inf.readline()) #making list of P(s|d)
		negProb=eval(inf.readline()) #making list of P(s|d')
		sympDict[disInfo[0]]={}  #symp(disInfo)=null
		symName.append(S4DList) #adding to list of symptom names
		for j in range(disDict[disInfo[0]]["symp"]):
			sympDict[disInfo[0]][S4DList[j]]={}
			sympDict[disInfo[0]][S4DList[j]]["pos"]=float(posProb[j])
			sympDict[disInfo[0]][S4DList[j]]["neg"]=float(negProb[j])
	outputstr=""
	#reading patients data from file and their calculations
	for i in range(patNum):
		patDict={} #pat dict
		outputstr+="Patient-"+str(i+1)+":\n"
		#print(str1)
		#reading data
		for d in range(disNum):
			patDict[disName[d]]={} #dict within a dict
			patInfo=eval(inf.readline())
			for s in range(disDict[disName[d]]["symp"]):
				patDict[disName[d]][symName[d][s]]=patInfo[s]
		#question 1
		op1={}
		for d in disDict:
			num=disDict[d]["prob"]
			den=1-disDict[d]["prob"]
			for s in sympDict[d]:
				if patDict[d][s]=='T':
					num*=sympDict[d][s]["pos"]
					den*=sympDict[d][s]["neg"]
				elif patDict[d][s]=='F':
					num*=(1-sympDict[d][s]["pos"])
					den*=(1-sympDict[d][s]["neg"])				
			ans=num/(num+den)
			ans=round(ans,4)
			op1[d]=str(ans)			
		#print(op1)
		outputstr+=str(op1)+"\n"
		
		#question 2
		op2={}
		for d in disDict:
			num=disDict[d]["prob"]
			den=1-disDict[d]["prob"]
			unProbList=[]
			unSymList=[]
			permList=[]
			for s in sympDict[d]:
				if patDict[d][s]=='T':
					num*=sympDict[d][s]["pos"]
					den*=sympDict[d][s]["neg"]
				elif patDict[d][s]=='F':
					num*=(1-sympDict[d][s]["pos"])
					den*=(1-sympDict[d][s]["neg"])
				elif patDict[d][s]=='U':
					unSymList.append(s)
			for i in range(len(unSymList)):
				dummy=['T','F']
				permList.append(dummy)
			permList=list(itertools.product(*permList))
			for i in range(len(permList)):
				newNum=1
				newDen=1
				for j in range(len(unSymList)):
					if permList[i][j]=='T':
						newNum*=sympDict[d][unSymList[j]]["pos"]
						newDen*=sympDict[d][unSymList[j]]["neg"]
					elif permList[i][j]=='F':
						newNum*=(1-sympDict[d][unSymList[j]]["pos"])
						newDen*=(1-sympDict[d][unSymList[j]]["neg"])
				ans=(num*newNum)/((num*newNum)+(den*newDen))
				ans=round(ans,4)
				ans="{0:.4f}".format(ans)
				unProbList.append(ans)
			op2[d]=[str((min(unProbList))),str((max(unProbList)))]
		#print(op2)
		outputstr+=str(op2)+"\n"
		
		# question 3
		op3={}
		for d in disDict:
			num=disDict[d]["prob"]
			den=1-disDict[d]["prob"]
			unValList=[]
			unSymList=[]
			maxA=0
			minB=0			
			for s in sympDict[d]:
				if patDict[d][s]=='T':
					num*=sympDict[d][s]["pos"]
					den*=sympDict[d][s]["neg"]
				elif patDict[d][s]=='F':
					num*=(1-sympDict[d][s]["pos"])
					den*=(1-sympDict[d][s]["neg"])
				elif patDict[d][s]=='U':
					unSymList.append(s)
			for i in range(len(unSymList)):
				#unknown is true
				newNum=num*sympDict[d][unSymList[i]]["pos"]
				newDen=den*sympDict[d][unSymList[i]]["neg"]
				ans=newNum/(newNum+newDen)
				if i==0:
					maxA=ans
					unValList.append(unSymList[i])
					unValList.append('T')
					minB=ans
					unValList.append(unSymList[i])
					unValList.append('T')
				else:
					if ans>maxA:
						maxA=ans
						unValList[0]=unSymList[i]
						unValList[1]='T'
					if ans<minB:
						minB=ans
						unValList[2]=unSymList[i]
						unValList[3]='T'
				#unknown is false
				newNum=num*(1-sympDict[d][unSymList[i]]["pos"])
				newDen=den*(1-sympDict[d][unSymList[i]]["neg"])
				ans=newNum/(newNum+newDen)			
				if ans>maxA:
					maxA=ans
					unValList[0]=unSymList[i]
					unValList[1]='F'
				if ans<minB:
					minB=ans
					unValList[2]=unSymList[i]
					unValList[3]='F'
			op3[d]=unValList				
		#print(op3)
		outputstr+=str(op3)+"\n"
	inf.close()
	return outputstr
示例#40
0
 def _get_partition_specs(self, listattr):
     
     prod = itertools.product(*listattr)
     
     return [('None', [item[0]], [item[1]])  for item in prod]
示例#41
0
def beta_stats(mask_area, test_field="encoding", test=["F", "L"], **kwargs):
    
    
    default_config = {
                      "encoding": ["F", "L"],
                      "level": ["3"],
                      "response" :["C"],
                      }

    condition_dir_dict = {
                          "encoding":0,
                          "level":1,
                          "response":2
                          }
    
    encoding = default_config["encoding"]
    level = default_config["level"]
    response = default_config["response"]
    
    items = itertools.product(encoding, level, response)
    
    conditions = ["".join(v) for v in items]
    
    path = "/home/robbis/mount/wkpsy01/fmri/carlo_ofp/0_results/"
    import glob
    
    pattern = "0_beta_%s_%s_total.nii.gz"
    
    maps = dict()
    
    for condition in default_config[test_field]:
        condition_pattern = [v for v in conditions if v.find(condition)!=-1]
        print condition_pattern
        condition_pattern.sort()
        rocfile = glob.glob(os.path.join(path, pattern % (mask_area, "_".join(condition_pattern))))
        print rocfile
        map[condition] = ni.load(rocfile[0])
        
    
    from scipy.stats import ttest_ind
    
    t, p = ttest_ind(map[test[0]].get_data(), map[test[1]].get_data(), axis=3)
    
    q = np.zeros_like(p)
    q[np.logical_not(p == 0)] = 1 - p[np.logical_not(p == 0)]
    t[np.isinf(t)] = 0
    
    p[np.isnan(p)] = 0
    
    def get_image(img):
        return ni.Nifti1Image(img, map[test[0]].affine)
    
    
    def get_name(mask_area, test, map_type):
        pattern = "0_beta_ttest_%s_%s_%s_3.nii.gz" % (mask_area, "_".join(test), map_type)
        return pattern
        
    
    ni.save(get_image(q), os.path.join(path, get_name(mask_area, test, "q")))
    ni.save(get_image(p), os.path.join(path, get_name(mask_area, test, "p")))
    ni.save(get_image(t), os.path.join(path, get_name(mask_area, test, "t")))
def IncrementAlphaHarness_ICs(recalculate = False,
                              num_iterates = 20,
                              Tf   = 1.,
                              tau_chars = [.5,2],
                              mus = [-1,1],
                              step_size = 5.):
    
    sigma = 1.;
    params = array([sigma]);
    amax = 1
    alpha_bounds = [-amax, amax];  
    alpha_bang_bang = lambda x: amax* sign(x)
    alpha_forward = lambda x: arctan(5*x) / (pi/ 2.) * amax
    alpha_null = lambda x: .0*x
    alpha_H1 = lambda x: amax* sign(x)*(abs(x) > 1.)
    
    
    
    dt = .01; num_nodes = 200;
    
    lSolver = FBSolver(dt, Tf, num_nodes, xmin=-5., xmax=5.)
    
    thetas = list( itertools.product(mus, tau_chars))
 
    pThetas = ones(len(thetas)) / len(thetas);
    
    file_name = 'alpha_iterates_uICs_Tf=%.1f'%Tf 
    if recalculate:                
        
        FBSolnsList = []
        xs = lSolver._xs;
        width = 2.0; x_0 = .0;
        pre_ICs = exp(-(xs-x_0)**2 / width**2) / (width * sqrt(pi))
        ICs = pre_ICs / (sum(pre_ICs)*lSolver._dx) 
        
        #Calculate bang-bang reference:
        alphas = lSolver.generateAlphaField(alpha_bang_bang);
        xs, ts, fs, ps, J, grad_J = lSolver.solve(thetas, pThetas,
                                                  params, alphas, 
                                                  ICs,
                                                  visualize=False)
        (FBSolution(params, thetas, pThetas, xs, ts,
                     fs, ps, alphas, grad_J, J)).save('alpha_bang_bang')
        print 'J_bang_bang = ', J
        
        #Calculate null reference:
        alphas = lSolver.generateAlphaField(alpha_null);
        xs, ts, fs, ps, J, grad_J = lSolver.solve(thetas, pThetas,
                                                  params, alphas, 
                                                  ICs,
                                                  visualize=False)
        (FBSolution(params, thetas, pThetas, xs, ts,
                     fs, ps, alphas, grad_J, J)).save('alpha_null')

        #NOw reset to the Null Solution:
        print 'ICs for alphas = bang-null-bang'
        alphas = lSolver.generateAlphaField(alpha_H1);

        for ak in xrange(num_iterates):

            xs, ts, fs, ps, J, grad_J = lSolver.solve(thetas, pThetas,
                                                  params, alphas, 
                                                  ICs,
                                                  visualize=False)
            print ak, J
            fbSoln = FBSolution(params, thetas, pThetas,
                                 xs, ts, fs, ps,
                                  alphas, grad_J, J)
            FBSolnsList.append(fbSoln)
            
            #calculate next alpha field:
            alphas = incrementAlpha(alphas, grad_J,
                                    step_size=step_size,
                                    alpha_max=amax)
        
        FBIterates(FBSolnsList).save(file_name)
        #//Resimulate
    
    #Load: 
    FBSolnsList = (FBIterates.load(file_name))._iteratesList
    num_iterates = len(FBSolnsList);
    
    
    #Visualize controls:
#    tks = [1, 20, 40,60,80, 99]
#    tks = array([1, 3, 10, 40, 60, 90, 97, 99])*int(Tf)
    tks = array([ 5, 20, 50, 80, 95 ])*int(Tf)

#    aks = [5, 10, 14, 16, 18, len(FBSolnsList)-1];
#    aks = [16, num_iterates - 1];
    aks = [0, int((num_iterates - 1)/2), num_iterates - 1];



    soln_fig = figure(figsize = (17,18));
    subplots_adjust(hspace = .2,wspace = .35,
                     left=.05, right=1.,
                     top = .95, bottom = .05)
    num_rows = len(tks);
    num_cols = 3;
    for row_idx, tk in enumerate(tks):
        for ak in aks:
            FBSoln = FBSolnsList[ak]
            plt_idx = row_idx*num_cols;
            xs = FBSoln._xs;
            ts = FBSoln._ts;
            fs, ps, alphas = FBSoln._fs, FBSoln._ps,FBSoln._alphas;
            
            tc_idx = 0;
            
            #fs: 
            ax = soln_fig.add_subplot(num_rows, num_cols, plt_idx+1)
            ax.plot(xs, fs[tc_idx, tk,:], label='k=%d'%ak); 
            if tk ==  tks[1]:
                ax.set_ylabel(r'$f_{\mu=%.1g, \tau=%.1g}$'%(thetas[tc_idx][0],thetas[tc_idx][1]),
                                                    fontsize = xlabel_font_size)
#            ax.set_ylim((.0, 2.0))
            #ps: 
            ax = soln_fig.add_subplot(num_rows, num_cols, plt_idx+2)
            ax.plot(xs, ps[tc_idx, tk,:], label='k=%d'%ak); 
            if tk ==  tks[1]:
                ax.set_ylabel(r'$p_{\mu=%.1g, \tau=%.1g}$'%(thetas[tc_idx][0], thetas[tc_idx][1]),
                                                    fontsize = xlabel_font_size)
#            ax.set_ylim((.0, 2.0))
            
            
            #alphas:
            ax = soln_fig.add_subplot(num_rows, num_cols, plt_idx+3)
            ax.plot(xs, alphas[tk,:], label='k=%d'%ak); 
            if tk == tks[1]:
                ax.set_ylabel(r'$\alpha_k$', fontsize = xlabel_font_size)
            
        #common to all drawing:
        for col_idx in xrange(1,num_cols+1):
            ax = soln_fig.add_subplot(num_rows, num_cols, plt_idx+col_idx)
            ax.set_title('t=%.2f'%ts[tk], fontsize = xlabel_font_size)
#            ax.vlines(0,ax.get_ylim()[0], ax.get_ylim()[1],linestyles='dashed')
#            ax.hlines(0,ax.get_xlim()[0], ax.get_xlim()[1],linestyles='dashed')
            ax.set_xlim(xs[0], xs[-1])
            if tk == tks[0]:
                ax.legend(prop={'size':label_font_size})
            if tk == tks[-1]:
                ax.set_xlabel('$x$', fontsize = xlabel_font_size);
            else:
                for x in ax.get_xticklabels():
                    x.set_visible(False)
                    
    #J figure:
    Js = [fb._J for fb in FBSolnsList];
    fbBangSoln = FBSolution.load('alpha_bang_bang')
    fbNullSoln = FBSolution.load('alpha_null')
    J_null  = fbNullSoln._J;
    J_bangbang = fbBangSoln._J;
    
    J_fig = figure(figsize = (17,6));
    subplots_adjust(left=.025, right=1.,
                     top = .95, bottom = .05)
    ax = J_fig.add_subplot(111);
    J_fig.subplots_adjust(left=.025, right=1.,
                     top = .95, bottom = .05)
    ax = J_fig.add_subplot(111);
    ax.plot(Js, 'b', label='Gradient Ascent');
    ax.plot(J_bangbang*ones_like(Js), 'r', label='Bang-Bang') 
    ax.plot(J_null*ones_like(Js), 'g', label=r'Do nothing ($\alpha =0$)') 
    ax.set_ylim([0., ceil(J_bangbang) ]);
    ax.legend(loc = 'lower right', prop={'size':label_font_size})
#   
    
    ax.set_ylabel(r'$J_{k}$', fontsize = xlabel_font_size);
    ax.set_xlabel('k', fontsize = xlabel_font_size)
    ax.set_title('$J$ evolution', fontsize = xlabel_font_size);
        
    #Save figs:
    for fig, fig_name in zip([soln_fig, J_fig],
                             ['FB_alpha_iterates_uICs_%d'%len(tks),
                              'FB_J_iterates_uICs']):       
#        fig.canvas.manager.window.showMaximized()
        lfig_name = os.path.join(FIGS_DIR, fig_name + '_Tf=%d.pdf'%(ceil(Tf)))
        print 'saving to ', lfig_name
        save_ret_val = fig.savefig(lfig_name, dpi=300)
示例#43
0
# encoding=UTF-8
'''
Created on 2013-7-18
@author: Administrator
'''
from timeit import itertools
from random import random, Random
import datetime

src = list(itertools.product(range(0, 10), repeat=5))
random = Random()
tdelta = datetime.timedelta(seconds=1)

def gen(filename, start, end, filters):
    
    with open(filename, 'w') as f:
        dt = start
        while dt < end:
            f.write(dt.strftime("%Y%m%d%H%M%S") + ":" + u",".join(map(unicode, random.choice(src))) + "\n")
            dt = dt + tdelta
            if filters is not None and dt < end and filters(dt):
                print 'next ' + dt.strftime("%Y-%m-%d %H:%M:%S")

    print 'finish write to ' + filename + "from " + start.strftime("%Y-%m-%d %H:%M:%S") + " to " + end.strftime("%Y-%m-%d %H:%M:%S")

if __name__ == '__main__':

    gen(r"D:\test\hadoop_src\2013",
        datetime.datetime(2013, 01, 01, 0, 0, 0),
        datetime.datetime(2013, 02, 01, 0, 0, 0),
        lambda dt:dt.hour == 0 and dt.minute == 0 and dt.second == 0)