Пример #1
0
 def __init__(self, *twod_array):
     if isinstance(twod_array[0], Matrix):
         self.theMatrix = twod_array[0]
     elif isinstance(twod_array[0], M):
         self.theMatrix = twod_array[0].theMatrix
     else:
         self.theMatrix = Matrix(twod_array)
def pythonToJamaMatrix(m):
    a = Matrix(
        jarray.array([[0] * len(m) for id in range(len(m))],
                     java.lang.Class.forName("[D")))
    for x, col in enumerate(m):
        for y, val in enumerate(col):
            a.set(x, y, m[x][y])
    return a
Пример #3
0
	def __init__(self,*twod_array):
		if isinstance(twod_array[0],Matrix):
			self.theMatrix = twod_array[0]
		elif isinstance(twod_array[0],M):
			self.theMatrix = twod_array[0].theMatrix
		else:
			self.theMatrix =Matrix(twod_array)
Пример #4
0
def fit_ellipse(coords):
    """find a best fit ellipse (least squares sense) from a list of co-ordinates"""
    # based on http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html
    xs = [float(x) for (x, y) in coords]
    xmean = sum(xs) / len(xs)
    xs = [x - xmean for x in xs]
    ys = [float(y) for (x, y) in coords]
    ymean = sum(ys) / len(ys)
    ys = [y - ymean for y in ys]

    N = 6
    d1 = [x * x for x in xs]
    d2 = [x * y for (x, y) in zip(xs, ys)]
    d3 = [y * y for y in ys]
    d4 = [x for x in xs]
    d5 = [y for y in ys]
    d6 = [1 for x in xs]
    d = sum([d1, d2, d3, d4, d5, d6], [])
    D = Matrix(d, len(d1))

    S = D.transpose().times(D)
    C = Matrix(6, 6)
    C.set(0, 2, 2)
    C.set(2, 0, 2)
    C.set(1, 1, -1)
    eig = EigenvalueDecomposition(S.inverse().times(C.transpose()))
    E = eig.getRealEigenvalues()
    #print("eigenvalues = " + str([('%.2E' % e) for e in E]));
    V = eig.getV()
    #print("eigenvectors = ");
    #for idx in range(0,N):
    #	print(str([('%.2E' % v) for v in vs[N * idx : (idx + 1) * N]]));
    absE = [abs(e) for e in E]
    n = absE.index(max(absE))
    a = [V.get(idx, n) for idx in range(0, N)]

    (xc, yc) = ellipse_center(a)
    xc += xmean
    yc += ymean
    centre = (xc, yc)
    angle = ellipse_angle_of_rotation(a)
    axes_l = ellipse_axis_length(a)
    return centre, angle, axes_l
def IndexCalculusFinale(B, p, alpha, s):
    # Bangkitkan Factor Base
    i = 0
    fb = [0] * s

    while (i < s):
        fb[i] = myFactorbase[i]
        i += 1
    bound = p - 2
    failedList = [0]
    expList = len(fb) * [0]
    LFB = [[0] * len(fb) for x in range(len(fb))]
    fbLength = len(fb)
    i = 0
    while (i < fbLength):
        exp = randint(2, bound)
        while ((expList.count(exp) > 0 and failedList.count[exp] > 0)
               or exp <= 2):
            exp = randint(2, bound)
        realMatrixExp = MatrixUtils.createRealMatrix(fbLength, 1)
        realMatrixExp.addToEntry(i, 0, exp)
        beta = pow(alpha, exp)
        beta = beta % p
        j = fbLength
        for j in range(fbLength - 1, -1, -1):
            if (j == 0 and beta > fb[fbLength - 1]):
                x = 0
                while (x < fbLength):
                    LFB[i][x] = 0
                    x += 1
                failedList.append(expList[i])
                i = i - 1
                pass
            else:
                while (beta % fb[j] == 0 and beta > 1):
                    LFB[i][j] += 1
                    beta = beta / fb[j]
                if (beta == 1):
                    myTemp = [0] * len(fb)
                    for k in range(0, len(myTemp)):
                        myTemp[k] = LFB[i][k]
                    if (myTemp.count(0) > fbLength - 2):
                        x = 0
                        while (x < fbLength):
                            LFB[i][x] = 0
                            failedList.append(expList[i])
                            expList[i] = exp
                            x += 1
                        i = i - 1
                        del myTemp
                        break
                    else:
                        break
                else:
                    expList[i] = exp
                    continue
        i += 1
    global gIC
    gIC = LFB
    global gGamma
    gGamma = expList

    #Java Matrix
    matrixFBL = Matrix(LFB)
    matrixExp = Matrix(expList, len(expList))
    #matrixFBLogValue = chol(matrixFBL, matrixExp)
    matrixFBLogValue = matrixFBL.solve(matrixExp)
    FBlog = matrixFBLogValue.getColumnPackedCopy()
    ### tahap terakhir
    mylength = len(fb)
    GammaIndex = [0] * len(fb)

    failedList = [0]
    exp = randint(2, p - 2)

    gamma = pow(alpha, exp)

    gamma = gamma % p
    gamma = (gamma * B) % p
    global ohm
    ohm = gamma

    i = mylength - 1
    maX = len(fb) - 1
    while (gamma > 1):
        if (i == 0 and gamma > fb[maX]):
            GammaIndex = [0] * len(fb)
            exp = randint(2, p - 2)
            gamma = pow(alpha, exp)
            gamma = gamma % p
            gamma = (gamma * B) % p
            i = mylength - 1
        elif (gamma % fb[i] == 0):
            gamma = gamma / fb[i]
            GammaIndex[i] += 1
        else:
            i -= 1
            continue
    temp = 0
    i = 0
    for i in range(0, len(FBlog)):
        temp += (FBlog[i] * GammaIndex[i])
        i += 1
    return (temp - exp) % (p - 1)
