示例#1
0
	def __init__(self, size):
		self.prim_keys = Array.Array(size)
		self.prim_values = Array.Array(size)
		self.ovflw_keys = Array.Array(size)
		self.ovflw_values = Array.Array(size)
		self.resizing = True                            # two different versions of the program, one resizes and the other does not
		self.debugging = False
示例#2
0
	def clear(self):
		self.prim_keys = Array.Array(size)
		self.prim_values = Array.Array(size)
		self.ovflw_keys = Array.Array(size)
		self.ovflw_values = Array.Array(size)

		
		
		
示例#3
0
 def __init__(self, size):
     ''' Creates two different versions of the program:
         one resizes, and the other does not.
     '''
     self.size = size
     self.prim_keys = Array.Array(size)
     self.prim_values = Array.Array(size)
     self.ovflw_keys = Array.Array(size)
     self.ovflw_values = Array.Array(size)
     self.resizing = True 
     self.debugging = False
示例#4
0
    def _resize(self):
        '''
        Private method that doubles the size of the overflow array
        if there are no more None spots left. Copies the key/value pairs
        to the larger overflow array, again in sequential position.
        '''
        temp_keys = Array.Array(len(self.overflow_keys) * 2)
        temp_values = Array.Array(len(self.overflow_keys) * 2)
        for i in range(len(self.overflow_values)):
            temp_keys[i] = self.overflow_keys[i]
            temp_values[i] = self.overflow_values[i]

        self.overflow_keys = temp_keys
        self.overflow_values = temp_values
        return
示例#5
0
def main():
    t = Tree.Average('tree.xml')
    print(t.serchAver())

    a = Array.Array()
    print(a.draw())
    print(a.separate())
示例#6
0
	def __init__(self, size):
		'''
			self.size is the size of the array
			self.primaryKeys is the array of the primary area values
			self.overflowKeys is the array of the overflow area values
			self.primaryValues is the array of the values of the primary area
			self.overflowValues is the array of the values of the overflow area
			self.debug is if debuging is on or off. It's off by default
		'''
		self.size = size
		self.primaryKeys = Array(self.size)
		self.primaryValues = Array(self.size)
		self.overflowKeys = Array(self.size)
		self.overflowValues = Array(self.size)
		self._debug = False
		self.resizing = True
示例#7
0
    def MultipleScatteringMatrix(self, index0, index1):
        This = self.Track.GetNode(index0)
        Other = self.Track.GetNode(index1)

        dx, dy, tx, ty, e = This.Pstate.State

        z0 = This.running
        z02 = z0**2
        z1 = Other.running
        dz = z1 - z0
        ds = abs(dz) * (tx**2 + ty**2 + 1)**0.5
        L = ds / self.gas.x0
        theta02 = thetaMS(K2P(This.ParticleEnergy), L)**2

        factor = theta02 * (1 + tx**2 + ty**2)
        p33 = factor * (1 + tx**2)
        p44 = factor * (1 + ty**2)
        p34 = factor * tx * ty

        state = This.Pstate.State if This.status < 2 else This.Fstate.State
        self.Eres2 = self.Eresolution**2 / state[-1]

        return Array.Matrix(
            [z02 * p33 / 3, z02 * p34 / 3, -z0 * p33 / 2, -z0 * p34 / 2, 0.],
            [z02 * p34 / 3, z02 * p44 / 3, -z0 * p34 / 2, -z0 * p44 / 2, 0.],
            [-z0 * p33 / 2, -z0 * p34 / 2, p33, p34, 0.],
            [-z0 * p34 / 2, -z0 * p44 / 2, p34, p44, 0.],
            [0., 0., 0., 0., self.Eres2])  # * 10.
示例#8
0
 def rehash(self):
     if self.loadFactor() > 0.5:
         items = list(self)
         self._items = Array(len(self._items) * 2)
         self._size = 0
         for item in items:
             self.add(item)
示例#9
0
 def testConstructor3(self):
     "Test Array2 copy constructor"
     for i in range(self.nrows):
         for j in range(self.ncols):
             self.array2[i][j] = i * j
     arrayCopy = Array.Array2(self.array2)
     self.failUnless(arrayCopy == self.array2)