Пример #6
0
def IndexCalculusFinale(B, p, alpha, s):
    global primus
    global akP
    global be

    primus = p
    akP = alpha
    be = B

    ### Bangkitkan Factor Base
    i = 0
    #fb=[0]*s
    fb = []
    i = 0
    while (myFactorbase[i] <= s):
        fb.append(myFactorbase[i])
        i += 1
    print "fb = ", fb
    """
    while(s>myFactorbase[i]):
            i+=1
            if(i==999):
                break
            
    fb=[0]*i
    i=0
    while(s>myFactorbase[i]):
            #i+=1
            fb[i]=myFactorbase[i]
            i+=1
            if(i==999):
                break
    """

    global gFB
    gFB = fb
    global drx
    drx = len(fb)

    bound = p - 2
    failedList = [0]
    expList = len(fb) * [0]
    LFB = [[0] * len(fb) for x in range(len(fb))]

    i = 0
    realMatrixExp = MatrixUtils.createRealMatrix(
        len(fb), 1)  #RealMatrix.createMatrix(1, fbLength, None)
    while (i < len(fb)):
        exp = randint(2, bound)
        while ((expList.count(exp) > 0 and failedList.count[exp] > 0)
               or exp <= 2):
            exp = randint(2, bound)
        realMatrixExp.addToEntry(i, 0, exp)

        beta = pow(alpha, exp)
        beta = beta % p
        j = len(fb)
        for j in range(len(fb) - 1, -1, -1):
            if (j == 0 and beta > fb[len(fb) - 1]):
                x = 0
                while (x < len(fb)):
                    LFB[i][x] = 0
                    x += 1
                failedList.append(expList[i])
                i = i - 1
                pass
            else:
                while (beta % fb[j] == 0 and beta > 1):
                    LFB[i][j] += 1
                    beta = beta / fb[j]
                if (beta == 1):
                    myTemp = [0] * len(fb)
                    for k in range(0, len(myTemp)):
                        myTemp[k] = LFB[i][k]
                    if (myTemp.count(0) > len(fb) - 2):
                        x = 0
                        while (x < len(fb)):
                            LFB[i][x] = 0
                            failedList.append(expList[i])
                            expList[i] = exp
                            x += 1
                        i = i - 1
                        del myTemp
                        break
                    else:
                        break
                else:
                    expList[i] = exp
                    continue
        i += 1
    global gIC
    gIC = LFB
    global gGamma
    gGamma = expList
    print LFB
    print expList
    """
    for i in range(0, len(LFB)):
        if(i==0):
            print"{",
        for j in range(0, len(LFB)):
            if(j==0):
                print "{",
            print LFB[i][j],",",
            if(j==(len(LFB)-1)):
                print expList[i],
                print "}",","
            
            if(i==len(LFB)-1 and j==len(LFB)-1):
                print "};"
    
    """
    global gRawIC
    gRawIC = LFB
    #Java Matrix
    matrixFBL = Matrix(LFB)
    matrixExp = Matrix(expList, len(expList))
    #matrixFBLogValue = chol(matrixFBL, matrixExp)
    matrixFBLogValue = matrixFBL.solve(matrixExp)
    FBlog = matrixFBLogValue.getColumnPackedCopy()
    global gReductedIC
    gReductedIC = FBlog

    #apache Commons Math 3
    """
    realMatrixLFB = MatrixUtils.createRealMatrix(fbLength, fbLength) #RealMatrix.createMatrix(1, fbLength, None)
    for i in range(0, fbLength):
        for j in range(0, fbLength):
            realMatrixLFB.addToEntry(i,j,LFB[i][j])
    #decomposition = QRDecomposition (realMatrixLFB).getSolver()
    decomposition = LUDecomposition(realMatrixLFB).getSolver()
    #decomposition =  myEigen(realMatrixLFB).getSolver()
    #decomposition = CholeskyDecomposition(realMatrixLFB).getSolver()
    mlg = decomposition.solve(realMatrixExp)
    mlg = mlg.transpose()
    mlg = mlg.getRow(0)
    FBlog = mlg
    """

    ### tahap terakhir
    mylength = len(fb)
    newp = p - 1
    GammaIndex = [0] * len(fb)

    failedList = [0]
    exp = randint(2, p - 2)

    randomPow = exp
    global randomPow
    gamma = pow(alpha, exp)

    randomB = gamma % p
    global randomB

    gamma = gamma % p
    gamma = (gamma * B) % p
    global ohm
    ohm = gamma

    print "init gamma : ", gamma

    #
    #logger.txt
    #

    i = mylength - 1
    maX = len(fb) - 1
    #print "i=",i
    while (gamma > 1):
        if (i == 0 and gamma > fb[maX]):
            GammaIndex = [0] * len(fb)
            exp = randint(2, p - 2)
            gamma = pow(alpha, exp)
            gamma = gamma % p
            gamma = (gamma * B) % p
            i = mylength - 1
        elif (gamma % fb[i] == 0):
            gamma = gamma / fb[i]
            GammaIndex[i] += 1
        else:
            i -= 1
            continue
    temp = 0
    global myReporter
    myReporter = ""
    global gRICsum
    gRICsum = GammaIndex

    i = 0
    for i in range(0, len(FBlog)):
        myReporter += str(GammaIndex[i])
        myReporter += "*log"
        myReporter += str(fb[i])
        myReporter += " = "
        myReporter += str(GammaIndex[i])
        myReporter += "*"
        myReporter += str(FBlog[i])
        myReporter += " = "
        myReporter += str(FBlog[i] * GammaIndex[i])
        myReporter += "\n"
        print GammaIndex[i], "*log", fb[i], "=", GammaIndex[i], "*", FBlog[
            i], "=", FBlog[i] * GammaIndex[i]
        temp += (FBlog[i] * GammaIndex[i])

        i += 1
        if (i == len(fb)):
            print "---------------------------------------------------"
    temp = (temp - exp)
    temp = temp % newp
    global gloc
    gloc = temp

    return temp
m = imp.getProcessor().getPixels()
m2 = [val for val in m]
L = [m2[i:i + imp.width] for i in range(0, len(m2), imp.width)]
imp.close()

# reshape image stack as an n x m matrix
n_slices = imp2.getStack().getSize()
I = []
for i in range(1, n_slices + 1):
    imp2.setSlice(i)
    n = imp2.getProcessor().getPixels()
    n2 = [val for val in n]
    I.append(n2)

# construct Jama matrices and calculate normals
B = Matrix(L)
C = Matrix(I)
kN = B.solve(C).getColumnPackedCopy()  # calculate normals via least squares

#return matrices to images
ipFloat = FloatProcessor(3, imp2.height * imp2.width, kN)
impa = ImagePlus("kN", ipFloat)
impa.show()

#reshape as using montage and reslice commands (need a better way to do this)
IJ.run(impa, "Montage to Stack...",
       "images_per_row=1 images_per_column=%d border=0" % imp2.height)
impb = IJ.getImage()
IJ.run("Reslice [/]...", "output=1.000 start=Left avoid")
impc = IJ.getImage()
Пример #8
0
    #----------------------
    sizes_X_arr.append(xRMS_Size)
    #--------elements of the transport matrix
    a11 = mtrx.getElem(0, 0)
    a12 = mtrx.getElem(0, 1)
    a16 = mtrx.getElem(0, 5)
    matrx_all_X.append([a11**2, 2 * a11 * a12, a12**2, a16**2])

#=========================================
#  Only x-axis analysis
#=========================================
sigma_rel_err = 0.01

n_ws = len(matrx_all_X)

mMatrX = Matrix(matrx_all_X, n_ws, 4)

sigma2Vector = Matrix(n_ws, 1)
weightM = Matrix.identity(n_ws, n_ws)

for ind in range(n_ws):
    sigma = sizes_X_arr[ind]
    sigma2Vector.set(ind, 0, sigma**2)
    err2 = (2 * sigma * sigma * sigma_rel_err)**2
    weightM.set(ind, ind, 1.0 / err2)

#=== mwmMatr = (M^T*W*M) =======
mwmMatr = ((mMatrX.transpose()).times(weightM)).times(mMatrX)