示例#10
0
def radisSort(intList, numDigits):
	# Create an array of queues to represent the bins
	NUM_BINS = 10

	binArray = Array(NUM_BINS)
	for k in range(NUM_BINS):
		binArray[k] = Queue()

	# The value of the current column
	column = 1

	# Iterate over the number of digits in the larges value
	for d in range(numDigits):

		# Distribute the keys accross the 10 bins
		for key in intList:
			digit = (key // column) % NUM_BINS
			binArray[digit].enqueue(key)

		# Gather the keys from the bins and place them back in intList
		i = 0
		for bin in binArray:
			while not bin.isEmpty():
				intList[i] = bin.dequeue()
				i += 1

		# Advance to the next column value
		column *= NUM_BINS
示例#11
0
 def __init__(self, sourceCollection = None, capacity = None):
     if capacity == None:
         self._capacity = HashSet.DEFAULT_CAPACITY
     else:
         self._capacity = capacity
     self._items = Array(self._capacity)         # 集的条目
     self._foundNode = self._priorNode = None    # 引用要定位的节点,否则为None,引用定位的节点之前的节点,否则为None
     self._index = -1                            # 引用节点所在链的索引,否则置为-1
     AbstractCollection.__init__(self, sourceCollection)
def CropImageAroundEdges(InputImage):
	# convert the input image to black
	InputImage = InputImage.convert('L')

	# extract the edges of the letters
	RawImage = PILToCV2(InputImage)
	GrayImage = cv2.cvtColor(RawImage, cv2.COLOR_BGR2GRAY)
	# convert back to a PIL image
	ImageEdges = Image.fromarray(InvertColor(cv2.Canny(GrayImage, 50, 150, apertureSize = 3)))


	CharacterHorizontalArray = Array.HorizontalArrayFromImage(ImageEdges)
	CharacterVerticalArray = Array.VerticalArrayFromImage(ImageEdges)

	YMin = 0
	YMax = 0
	XMin = 0
	XMax = 0

	# find the min and max for y
	for i in range(0, len(CharacterVerticalArray)):
		if CharacterVerticalArray[i] != 255:
			YMin = i
			break
	for i in range(ImageEdges.size[1] - 1, -1, -1):
		if CharacterVerticalArray[i] != 255:
			YMax = i
			break

	# find the min and max for x
	for i in range(0, len(CharacterHorizontalArray)):
		if CharacterHorizontalArray[i] != 255:
			XMin = i
			break
	for i in range(ImageEdges.size[0] - 1, -1, -1):
		if CharacterHorizontalArray[i] != 255:
			XMax = i
			break

	# +1's are to compensate for how crop function works
	InputImage = InputImage.crop((XMin, YMin, XMax + 1, YMax + 1))
	return InputImage
示例#13
0
	def RoundAltitude(self, InputAltitude):
		PossibleAltitudes = [6000, 9000, 12000, 18000, 24000, 30000, 34000, 39000]
		Differences = []

		for i in range(0, len(PossibleAltitudes)):
			PossibleAltitude = PossibleAltitudes[i]

			Differences.append([abs(PossibleAltitude - InputAltitude), i])

		ClosestAltitudeIndex = sorted(Differences, key=Array.itemgetter(0))[0][1]
		
		return PossibleAltitudes[ClosestAltitudeIndex]
示例#14
0
 def testSetGet1(self):
     "Test Array2 __setitem__, __getitem__ methods"
     m = self.nrows
     n = self.ncols
     array1 = []
     a = np.arange(n, dtype="l")
     for i in range(m):
         array1.append(Array.Array1(i * a))
     for i in range(m):
         self.array2[i] = array1[i]
     for i in range(m):
         self.failUnless(self.array2[i] == array1[i])
示例#15
0
    def TransportMatrix(self, index0, index1):
        This = self.Track.GetNode(index0)
        Other = self.Track.GetNode(index1)

        state = This.Pstate.State if This.status < 2 else This.Fstate.State
        tx = state[2]
        ty = state[3]
        dz = Other.running - This.running
        ds = abs(dz) * (tx**2 + ty**2 + 1)**0.5

        F = Array.Identity(self.Sdim)
        F[-1][-1] = self.Eloss(state[-1], ds)
        return F
示例#16
0
	def tabulate(self):
		self.belowcount = 0           # this counts values below the starting value
		self.abovecount = 0           # this counts values above the ending value
		numslots = int(round((self.end - self.start)/self.delta, 0))
		self.counts = Array.Array(numslots, 0)
		for line in self.lines:
			n = float(line)
			if n < self.start:
				self.belowcount += 1
			elif n > self.end:
				self.abovecount += 1
			else:
				slotnumber = int((n - self.start) / self.delta)
				self.counts[slotnumber] += 1
示例#17
0
    def RoundAltitude(self, InputAltitude):
        PossibleAltitudes = [
            6000, 9000, 12000, 18000, 24000, 30000, 34000, 39000
        ]
        Differences = []

        for i in range(0, len(PossibleAltitudes)):
            PossibleAltitude = PossibleAltitudes[i]

            Differences.append([abs(PossibleAltitude - InputAltitude), i])

        ClosestAltitudeIndex = sorted(Differences,
                                      key=Array.itemgetter(0))[0][1]

        return PossibleAltitudes[ClosestAltitudeIndex]
示例#18
0
def FindClosestPoint(PointArray, TargetPoint):
    # check to make sure that all of the parameters are correct
    # if len(np.array(TargetPoint).shape) != 1 or len(TargetPoint) != 2:
    # 	raise Exception("TargetPoint was in an illegal format")
    # if len(np.array(PointArray).shape) != 2:
    # 	raise Exception("PointArray was in an illegal format")

    PositionDistanceArray = []

    for CurrentPoint in PointArray:
        Distance = DistanceBetweenPoints(TargetPoint, CurrentPoint)

        # add distance from target point, currentpoint, and index to this array
        Index = len(PositionDistanceArray)
        PositionDistanceArray.append([CurrentPoint, Distance, Index])

    # sort the array and find the index in the array that signifies the point with the shortest Distance to the TargetPoint
    return sorted(PositionDistanceArray, key=Array.itemgetter(1))[0][2]
示例#19
0
def FindClosestPoint(PointArray, TargetPoint):
	# check to make sure that all of the parameters are correct
	# if len(np.array(TargetPoint).shape) != 1 or len(TargetPoint) != 2:
	# 	raise Exception("TargetPoint was in an illegal format")
	# if len(np.array(PointArray).shape) != 2:
	# 	raise Exception("PointArray was in an illegal format")

	PositionDistanceArray = []

	for CurrentPoint in PointArray:
		Distance = DistanceBetweenPoints(TargetPoint, CurrentPoint)

		# add distance from target point, currentpoint, and index to this array
		Index = len(PositionDistanceArray)
		PositionDistanceArray.append([CurrentPoint, Distance, Index])

	# sort the array and find the index in the array that signifies the point with the shortest Distance to the TargetPoint
	return sorted(PositionDistanceArray, key=Array.itemgetter(1))[0][2]
示例#20
0
    def Filter(self, index):

        C_filtered = (self.this_node.pred_state.CovarianceMatrix.Inverse() +
                      self.MMMatrixT**self.NMatrixI**self.MMMatrix).Inverse()
        GainMatrix = C_filtered**self.MMMatrixT**NMatrixI
        x_filtered = self.prev_state + GainMatrix**(
            self.this_hit - self.MMMatrix**self.prev_state)

        projector = Array.Identity(self.ndim) - self.MMMatrix**GainMatrix
        r_filtered = projector**self.this_node.pred_resid
        R_filtered = projector**self.NMatrix

        chi2plus = r_filtered**R_filtered.Inverse()**r_filtered
        newchi2 = self.prev_node.cumchi2 + chi2plus

        self.this_node.filt_state = KalmanMeasurement(x_filtered, C_filtered)
        self.this_node.filt_resid = KalmanMeasurement(r_filtered, R_filtered)
        self.this_node.chi2 = chi2plus
        self.this_node.cumchi2 = newchi2
示例#21
0
    def MultipleScatteringMatrix(self, index0, index1):
        This = self.Track.GetNode(index0)
        Other = self.Track.GetNode(index1)
        z0 = This.running
        z02 = z0**2
        z1 = Other.running
        L = abs(z1 - z0) / self.gas.x0 * 0.1

        dx, dy, tx, ty, e = This.Pstate.State
        theta02 = thetaMS(K2P(e), L)**2

        factor = theta02 * (1 + tx**2 + ty**2)
        p33 = factor * (1 + tx**2)
        p44 = factor * (1 + ty**2)
        p34 = factor * tx * ty

        return Array.Matrix([z02 * p33, z02 * p34, -z0 * p33, -z0 * p34, 0.],
                            [z02 * p34, z02 * p44, -z0 * p34, -z0 * p44, 0.],
                            [-z0 * p33, -z0 * p34, p33, p34, 0.],
                            [-z0 * p34, -z0 * p44, p34, p44, 0.],
                            [0., 0., 0., 0., self.Eres2])
示例#22
0
 def testConstructor3(self):
     "Test Array1 copy constructor"
     for i in range(self.array1.length()):
         self.array1[i] = i
     arrayCopy = Array.Array1(self.array1)
     self.failUnless(arrayCopy == self.array1)
示例#23
0
            # crop the letter
            Letter = Letter.crop((0, FirstRow, Letter.size[0], LastRow))

            # resize the letter to height 300
            ChangeHeight = 400.0 / Letter.size[1]
            Letter = Letter.resize((int(Letter.size[0] * ChangeHeight), 400),
                                   Image.ANTIALIAS)

            # create a new white image
            FinalImage = Image.new('L', (600, 400), 255)

            # paste the letter onto the new white canvas
            FinalImage.paste(Letter, (0, 400 - Letter.size[1]))

            # resize the image to 30x20
            FinalImage = FinalImage.resize((30, 20), Image.ANTIALIAS)

            FinalImage = Array.BlackAndWhite(FinalImage, Threshold=10)

            FolderName = listdir("./Letters")[(i / 2) % 26]

            # cycle through filenames in an attempt to find empty ones
            FileName = 0
            while str(FileName) + ".png" in listdir("./Letters/" + FolderName):
                FileName += 1

            # save that shit
            FinalImage.save("Letters/" + FolderName + "/" + str(FileName) +
                            ".png")
    except IndexError:
        print "error parsing", SheetName, "font"
示例#24
0
 def testConstructor0(self):
     "Test Array1 default constructor"
     a = Array.Array1()
     self.failUnless(isinstance(a, Array.Array1))
     self.failUnless(len(a) == 0)
示例#25
0
 def testConstructor2(self):
     "Test Array1 array constructor"
     na = np.arange(self.length)
     aa = Array.Array1(na)
     self.failUnless(isinstance(aa, Array.Array1))
示例#26
0
 def testSetBad1(self):
     "Test Array2 __setitem__ method, negative index"
     a = Array.Array1(self.ncols)
     self.assertRaises(IndexError, self.array2.__setitem__, -1, a)
示例#27
0
 def testSetBad2(self):
     "Test Array2 __setitem__ method, out-of-range index"
     a = Array.Array1(self.ncols)
     self.assertRaises(IndexError, self.array2.__setitem__, self.nrows + 1,
                       a)
示例#28
0
 def setUp(self):
     self.length = 5
     self.array1 = Array.Array1(self.length)
示例#29
0
 def __init__(self, state=Array.Vector(), CovarianceMatrix=Array.Matrix()):
     self.state = state
     self.CovarianceMatrix = CovarianceMatrix
示例#30
0
            AngleSum += np.arctan2(x2 - x1, y2 - y1)
            NumberOfLines += 1
            Lines.append([x2, y1, x2, y2])

    # get the mean angle
    AngleSum /= NumberOfLines
    # convert to degrees
    AngleSum = (AngleSum / (np.pi * 2)) * 360

    RotationArray.append([ImageName, AngleSum])

for Object in RotationArray:
    print "rotate", Object[0], "by", Object[1], "degrees"

    ToRotate = Image.open("Processed/" + Object[0])

    # draw some lines on it
    # Drawing = ImageDraw.Draw(ToRotate)
    # for points in Lines:
    # 	Drawing.line((points[0], points[1], points[2], points[3]), fill=128)

    # rotate it
    ToRotate = ToRotate.convert('RGBA').rotate(-Object[1] + 90, expand=1)

    Final = Image.new('RGBA', ToRotate.size, (255, 255, 255, 255))
    Final = Image.composite(ToRotate, Final, ToRotate)

    # crop the image so that there's no white space showing at the edges
    Final = Array.CropImageAroundBlack(Final)

    Final.convert('L').save('Rotated/' + Object[0])
示例#31
0
 def testConstructor2(self):
     "Test Array2 array constructor"
     na = np.zeros((3, 4), dtype="l")
     aa = Array.Array2(na)
     self.failUnless(isinstance(aa, Array.Array2))
示例#32
0
 def setUp(self):
     self.nrows = 5
     self.ncols = 4
     self.array2 = Array.Array2(self.nrows, self.ncols)