#=== corr2ValMatr = [(M^T*W*M)^-1] * M^T * W * Vector(sigma**2)
corr2ValMatr = (((mwmMatr.inverse()).times(
Пример #9
0
class M:

	def __init__(self,*twod_array):
		if isinstance(twod_array[0],Matrix):
			self.theMatrix = twod_array[0]
		elif isinstance(twod_array[0],M):
			self.theMatrix = twod_array[0].theMatrix
		else:
			self.theMatrix =Matrix(twod_array)

	def __add__(self,other):
		if self.isaMatrix(other):
			return M(self.theMatrix.plus(self.extractMatrix(other)))
		elif isinstance(other,PyInteger):
			out = M(self.theMatrix.copy())
			for i in range(len(out)):
				out[i] = self[i] + other
			return out			
		#assume a sequence or tuple
		else:
			out = M(self.theMatrix.copy())
			for i in range(len(other)):
				out[i] = self[i] + other[i]
			return out

	def __radd__(self,other):
		if self.isaMatrix(other):
			return M(self.theMatrix.plus(self.extractMatrix(other)))
		elif isinstance(other,PyInteger):
			out = M(self.theMatrix.copy())
			for i in range(len(out)):
				out[i] = self[i] + other
			return out			
		#assume a sequence or tuple
		else:
			out = M(self.theMatrix.copy())
			for i in range(len(other)):
				out[i] = self[i] + other[i]
			return out

	def __iadd__(self,other):
		temp = self.extractMatrix(self.__add__(other))
		self.theMatrix = temp
		return self

	def __sub__(self,other):
		if self.isaMatrix(other):
			return M(self.theMatrix.minus(self.extractMatrix(other)))
		elif isinstance(other,PyInteger):
			out = M(self.theMatrix.copy())
			for i in range(len(out)):
				out[i] = self[i] - other
			return out			
		#assume a sequence or tuple
		else:
			out = M(self.theMatrix.copy())
			for i in range(len(other)):
				out[i] = self[i] - other[i]
			return out

	def __rsub__(self,other):
		if self.isaMatrix(other):
			return M(self.theMatrix.minus(self.extractMatrix(other)))
		elif isinstance(other,PyInteger):
			out = M(self.theMatrix.copy())
			for i in range(len(out)):
				out[i] = other - self[i]
			return out			
		#assume a sequence or tuple
		else:
			out = M(self.theMatrix.copy())
			for i in range(len(other)):
				out[i] = other[i] - self[i]
			return out

	def __isub__(self,other):
		temp = self.extractMatrix(self.__sub__(other))
		self.theMatrix = temp
		return self

	def __mul__(self,other):
		if isinstance(other,M):
			return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
		elif isinstance(other,Matrix):
			return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
		elif type(other) == type([]):
			out = M(self.theMatrix.copy())
			for i in range(len(other)):
				out.__setitem__(i,self.__getitem__(i) * other[i])
			return out
		else:
			return M(self.theMatrix.times(other))

	def __rmul__(self,other):
		if isinstance(other,M):
			return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
		elif isinstance(other,Matrix):
			return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
		elif type(other) == type([]):
			out = M(self.theMatrix.copy())
			for i in range(len(other)):
				out.__setitem__(i,self.__getitem__(i) * other[i])
			return out
		else:
			return M(self.theMatrix.times(other))

	def __imul__(self,other):
		temp = self.extractMatrix(self.__mul__(other))
		self.theMatrix = temp
		return self

	def cross(self,other):
		return self.__mul__(other)

	def dot(self,other):
		return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))

	def __getitem__(self,key):
		out = []
		rows = self.theMatrix.getColumnDimension()
		if isinstance(key,PySlice):
			start = key.start
			step = key.step
			stop = key.stop
			if start == None:
				start = 0
			if stop == None:
				stop = len(self)
			for i in range(start,stop,step):
				a,b = divmod(i,rows)
				out.append(self.theMatrix.get(a,b))
		if isinstance(key,PyTuple):
			if len(key) == 1:
				for i in range(key[0]):
					a,b = divmod(i,rows)
					out.append(self.theMatrix.get(a,b))
			if len(key) == 2:
				for i in range(key[0],key[1]):
					a,b = divmod(i,rows)
					out.append(self.theMatrix.get(a,b))
			elif len(key) == 3:
				for i in range(key[0],key[1],key[2]):
					a,b = divmod(i,rows)
					out.append(self.theMatrix.get(a,b))
		if isinstance(key,PyInteger):
			a,b = divmod(key,rows)
			out = self.theMatrix.get(a,b)
		return out

	def __setitem__(self,key,value):
		cols = self.theMatrix.getColumnDimension()
		a,b = divmod(key,cols)
		return self.theMatrix.set(a,b,value)

	def __len__(self):
 		return self.theMatrix.getColumnDimension()*self.theMatrix.getRowDimension()

	def __str__(self):
		output =  ""
		for i in range(self.theMatrix.getRowDimension()):
			if i == 0:
				output = output +"["
			for j in range(self.theMatrix.getColumnDimension()):
				if j == 0:
					output = output +"["
				output = output + Double.toString(self.theMatrix.get(i,j))
				if (j == (self.theMatrix.getColumnDimension() -1)):
					output = output +"]"
				else:
					output = output + ", "
			if (i == (self.theMatrix.getRowDimension() -1)):
				output = output +"]"
			else:
				output = output + ", "
		return output

	def __repr__(self):
		return self.__str__()

	def __call__(self):
		return self.__str__()

	#also will want every method supplied by Jama.Matrix class

	def extractMatrix(self,other):
		if isinstance(other, Matrix):
			return other
		elif isinstance(other, M):
			return other.theMatrix

	def isaMatrix(self,other):
		if isinstance(other, Matrix):
			return 1
		elif isinstance(other, M):
			return 1
		else:
			return 0
Пример #10
0
	def runErrorsCalculator(self):
		# this method should be preceded by calculateDiff2(). All trajectories should be ready.
		tr_twiss_analysis_controller = self.linac_wizard_document.tr_twiss_analysis_controller
		transverse_twiss_fitting_controller = tr_twiss_analysis_controller.transverse_twiss_fitting_controller
		init_and_fit_params_controller = transverse_twiss_fitting_controller.init_and_fit_params_controller		
		final_twiss_params_holder = init_and_fit_params_controller.final_twiss_params_holder			
		fit_param_index = tr_twiss_analysis_controller.fit_param_index
		accStatesKeeper = tr_twiss_analysis_controller.accStatesKeeper
		#---- fit_err_text - in %
		size_accuracy = init_and_fit_params_controller.fit_err_text.getValue()/100.
		#matrices to keep [m11^2,2*m11*m12,m12^2] raws
		mMatrX0 = [] 
		mMatrY0 = []	
		weghtVectorX = []
		weghtVectorY = []
		sizesVectorX = []
		sizesVectorY = []	
		for accState in accStatesKeeper.getAccStatesArr():
			if(accState.isOn):
				traj = accState.scenario.getTrajectory()
				for size_record in accState.size_hor_record_arr:
					if(not size_record.isOn): continue
					size = size_record.gauss_sigma
					if(fit_param_index == 1): size = size_record.custom_gauss_sigma
					if(fit_param_index == 2): size = size_record.custom_rms_sigma
					ws_node = size_record.ws_node
					probe_state =  accState.traj.stateForElement(ws_node.getId())
					m = probe_state.getResponseMatrix()
					mMatrX0.append([m.getElem(0,0)*m.getElem(0,0),2*m.getElem(0,0)*m.getElem(0,1),m.getElem(0,1)*m.getElem(0,1)])
					weghtVectorX.append(1./(4.0*size**4*size_accuracy**2))
					sizesVectorX.append(size)
				for size_record in accState.size_ver_record_arr:
					if(not size_record.isOn): continue
					size = size_record.gauss_sigma
					if(fit_param_index == 1): size = size_record.custom_gauss_sigma
					if(fit_param_index == 2): size = size_record.custom_rms_sigma
					ws_node = size_record.ws_node
					probe_state =  accState.traj.stateForElement(ws_node.getId())
					m = probe_state.getResponseMatrix()
					mMatrY0.append([m.getElem(2,2)*m.getElem(2,2),2*m.getElem(2,2)*m.getElem(2,3),m.getElem(2,3)*m.getElem(2,3)])
					weghtVectorY.append(1./(4.0*size**4*size_accuracy**2))
					sizesVectorY.append(size)	
		#---from Python arr to Matrix
		if(len(sizesVectorX) < 3 or len(sizesVectorY) < 3):
			print "debug There is not enough data! We have only Nx=",len(sizesVectorX)," and Ny=",len(sizesVectorY)
			final_twiss_params_holder.setParamsErr(0,0.,0.,0.)
			final_twiss_params_holder.setParamsErr(1,0.,0.,0.)		
			init_and_fit_params_controller.finalTwiss_table.getModel().fireTableDataChanged()			
			return
		mMatrX = Matrix(mMatrX0,len(mMatrX0),3)
		mMatrY = Matrix(mMatrY0,len(mMatrY0),3)
		#=== mwmMatr = (M^T*W*M) =======
		mwmMatrX = Matrix(3,3)
		for i0 in range(3):
			for i1 in range(3):
				sum_val = 0.
				for j in range(len(weghtVectorX)):
					sum_val +=  mMatrX.get(j,i0)*weghtVectorX[j]*mMatrX.get(j,i1)					
				mwmMatrX.set(i0,i1,sum_val)
		mwmMatrY = Matrix(3,3)
		for i0 in range(3):
			for i1 in range(3):
				sum_val = 0.
				for j in range(len(weghtVectorY)):
					sum_val +=  mMatrY.get(j,i0)*weghtVectorY[j]*mMatrY.get(j,i1)					
				mwmMatrY.set(i0,i1,sum_val)				
		#print "debug Matrix X det =",mwmMatrX.det(),mwmMatrX.print(15,5)
		#print "debug Matrix Y det =",mwmMatrY.det(),mwmMatrY.print(15,5)	
		errorMatrix_X = mwmMatrX.inverse()
		errorMatrix_Y = mwmMatrY.inverse()
		#correlation results [<x^2>, <x*xp>, <xp^2>] [<y^2>, <y*yp>, <yp^2>]
		correlValsVector_X = [0.,0.,0.]	
		for i0 in range(3):
			for i1 in range(3):
				for iws in range(len(weghtVectorX)):
					correlValsVector_X[i0] += errorMatrix_X.get(i0,i1)*mMatrX.get(iws,i1)*weghtVectorX[iws]*(sizesVectorX[iws])**2
		correlValsVector_Y = [0.,0.,0.]	
		for i0 in range(3):
			for i1 in range(3):
				for iws in range(len(weghtVectorY)):
					correlValsVector_Y[i0] += errorMatrix_Y.get(i0,i1)*mMatrY.get(iws,i1)*weghtVectorY[iws]*(sizesVectorY[iws])**2
		#--------Errors for values [ <x2>, <x*xp>, <xp2>]		
		correlErrValsVectorX = [0.,0.,0.]
		correlErrValsVectorY = [0.,0.,0.]
		for i0 in range(3):
			#print "debug i=",i0," matr X(i,i) = ",errorMatrix_X.get(i0,i0)
			#print "debug i=",i0," matr Y(i,i) = ",errorMatrix_Y.get(i0,i0)
			correlErrValsVectorX[i0] = math.sqrt(math.fabs(errorMatrix_X.get(i0,i0)))
			correlErrValsVectorY[i0] = math.sqrt(math.fabs(errorMatrix_Y.get(i0,i0)))
		res_tuple = (correlValsVector_X,correlErrValsVectorX,correlValsVector_Y,correlErrValsVectorY)
		([x2,x_xp,xp2],[x2_err,x_xp_err,xp2_err],[y2,y_yp,yp2],[y2_err,y_yp_err,yp2_err]) = res_tuple
		emittX = math.sqrt(math.fabs(x2*xp2 - x_xp**2))
		emittY = math.sqrt(math.fabs(y2*yp2 - y_yp**2))
		betaX = x2/emittX
		betaY = y2/emittY
		alphaX = - x_xp/emittX
		alphaY = - y_yp/emittY
		emittX_err = math.fabs(math.sqrt((xp2*x2_err/(2*emittX))**2 + (x2*xp2_err/(2*emittX))**2 + (x_xp*x_xp_err/emittX)**2))
		emittY_err = math.fabs(math.sqrt((yp2*y2_err/(2*emittY))**2 + (y2*yp2_err/(2*emittY))**2 + (y_yp*y_yp_err/emittY)**2))
		betaX_err = math.fabs(math.sqrt((x2_err/emittX)**2 + (x2*emittX_err/(emittX**2))**2))
		betaY_err = math.fabs(math.sqrt((y2_err/emittY)**2 + (y2*emittY_err/(emittY**2))**2))
		alphaX_err = math.fabs(math.sqrt((x_xp_err/emittX)**2 + (x_xp*emittX_err/(emittX**2))**2))
		alphaY_err = math.fabs(math.sqrt((y_yp_err/emittY)**2 + (y_yp*emittY_err/(emittY**2))**2))
		print "======== one pass knob error analysis results ============="
		print "<x^2>,<x*xp>,<xp^2> = (%12.5g +- %10.3g) (%12.5g +- %10.3g) (%12.5g +- %10.3g)"%(x2,x2_err,x_xp,x_xp_err,xp2,xp2_err) 		
		print "<y^2>,<y*yp>,<yp^2> = (%12.5g +- %10.3g) (%12.5g +- %10.3g) (%12.5g +- %10.3g)"%(y2,y2_err,y_yp,y_yp_err,yp2,yp2_err) 
		print "==========================================================="
		final_twiss_params_holder.setParamsErr(0,0.,0.,0.)
		final_twiss_params_holder.setParamsErr(1,0.,0.,0.)	
		if(x2 < 0. or xp2 < 0. or y2 < 0. or yp2 < 0. or x2_err < 0. or xp2_err < 0. or y2_err < 0. or yp2_err < 0.): 
			final_twiss_params_holder.setParamsErr(0,0.,0.,0.)
			final_twiss_params_holder.setParamsErr(1,0.,0.,0.)		
			init_and_fit_params_controller.finalTwiss_table.getModel().fireTableDataChanged()
			return
		x_err = math.sqrt(x2_err)/(2.*math.sqrt(x2))
		xp_err = math.sqrt(xp2_err)/(2.*math.sqrt(xp2))
		y_err = math.sqrt(y2_err)/(2.*math.sqrt(y2))
		yp_err = math.sqrt(yp2_err)/(2.*math.sqrt(yp2))
		print "sqrt(<x^2>),<x*xp>,sqrt(<xp^2>) = (%12.5g +- %10.3g) (%12.5g +- %10.3g) (%12.5g +- %10.3g)"%(math.sqrt(x2),x_err,x_xp,x_xp_err,math.sqrt(xp2),xp_err) 		
		print "sqrt(<y^2>),<y*yp>,sqrt(<yp^2>) = (%12.5g +- %10.3g) (%12.5g +- %10.3g) (%12.5g +- %10.3g)"%(math.sqrt(y2),y_err,y_yp,y_yp_err,math.sqrt(yp2),yp_err) 		
		print "==========================================================="
		print "X alpha, beta, emitt = (%12.5g +- %10.3g) (%12.5g +- %10.3g) (%12.5g +- %10.3g)"%(alphaX,alphaX_err,betaX,betaX_err,emittX,emittX_err) 
		print "Y alpha, beta, emitt = (%12.5g +- %10.3g) (%12.5g +- %10.3g) (%12.5g +- %10.3g)"%(alphaY,alphaY_err,betaY,betaY_err,emittY,emittY_err) 	
		final_twiss_params_holder.setParams(0,alphaX, betaX, emittX)
		final_twiss_params_holder.setParams(1,alphaY, betaY, emittY)
		final_twiss_params_holder.setParamsErr(0,alphaX_err, betaX_err, emittX_err)
		final_twiss_params_holder.setParamsErr(1,alphaY_err, betaY_err, emittY_err)
		init_and_fit_params_controller.finalTwiss_table.getModel().fireTableDataChanged()		
# E.g. from 0 to 2*width, from 0 to 2*height, etc. for every dimension
# Notice the -1 in maxC: the interval is inclusive of the largest coordinate.
minC = [0 for d in range(img.numDimensions())]
maxC = [int(img.dimension(i) * scale) -1 for i, scale in enumerate(s)]
imgI = Views.interval(bigger, minC, maxC)

# Visualize the bigger view
imp2x = IL.wrap(imgI, imp.getTitle() + " - 2X") # an ImagePlus
imp2x.show()

# Define a rotation by +30º relative to the image center in the XY axes
# (not explicitly XY but the first two dimensions)
angle = radians(30)
rot2d = Affine2D.getRotateInstance(angle, img.dimension(0) / 2, img.dimension(1) / 2)
ndims = img.numDimensions()
matrix = Matrix(ndims, ndims + 1)
matrix.set(0, 0, rot2d.getScaleX())
matrix.set(0, 1, rot2d.getShearX())
matrix.set(0, ndims, rot2d.getTranslateX())
matrix.set(1, 0, rot2d.getShearY())
matrix.set(1, 1, rot2d.getScaleY())
matrix.set(1, ndims, rot2d.getTranslateY())
for i in range(2, img.numDimensions()):
  matrix.set(i, i, 1.0)

from pprint import pprint
pprint([list(row) for row in matrix.getArray()])

# Define a rotated view of the image
rotated = RV.transform(imgR, AffineTransform(matrix))
Пример #12
0
class M:
    def __init__(self, *twod_array):
        if isinstance(twod_array[0], Matrix):
            self.theMatrix = twod_array[0]
        elif isinstance(twod_array[0], M):
            self.theMatrix = twod_array[0].theMatrix
        else:
            self.theMatrix = Matrix(twod_array)

    def __add__(self, other):
        if self.isaMatrix(other):
            return M(self.theMatrix.plus(self.extractMatrix(other)))
        elif isinstance(other, PyInteger):
            out = M(self.theMatrix.copy())
            for i in range(len(out)):
                out[i] = self[i] + other
            return out
        #assume a sequence or tuple
        else:
            out = M(self.theMatrix.copy())
            for i in range(len(other)):
                out[i] = self[i] + other[i]
            return out

    def __radd__(self, other):
        if self.isaMatrix(other):
            return M(self.theMatrix.plus(self.extractMatrix(other)))
        elif isinstance(other, PyInteger):
            out = M(self.theMatrix.copy())
            for i in range(len(out)):
                out[i] = self[i] + other
            return out
        #assume a sequence or tuple
        else:
            out = M(self.theMatrix.copy())
            for i in range(len(other)):
                out[i] = self[i] + other[i]
            return out

    def __iadd__(self, other):
        temp = self.extractMatrix(self.__add__(other))
        self.theMatrix = temp
        return self

    def __sub__(self, other):
        if self.isaMatrix(other):
            return M(self.theMatrix.minus(self.extractMatrix(other)))
        elif isinstance(other, PyInteger):
            out = M(self.theMatrix.copy())
            for i in range(len(out)):
                out[i] = self[i] - other
            return out
        #assume a sequence or tuple
        else:
            out = M(self.theMatrix.copy())
            for i in range(len(other)):
                out[i] = self[i] - other[i]
            return out

    def __rsub__(self, other):
        if self.isaMatrix(other):
            return M(self.theMatrix.minus(self.extractMatrix(other)))
        elif isinstance(other, PyInteger):
            out = M(self.theMatrix.copy())
            for i in range(len(out)):
                out[i] = other - self[i]
            return out
        #assume a sequence or tuple
        else:
            out = M(self.theMatrix.copy())
            for i in range(len(other)):
                out[i] = other[i] - self[i]
            return out

    def __isub__(self, other):
        temp = self.extractMatrix(self.__sub__(other))
        self.theMatrix = temp
        return self

    def __mul__(self, other):
        if isinstance(other, M):
            return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
        elif isinstance(other, Matrix):
            return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
        elif type(other) == type([]):
            out = M(self.theMatrix.copy())
            for i in range(len(other)):
                out.__setitem__(i, self.__getitem__(i) * other[i])
            return out
        else:
            return M(self.theMatrix.times(other))

    def __rmul__(self, other):
        if isinstance(other, M):
            return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
        elif isinstance(other, Matrix):
            return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))
        elif type(other) == type([]):
            out = M(self.theMatrix.copy())
            for i in range(len(other)):
                out.__setitem__(i, self.__getitem__(i) * other[i])
            return out
        else:
            return M(self.theMatrix.times(other))

    def __imul__(self, other):
        temp = self.extractMatrix(self.__mul__(other))
        self.theMatrix = temp
        return self

    def cross(self, other):
        return self.__mul__(other)

    def dot(self, other):
        return M(self.theMatrix.arrayTimes(self.extractMatrix(other)))

    def __getitem__(self, key):
        out = []
        rows = self.theMatrix.getColumnDimension()
        if isinstance(key, PySlice):
            start = key.start
            step = key.step
            stop = key.stop
            if start == None:
                start = 0
            if stop == None:
                stop = len(self)
            for i in range(start, stop, step):
                a, b = divmod(i, rows)
                out.append(self.theMatrix.get(a, b))
        if isinstance(key, PyTuple):
            if len(key) == 1:
                for i in range(key[0]):
                    a, b = divmod(i, rows)
                    out.append(self.theMatrix.get(a, b))
            if len(key) == 2:
                for i in range(key[0], key[1]):
                    a, b = divmod(i, rows)
                    out.append(self.theMatrix.get(a, b))
            elif len(key) == 3:
                for i in range(key[0], key[1], key[2]):
                    a, b = divmod(i, rows)
                    out.append(self.theMatrix.get(a, b))
        if isinstance(key, PyInteger):
            a, b = divmod(key, rows)
            out = self.theMatrix.get(a, b)
        return out

    def __setitem__(self, key, value):
        cols = self.theMatrix.getColumnDimension()
        a, b = divmod(key, cols)
        return self.theMatrix.set(a, b, value)

    def __len__(self):
        return self.theMatrix.getColumnDimension(
        ) * self.theMatrix.getRowDimension()

    def __str__(self):
        output = ""
        for i in range(self.theMatrix.getRowDimension()):
            if i == 0:
                output = output + "["
            for j in range(self.theMatrix.getColumnDimension()):
                if j == 0:
                    output = output + "["
                output = output + Double.toString(self.theMatrix.get(i, j))
                if (j == (self.theMatrix.getColumnDimension() - 1)):
                    output = output + "]"
                else:
                    output = output + ", "
            if (i == (self.theMatrix.getRowDimension() - 1)):
                output = output + "]"
            else:
                output = output + ", "
        return output

    def __repr__(self):
        return self.__str__()

    def __call__(self):
        return self.__str__()

    #also will want every method supplied by Jama.Matrix class

    def extractMatrix(self, other):
        if isinstance(other, Matrix):
            return other
        elif isinstance(other, M):
            return other.theMatrix

    def isaMatrix(self, other):
        if isinstance(other, Matrix):
            return 1
        elif isinstance(other, M):
            return 1
        else:
            return 0
	mtrx = state.getResponseMatrix()
	#----------------------
	sizes_X_arr.append(xRMS_Size)
	#--------elements of the transport matrix
	a11 = mtrx.getElem(0,0)
	a12 = mtrx.getElem(0,1)
	matrx_all_X.append([a11**2, 2*a11*a12,a12**2])
	
#=========================================
#  Only x-axis analysis
#=========================================
sigma_rel_err = 0.05

n_ws = len(matrx_all_X)

mMatrX = Matrix(matrx_all_X,n_ws,3)

sigma2Vector = Matrix(n_ws,1)
weightM = Matrix.identity(n_ws,n_ws)

for ind in range(n_ws):
	sigma = sizes_X_arr[ind]*(1.0 +	random.gauss(0.,sigma_rel_err))
	sigma2Vector.set(ind,0,sigma**2)
	err2 = (2*sigma*sigma*sigma_rel_err)**2
	weightM.set(ind,ind,1.0/err2)
	
#=== mwmMatr = (M^T*W*M) =======
mwmMatr = ((mMatrX.transpose()).times(weightM)).times(mMatrX)

#=== corr2ValMatr = [(M^T*W*M)^-1] * M^T * W * Vector(sigma**2)
corr2ValMatr = (((mwmMatr.inverse()).times(mMatrX.transpose())).times(weightM)).times(sigma2Vector)
Пример #14
0
xmean = sum(xs) / len(xs)
xs = [x - xmean for x in xs]
ys = [float(y) for (x, y) in pts]
ymean = sum(ys) / len(ys)
ys = [y - ymean for y in ys]
#print("x[:10] = " + str(xs[:10]))
#print("y[:10] = " + str(ys[:10]))

d1 = [x * x for x in xs]
d2 = [x * y for (x, y) in zip(xs, ys)]
d3 = [y * y for y in ys]
d4 = [x for x in xs]
d5 = [y for y in ys]
d6 = [1 for x in xs]
d = sum([d1, d2, d3, d4, d5, d6], [])
D = Matrix(d, len(d1))

S = D.transpose().times(D)
print("S = " + str([s for s in S.getRowPackedCopy()]))
C = Matrix(6, 6)
C.set(0, 2, 2)
C.set(2, 0, 2)
C.set(1, 1, -1)
#eig = EigenvalueDecomposition(S.inverse().times(C));
eig = EigenvalueDecomposition(S.inverse().times(C.transpose()))
#eig = EigenvalueDecomposition(S.inverse().transpose().times(C));
E = eig.getRealEigenvalues()
print("eigenvalues = " + str([('%.2E' % e) for e in E]))
#E = [abs(e) for e in E];
#print(E)
V = eig.getV()