Beispiel #1
0
    def overUnder(self, point, onThresh=0):
        """
		Arguments:
			point: [Vector] A point
			onThresh: [float] The permitted error when testing for being "on" a line
		Returns: 1 if this point lies on or vertically over segment, -1 if
			lies vertically under, 0 if out of range over x
		"""

        rx = Region(self.p1.x, self.p2.x)
        ry = Region(self.p1.y, self.p2.y)

        if (not rx.contains(point.x)) or self.p1.x == self.p2.x:
            # Point is out of range over x
            return 0

        # y at the point where point is
        yThresh = self.p1.y + \
         (self.p2.y - self.p1.y) * \
         (point.x - self.p1.x) / (self.p2.x - self.p1.x)

        if abs(point.y - yThresh) < onThresh:
            # On segment
            return 1
        if point.y >= yThresh:
            # Over segment
            return 1
        else:
            # Under segment
            return -1
Beispiel #2
0
 def image_regions(self):
     '''image_regions looks for areas of the page that are not text or
     margin that might be big enough to fit an image.'''
     all = self.jp2_region
     if self.metadata:
         s = int(round(self.metadata.dpi * 0.25))
         all = all.inset(s, s, s, s)
     enough_width = (all.right - all.left) / 4
     enough_height = (all.bottom - all.top) / 10
     candidates = []
     vstart = all.top
     obj = self.get_ocr_object_element()
     if not obj:
         return [all]
     for p in obj.iter('PARAGRAPH'):
         r = text_bounds(p, all)
         if r.top - vstart >= enough_height:
             candidates.append(Region(all.left, all.right, vstart, r.top))
         if r.height >= enough_height:
             if (r.left - all.left) >= enough_width:
                 candidates.append(
                     Region(all.left, r.left - 1, r.top, r.bottom))
             if (all.right - r.right) >= enough_width:
                 candidates.append(
                     Region(r.right + 1, all.right, r.top, r.bottom))
         vstart = r.bottom + 1
     if (all.bottom - vstart) >= enough_height:
         candidates.append(Region(all.left, all.right, vstart, all.bottom))
     return candidates
Beispiel #3
0
def populateregion(profilename, regionname):

    region = Region(regionname)
    region.name = regionname

    vpcs = Vpc.loaddata(profilename, regionname)

    eips = ElasticIp.loaddata(profilename, regionname)
    instances = EC2.loaddata(profilename, regionname)

    region.elasticips = eips
    region.instances = instances
    region.vpcs = vpcs

    subnets = Subnet.loaddata(profilename, regionname)
    region.subnets = subnets

    loadbalancers = ElasticLoadBalancer.loaddata(profilename, regionname)
    region.elasticloadbalancers = loadbalancers

    region.linksubnetstovpcs()

    # writetoyaml(account)

    return region
Beispiel #4
0
    def _divideAndCount(self, n):
        # devide the region into n*n grids to compute the entropy
        # p(i) = # of photos in that grid, to the total number of grids
        # it returns the list of subregions associated with the number photos falling into that region
        photo_number = self.getPhotoNumber()
        region = Region(self._event["region"])
        subregions = region.divideRegions(n, n)

        # Laplacian smoothed
        pro = [1.0 / n / n] * n * n

        photos = self._event["photos"]
        for photo in photos:
            lat = photo["location"]["latitude"]
            lng = photo["location"]["longitude"]
            flag = False
            i = 0
            for subregion in subregions:
                if subregion.insideRegion([lat, lng]):
                    pro[i] += 1.0 / n / n
                    if flag == True:
                        raise Exception("bad data")
                    flag = True
                i += 1
        return pro
Beispiel #5
0
    def fix_bounding_box_scale(self, i_box, org_frame_heigth, org_frame_width):
        self.original_ratio = Fraction(self.targetwidth, self.targetheight)
        h1 = i_box[1]
        w1 = i_box[0]
        h_box = i_box[3]
        w_box = i_box[2]

        if h_box < self.targetheight:
            h1 = h1 + (h_box - self.targetheight)//2
            if h1 < 0:
                h1 = 0
            if h1 + self.targetheight > org_frame_heigth:
                h1 = h1 - (h1 + self.targetheight - org_frame_heigth)
            h_box = self.targetheight

        if w_box < self.targetwidth:
            w1 = w1 + (w_box - self.targetheight)//2
            if w1 < 0:
                w1 = 0
            if w1 + self.targetwidth > org_frame_width:
                w1 = w1 - (w1 + self.targetwidth - org_frame_width)
            w_box = self.targetwidth

        i_box_ratio = w_box/h_box
        if i_box_ratio == self.original_ratio.numerator/self.original_ratio.denominator:
            region = Region(h1=h1, w1=w1, h2=h1 + h_box, w2=w1 + w_box)
        elif i_box_ratio < (org_frame_width/org_frame_heigth):
            region = self.fix_vertical_ratio(w1, h1, w_box, h_box, org_frame_heigth, org_frame_width)
        else:
            region = self.fix_horizontal_ratio(w1, h1, w_box, h_box, org_frame_heigth, org_frame_width)
        if region.h2 >= org_frame_heigth:
            region.h2 = org_frame_heigth - 1
        if region.w2 >= org_frame_width:
            region.w2 = org_frame_width - 1
        return region
Beispiel #6
0
def buildAllCorpus(element_type='photos', time_interval_length=14, debug=False, paras={}):
    # return a dict = {region : its local corpus}
    assert element_type in ['photos', 'tweets']

    all_corpus = {}
    if element_type == 'photos':
        config = InstagramConfig
    else:
        config = TwitterConfig

    coordinates = [config.min_lat, config.min_lng,
                   config.max_lat, config.max_lng]

    nyc = Region(coordinates)
    region_list = nyc.divideRegions(25, 25)
    region_list = nyc.filterRegions(region_list, test=True, n=25, m=25, element_type=element_type)

    # 14 days ago
    now = int(tool.getCurrentStampUTC())

    num = 0
    for region in region_list:
        if debug and num > 0:
            # speed up the debugging
            pass
        else:
            cor = Corpus()
            cor.buildCorpus(region, [now - time_interval_length * 3600 * 24, now], element_type, paras)
        all_corpus[region.getKey()] = cor
        num += 1
        print 'build corpus %d' % (num)
    return all_corpus
    def _divideAndCount(self, n):
        # devide the region into n*n grids to compute the entropy
        # p(i) = # of photos in that grid, to the total number of grids
        # it returns the list of subregions associated with the number photos falling into that region
        photo_number = self.getPhotoNumber()
        region = Region(self._event['region'])
        subregions = region.divideRegions(n, n)

        # Laplacian smoothed
        pro = [1.0] * n * n
        s = n * n
        photos = self._event['photos']
        for photo in photos:
            lat = photo['location']['latitude']
            lng = photo['location']['longitude']
            flag = False
            i = 0
            for subregion in subregions:
                if subregion.insideRegion([lat, lng]):
                    pro[i] += 1.0
                    s += 1
                    if flag == True:
                        raise Exception('bad data')
                    flag = True
                i += 1
        for i in xrange(0, n * n):
            pro[i] /= s
        return pro
Beispiel #8
0
    def _divideAndCount(self, n):
        # devide the region into n*n grids to compute the entropy
        # p(i) = # of photos in that grid, to the total number of grids
        # it returns the list of subregions associated with the number photos falling into that region
        photo_number = self.getPhotoNumber()
        region = Region(self._event['region'])
        subregions = region.divideRegions(n, n)

        # Laplacian smoothed
        pro = [1.0 / n / n] * n * n

        photos = self._event['photos']
        for photo in photos:
            lat = photo['location']['latitude']
            lng = photo['location']['longitude']
            flag = False
            i = 0
            for subregion in subregions:
                if subregion.insideRegion([lat, lng]):
                    pro[i] += 1.0 / n / n
                    if flag == True:
                        raise Exception('bad data')
                    flag = True
                i += 1
        return pro
Beispiel #9
0
	def open(self, region=None, exemptions=None, open_border=True):
		'''
		Method: open
		Description: Opens (visits all cells and destroys all walls within) the given region, avoiding the given exempt regions.
		Parameters: region=None, exemptions=None
			region: Region - A region for maze opening to span
			exemptions: Regions - A collection of regions for maze opening to avoid
		Return: None
		'''

		# Ensure that valid boundaries are set.
		if region is None:
			region = Region((0, 0), (self.get_width(), self.get_height()))

		# Construct a set of valid cells.
		valid_cells = self.valid_cell_set(region, exemptions)

		# Visit all valid cells and open the walls as necessary (region borders only open if open_border is True).
		for cell in valid_cells:
			cell.visit()
			border_directions = region.on_border(cell.m_position)
			for direction in list(Direction):

				# Ensure that the border is allowed to be destroyed.
				if (self.get_neighbor_cell(cell, direction) is not None) and (open_border) or (direction not in border_directions):
					self.set_wall(cell, direction, False)
Beispiel #10
0
 def create_new_region(self):
     """
     Begin the creation of a new region.
     :return:
     """
     new_id = self.generate_id()
     self.current_region = Region(new_id)
Beispiel #11
0
    def test_adding(self):
        for _ in range(5000):
            self.kd.add((random.randint(250, 750), random.randint(250, 750)))

        # make sure not to overlap!
        q_ne = self.expand(Region(500, 500, 1000, 1000))
        q_nw = self.expand(Region(0, 500, 499, 1000))
        q_sw = self.expand(Region(0, 0, 499, 499))
        q_se = self.expand(Region(500, 0, 1000, 499))

        q_all = self.expand(Region(0, 0, 1000, 1000))

        # quick check to see if any were missing
        combined = q_ne + q_nw + q_sw + q_se
        for q in q_all:
            if q not in combined:
                print(q, " missing ")

        self.assertEqual(len(q_all), len(combined))

        # validate searches are true
        for p in combined:
            self.assertTrue(self.kd.find(p))

        # validate can't add these points anymore
        for p in combined:
            self.assertFalse(self.kd.add(p))
Beispiel #12
0
def find(**kwargs):
    """Find VPCs by name or ID across all regions."""
    vpc_ids = kwargs.get("ids", list())
    vpc_names = kwargs.get("names", list())
    vpcs = list()

    if type(vpc_ids) == str:
        vpc_ids = [vpc_ids]
    if type(vpc_names) == str:
        vpc_names = [vpc_names]

    for vpc_name in vpc_names:
        n_list = vpc_name.split("-")
        if len(n_list) != 4:
            raise NameError, "Invalid VPC name: " + vpc_name
        (reg, env) = ("-".join(n_list[:3]), n_list[3])
        res = Region(name=reg).find_vpcs(env=env)
        for v in res:
            if not v in vpcs:
                vpcs.append(v)

    for vpc_id in vpc_ids:
        for region in get_regions():
            res = region.find_vpcs(id=vpc_id)
            if res:
                for v in res:
                    if not v in vpcs:
                        vpcs.append(v)
                break

    if not vpc_id and not vpc_ids:
        for region in get_regions():
            res.extend(region.find_vpcs())

    return vpcs
Beispiel #13
0
    def range(self, event):
        """Initiate a range search using a selected rectangular region."""

        p = (event.x, self.toCartesian(event.y))

        if self.selectedRegion is None:
            self.selectedStart = Region(p[X], p[Y], p[X], p[Y])
        self.selectedRegion = self.selectedStart.unionPoint(p)

        self.paint()

        # return (node,status) where status is True if draining entire tree rooted at node. Draw these
        # as shaded red rectangle to identify whole sub-tree is selected.
        for pair in self.tree.range(self.selectedRegion):
            p = pair[0].point

            if pair[1]:
                self.canvas.create_rectangle(pair[0].region.x_min,
                                             self.toTk(pair[0].region.y_min),
                                             pair[0].region.x_max,
                                             self.toTk(pair[0].region.y_max),
                                             fill='Red',
                                             stipple='gray12')
            else:
                self.canvas.create_rectangle(p[X] - RectangleSize,
                                             self.toTk(p[Y]) - RectangleSize,
                                             p[X] + RectangleSize,
                                             self.toTk(p[Y]) + RectangleSize,
                                             fill='Red')
Beispiel #14
0
	def overUnder(self, point, onThresh=0):
		"""
		Arguments:
			point: [Vector] A point
			onThresh: [float] The permitted error when testing for being "on" a line
		Returns: 1 if this point lies on or vertically over segment, -1 if
			lies vertically under, 0 if out of range over x
		"""
		
		rx = Region(self.p1.x, self.p2.x)
		ry = Region(self.p1.y, self.p2.y)
		
		if (not rx.contains(point.x)) or self.p1.x == self.p2.x:
			# Point is out of range over x
			return 0
		
		# y at the point where point is
		yThresh = self.p1.y + \
			(self.p2.y - self.p1.y) * \
			(point.x - self.p1.x) / (self.p2.x - self.p1.x)
		
		if abs(point.y - yThresh) < onThresh:
			# On segment
			return 1
		if point.y >= yThresh:
			# Over segment
			return 1
		else:
			# Under segment
			return -1
Beispiel #15
0
    def _divideAndCount(self, n):
        # devide the region into n*n grids to compute the entropy
        # p(i) = # of elements in that grid, to the total number of grids
        # it returns the list of subregions associated with the number elements falling into that region
        element_number = self.getElementNumber()
        region = Region(self._event["region"])
        subregions = region.divideRegions(n, n)

        # Laplacian smoothed
        pro = [1.0] * n * n
        s = n * n
        elements = self._event[self._element_type]
        for element in elements:
            lat = element["location"]["latitude"]
            lng = element["location"]["longitude"]
            flag = False
            i = 0
            for subregion in subregions:
                if subregion.insideRegion([lat, lng]):
                    pro[i] += 1.0
                    s += 1
                    if flag == True:
                        raise Exception("bad data")
                    flag = True
                i += 1
        for i in xrange(0, n * n):
            pro[i] /= s
        return pro
Beispiel #16
0
	def intersect(self, other, pThresh=0):
		"""Determines the intersection point of self and other
		Arguments:
			other: [Segment] A segment
			pThresh: [float] The permitted error when testing for parallel
				lines (default: 0) 
		Returns: [List [Vector]] Empty list for no intersect, one Vector for a
			point-intersect, two for a segment-intersect 
		"""
		
		# Manually handles zero-length lines
		if self.len() == 0 or other.len() == 0: return [] 
		
		# Manually handles point overlaps
		if self == other: return [self.p1, self.p2]
		if self.p1 == other.p1 or self.p1 == other.p2: return []
		if self.p2 == other.p1 or self.p2 == other.p2: return []
		
		# Maps problem to problem of locating other's x-intersect
		toMove = self.p1.mul(-1)
		toRotate = -1 * self.angle()
		s1 = self.copy()
		s2 = other.copy()
		s1.move(toMove)
		s2.move(toMove)
		s1.rotate(toRotate)
		s2.rotate(toRotate)
		
		# No x-intersect -- s2 does not cross s1's line
		if abs(s2.p1.y) > pThresh and numpy.sign(s2.p1.y) == numpy.sign(s2.p2.y):
			return []
		
		# Segments are parallel
		if abs(s2.p1.y) <= pThresh and abs(s2.p1.y) <= pThresh:
			s1region = Region(s1.p1.x, s1.p2.x)
			s2region = Region(s2.p1.x, s2.p2.x)
			overlap = s1region.overlapRegion(s2region)
			
			if overlap is False:
				# No intersection
				return []
			else:
				# Calculates segment of intersection
				p1Intersect = fromPolar(overlap.left, self.angle()) \
					.add(self.p1)
				p2Intersect = fromPolar(overlap.len(), self.angle()) \
					.add(p1Intersect)
				return [p1Intersect, p2Intersect]
		
		# Calculates the x-intersect
		xIntersect = s2.p1.x + (s2.p2.x - s2.p1.x) * (s2.p1.y / (s2.p1.y - s2.p2.y))
		
		if not Region(s1.p1.x, s1.p2.x).contains(xIntersect):
			# No x-intersect -- s2 crosses s1's line out of range of s1
			return []
		
		# Calculates and returns the intersection point
		pIntersect = fromPolar(xIntersect, self.angle()).add(self.p1)
		return [pIntersect]
Beispiel #17
0
    def __init__(self,
                 environment=None,
                 start_state=None,
                 end=None,
                 speed=10,
                 sight_distance=None,
                 dist_max=5):
        self.environment = environment
        self.state = start_state
        self.end = end
        self.speed = speed
        self.sight_distance = sight_distance
        self.dist_max = dist_max
        self.rrt_star_max_sq = 25

        if environment is None:
            self.environment = Environment()

        if sight_distance is None:
            y_range = self.environment.bounds[3] - self.environment.bounds[2]
            self.sight_distance = int(y_range / 10.0)

        if start_state is None:
            self.state = (self.environment.bounds[0],
                          self.environment.bounds[2])

        if end is None:
            self.end = Region([
                (self.environment.bounds[1], self.environment.bounds[3]),
                (self.environment.bounds[1],
                 self.environment.bounds[3] - self.sight_distance),
                (self.environment.bounds[1] - self.sight_distance,
                 self.environment.bounds[3] - self.sight_distance),
                (self.environment.bounds[1] - self.sight_distance,
                 self.environment.bounds[3]),
            ])

        self.node_state = SearchNode(self.state)
        self.nodes = [self.node_state]

        self.searching = True
        self.counter = 0

        self.search_lines = []
        self.path_lines = []

        self.discovered_lines = []
        self.discovered_obstacles = set()
        self.goal_lines = self.end.line_segments()

        self.goal_found = False

        # Initialize with seen obstacles
        seen_obstacles = self.checkNewObstacles()
        if len(seen_obstacles) > 0:
            for obs in seen_obstacles:
                self.discovered_lines += obs.line_segments()
                self.discovered_obstacles.add(id(obs))
Beispiel #18
0
def testCount():
	rows = 5
	cols = 5
	coverage = 20
	numbits = 10
	numRounds = 500
	trainingRounds = numRounds/4
	originalInputVector = InputVector(numbits)
	inputVector = InputVector(0)

	predictions = dict()
	#repeat several times to increase activity:
	for i in range(3):
		inputVector.extendVector(originalInputVector)

	desiredLocalActivity = DESIRED_LOCAL_ACTIVITY

	newRegion = Region(rows,cols,inputVector,coverage,desiredLocalActivity)
	outputVector = newRegion.getOutputVector()
	correctBitPredictions = 0
 
	for round in range(numRounds): # This test executes the CLA for a set number of rounds. 
     
		#print("Round: " + str(round))
		# if (round % 2 == 0):
		# 	val = 682
		# else:
		# 	val = 341
		val = Ultrasonic(brick, PORT_1).get_sample()
		setInput(originalInputVector,val)
		inputString = inputVector.toString()
		outputString = outputVector.toString()
		#print(originalInputVector.toString())
           
		#for bit in originalInputVector.getVector():
		# 	print(bit.bit)
		# print('')
		# print(inputString)


		if outputString in predictions:
			currentPredictionString = predictions[outputString]
		else:
			currentPredictionString = "[New input]"
		pred[outputString] = inputString
		print("Round: %d" % round) # Prints the number of the round
		printStats(inputString, currentPredictionString)
		if (round > trainingRounds):
			correctBitPredictions += stringOverlap(currentPredictionString, predictions[outputString])
				 

		newRegion.doRound()
		printColumnStats(newRegion)
	for key in predictions:
		print("key: " + key + " predictions: " + predictions[key])

	print("Accuracy: " + str(float(correctBitPredictions)/float((30*(numRounds-trainingRounds)))))
Beispiel #19
0
 def _getRandomCenters(self, leftTop, rightBottom):
     dummyRegion = Region(leftTop, rightBottom)
     childRegionCount = int(round(pow(Settings.numberOfcenters, 0.5)))
     dummyRegion.segmentByChildCount(childRegionCount, childRegionCount)
     randomCenters = []
     for childRegionRow in dummyRegion.getChildRegions():
         for childRegion in childRegionRow:
             randomCenter = self._getRandomCenter(childRegion.getLeftTop(), childRegion.getRightBottom())
             randomCenters.append(randomCenter)
     return randomCenters
Beispiel #20
0
def rez(agent, region_url, position=[128, 128, 128]):
    """rez an agent on a region
    
    this will call request and rez_avatar/rez caps
    
    """

    region = Region(region_url, position)
    region.rez(agent)
    return region
Beispiel #21
0
def testCount():
    rows = 5
    cols = 5
    coverage = 20
    numbits = 10
    numRounds = 500
    trainingRounds = numRounds / 4
    originalInputVector = InputVector(numbits)
    inputVector = InputVector(0)

    pred = dict()
    #repeat several times to increase activity:
    for i in range(3):
        inputVector.extendVector(originalInputVector)

    desiredLocalActivity = DESIRED_LOCAL_ACTIVITY

    r = Region(rows, cols, inputVector, coverage, desiredLocalActivity)
    outputVector = r.getOutputVector()
    correctBitPredctions = 0
    for round in range(numRounds):
        #print("Round: " + str(round))
        # if (round % 2 == 0):
        # 	val = 682
        # else:
        # 	val = 341
        val = round % 30
        setInput(originalInputVector, val)
        inputString = inputVector.toString()
        outputString = outputVector.toString()
        # for bit in inputVector.getVector():
        # 	printBit(bit)
        # print('')
        # print(inputString)

        if outputString in pred:
            curPredString = pred[outputString]
        else:
            curPredString = "[New input]"
        pred[outputString] = inputString

        printStats(inputString, curPredString)
        if (round > trainingRounds):
            correctBitPredctions += stringOverlap(curPredString,
                                                  pred[outputString])

        r.doRound()
        printColumnStats(r)
    for key in pred:
        print("key: " + key + " pred: " + pred[key])

    print("Accuracy: " + str(
        float(correctBitPredctions) / float((30 *
                                             (numRounds - trainingRounds)))))
Beispiel #22
0
def generateData2():
#   if sparse:
    #rep = Representor()

    all_corpus = buildAllCorpus(time_interval_length=14, debug=True)
    true_event_list, false_event_list = loadUnbalancedData()
    BaseFeatureProduction.GenerateArffFileHeader()

    for event in true_event_list + false_event_list:
        r = Region(event['region'])
        corpus = all_corpus[r.getKey()]
        BaseFeatureProduction(event, corpus, None).printFeatures()
Beispiel #23
0
    def open_directions_for_circle_avoiding_point(circ: Circle, p: P,
                                                  step) -> Region:
        """
        Handle the case where the load is near the edge of the segment. In this case the
        parent method (open_directions_for_avoiding_segment) does not compute the correct
        allowable region.
        """

        radius = circ.radius
        center = circ.center
        a = center.dist(p)
        if a > step + radius:
            # Case where the motion is fully allowed.
            return Region()
        if a < radius:
            # Case where the point is already within the load radius. i.e. numerical error or bug
            direction = center - p  # away from point
            return Region(-direction.perp(),
                          direction.perp())  # half plane perpendicular to
            # direction  - defines allowed open region for further motion

            # x = (radius ** 2 - step ** 2 - a ** 2) / (2 * a)
            # if x < 0:
            #     print("wow")
            #     return None
            # y = np.sqrt(step ** 2 - x ** 2)
            # direction = (center - p).resize(a + x)
            # perp = direction.perp().resize(y)
            # return Region(direction - perp - p, direction + perp - p)

        # if a>radius and a<radius+step
        # first find the maximal step size for which the region limit grows.
        # Above this step size, the limit in the open direction stays the same as the load just
        # slides next to the edge.
        d = np.sqrt(a**2 - radius**2)
        if d < step:
            step = d

        # Using the perpendicular of the triangle connecting a, the radius and the line of size
        # step connecting the circle to the edge, we cut a into two parts x and y such that
        # r^2-y^2=step^2-x^2 -> b=r^2-step^2=y^2-x^2
        # We then use this equation as well as a=x+y
        # to get the size of the final vector in the direction of a (x) and its size in the
        # perpendicular direction (h) as a function of the known quantities (radius,step and a).
        b = radius**2 - step**2
        x = (a**2 - b) / (2 * a)
        if x >= step:
            return Region()
        h = np.sqrt(step**2 - x**2)
        direction = (p - center).resize(x)
        left = direction + direction.perp().resize(h)
        right = direction - direction.perp().resize(h)
        return Region(left, right)
Beispiel #24
0
def get_screen_details(screen_list, screen_id):
    if len(screen_list) == 0:
        logger.error('Could not retrieve list of available monitors.')
    else:
        try:
            details = screen_list[screen_id]
            return Region(details['left'], details['top'], details['width'],
                          details['height'])
        except IndexError:
            logger.warning(
                'Screen %s does not exist. Available monitors: %s' %
                (screen_id, ', '.join(get_available_monitors(screen_list))))
    return Region()
Beispiel #25
0
    def setup_map(self, options):
        '''
        Method to set up essential map data given by the server.
        '''
        map_type = options[0]

        for i in range(1, len(options), 2):

            if map_type == 'super_regions':

                super_region = SuperRegion(options[i], int(options[i + 1]))
                self.map.super_regions.append(super_region)

            elif map_type == 'regions':

                super_region = self.map.get_super_region_by_id(options[i + 1])
                region = Region(options[i], super_region)
                
                self.map.regions.append(region)
                super_region.regions.append(region)

            elif map_type == 'neighbors':

                region = self.map.get_region_by_id(options[i])
                neighbours = [self.map.get_region_by_id(region_id) for region_id in options[i + 1].split(',')]

                for neighbour in neighbours:
                    region.neighbours.append(neighbour)
                    neighbour.neighbours.append(region)
            
        if map_type == 'wastelands':

            for i in range(1, len(options)):

                region = self.map.get_region_by_id(options[i])
                region.is_wasteland = True


        if map_type == 'neighbors':
            
            for region in self.map.regions:

                if region.is_on_super_region_border:
                    continue

                for neighbour in region.neighbours:

                    if neighbour.super_region.id != region.super_region.id:

                        region.is_on_super_region_border = True
                        neighbour.is_on_super_region_border = True
Beispiel #26
0
def main():
    """Creates a specified region and downloads files from USGS."""
    # example:
    # ./GetRegion.py --name BlockIsland --ymax 41.2378 --ymin 41.1415 --xmin -71.6202 --xmax -71.5332

    # defaults
    default_orthoIDs     = ','.join(Region.productIDs['ortho'])
    default_elevationIDs = ','.join(Region.productIDs['elevation'])
    default_landcoverIDs = ','.join(Region.productIDs['landcover'])

    # parse options and get results
    parser = argparse.ArgumentParser(description='Create regions and download files from USGS.')
    parser.add_argument('--name', required=True, type=str, help='name of the region to be generated')
    parser.add_argument('--xmax', required=True, type=float, help='easternmost longitude (west is negative)')
    parser.add_argument('--xmin', required=True, type=float, help='westernmost longitude (west is negative)')
    parser.add_argument('--ymax', required=True, type=float, help='northernmost latitude (south is negative)')
    parser.add_argument('--ymin', required=True, type=float, help='southernmost longitude (south is negative)')
    parser.add_argument('--tilesize', type=int, help='tilesize value (default %d)' % Region.tilesize)
    parser.add_argument('--scale', type=int, help='scale value (default %d)' % Region.scale)
    parser.add_argument('--vscale', type=int, help='vscale value (default %d)' % Region.vscale)
    parser.add_argument('--trim', type=int, help='trim value (default %d)' % Region.trim)
    parser.add_argument('--sealevel', type=int, help='sealevel value (default %d)' % Region.sealevel)
    parser.add_argument('--maxdepth', type=int, help='maxdepth value (default %d)' % Region.maxdepth)
    parser.add_argument('--orthoIDs', default=default_orthoIDs, type=checkOrthoIDs, help='ordered list of product IDs (default %s)' % default_orthoIDs)
    parser.add_argument('--elevationIDs', default=default_elevationIDs, type=checkElevationIDs, help='ordered list of product IDs (default %s)' % default_elevationIDs)
    parser.add_argument('--landcoverIDs', default=default_landcoverIDs, type=checkLandcoverIDs, help='ordered list of product IDs (default %s)' % default_landcoverIDs)
    parser.add_argument('--enable-ore', action='store_true', dest='doOre', default=False, help='enable ore generation')
    parser.add_argument('--enable-schematics', action='store_true', dest='doSchematics', default=False, help='enable schematic usage')
    parser.add_argument("-v", "--verbosity", action="count", \
                        help="increase output verbosity")
    parser.add_argument("-q", "--quiet", action="store_true", \
                        help="suppress informational output")
    args = parser.parse_args()

    # set up logging
    log_level = klog_levels.LOG_INFO
    if args.quiet:
        log_level = klog_levels.LOG_ERROR
    if args.verbosity:
        # v=1 is DEBUG 1, v=2 is DEBUG 2, and so on
        log_level += args.verbosity
    log = klogger(log_level)

    # create the region
    log.log_info("Creating new region %s..." % args.name)
    myRegion = Region(name=args.name, xmax=args.xmax, xmin=args.xmin, ymax=args.ymax, ymin=args.ymin, scale=args.scale, vscale=args.vscale, trim=args.trim, tilesize=args.tilesize, sealevel=args.sealevel, maxdepth=args.maxdepth, oiIDs=args.orthoIDs, lcIDs=args.landcoverIDs, elIDs=args.elevationIDs, doOre=args.doOre, doSchematics=args.doSchematics)

    log.log_info("Retrieving files...")
    myRegion.log = log
    myRegion.getfiles()
Beispiel #27
0
    def __init__(self, x, y, width, height, score):
        """Function assign values to the x, y, width, height and score region parameters.

        :param x: Location x parameter.
        :param y: Location y parameter.
        :param width: Region's width.
        :param height: Region's height.
        :param score: Similarity with which the pattern is found.
        """

        Region.__init__(self, x, y, width, height)
        self._width = width
        self._height = height
        self._score = score
def test():
    coordinates = [InstagramConfig.photo_min_lat,
            InstagramConfig.photo_min_lng,
            InstagramConfig.photo_max_lat,
            InstagramConfig.photo_max_lng
            ]
    huge_region = Region(coordinates)
    regions = huge_region.divideRegions(5,5)  #Warning: DO NOT SET THIS BELOW 5 OR MEMORY OVERFLOW
    
    for i in range(25):
        test_region = regions[i]
        test_region.display()
        ts = InstagramTimeSeries(test_region, 1355765315, 1355765315+30*24*3600)
        print ts.buildTimeSeries()
Beispiel #29
0
def test():
    coordinates = [
        InstagramConfig.photo_min_lat, InstagramConfig.photo_min_lng,
        InstagramConfig.photo_max_lat, InstagramConfig.photo_max_lng
    ]
    huge_region = Region(coordinates)
    regions = huge_region.divideRegions(
        5, 5)  #Warning: DO NOT SET THIS BELOW 5 OR MEMORY OVERFLOW

    for i in range(25):
        test_region = regions[i]
        test_region.display()
        ts = InstagramTimeSeries(test_region, 1355765315,
                                 1355765315 + 30 * 24 * 3600)
        print ts.buildTimeSeries()
Beispiel #30
0
    def normal_region(image):
        width, height = image.shape

        fill_dict = defaultdict(set)
        for i in range(width):
            for j in range(height):
                if image[i, j] < 240:
                    fill_dict[image[i, j]].add(Point(i, j))

        maximum_value = max(fill_dict, key=lambda x: len(fill_dict.get(x)))
        maximum_set = fill_dict.get(maximum_value)

        region = Region(maximum_set, maximum_value)

        return region.generate_image()
Beispiel #31
0
def get_region(region_id):
    from region import Region as Reg

    region = Reg.read_db(region_id)
    wpt_coords = []
    turnpoints = []

    for obj in region.turnpoints:
        wpt_coords.append({
            'longitude': obj.lon,
            'latitude': obj.lat,
            'name': obj.name
        })

        turnpoints.append({
            'radius': obj.radius,
            'longitude': obj.lon,
            'latitude': obj.lat,
            #         'altitude': obj.altitude,
            'name': obj.name,
            'type': obj.type,
            'shape': obj.shape

        })

    return region, wpt_coords, turnpoints
	def doubleCut(self, other, doreverse=True):
		'''takes self and another AngularDomain, and slices both of them,
		i.e.: cuts each region in the endpoints of the other AngularDomains
		regions, i.e.: ater this operation, for each region R1 in one
		AngularDomain, if there exists an Region R2 in the other so that R1
		contains R2 or R2 contains R1, the endpoints of R1 and R2 are the
		same.'''
		i,j= 0,0
		while i<len(self) and j<len(other):
			p= Region.relativePosition(self[i],other[j])
			if p==1:
				i+=1
			elif p==2:
				j+=1
			elif p==3:
				self.cutRegionOnPoint(i, other[j][0])
				i+=1
				other.cutRegionOnPoint(j, self[i][1])
				j+=1
			elif p==4:
				other.cutRegionOnPoint(j, self[i][0])
				j+=1
				self.cutRegionOnPoint(i, other[j][1])
				i+=1
			elif p==5:
				i= self.cutRegionOnPoint(i, other[j][0])
				i= self.cutRegionOnPoint(i, other[j][1])
				j+=1
			elif p==6:
				j= other.cutRegionOnPoint(j, self[i][0])
				j= other.cutRegionOnPoint(j, self[i][1])
				i+=1
Beispiel #33
0
    def __init__(self):
        """App for creating Quad tree dynamically and executing range queries."""

        self.tree = QuadTree(Region(0, 0, W, H))
        self.match = None

        # for range query
        self.selectedRegion = None
        self.queryRect = None

        self.master = tkinter.Tk()
        self.master.title('Quad Tree Range Application')
        self.w = tkinter.Frame(self.master, width=W, height=H)
        self.canvas = tkinter.Canvas(self.w, width=W, height=H)

        self.paint()

        self.canvas.bind("<Button-1>", self.click)
        self.canvas.bind("<Button-3>", self.range)  # when right mouse clicked
        self.canvas.bind("<ButtonRelease-3>", self.clear)
        self.canvas.bind("<B3-Motion>",
                         self.range)  # only when right mouse dragged

        # Different bindings on Macintosh platform
        self.canvas.bind("<Button-2>", self.range)  # when right mouse clicked
        self.canvas.bind("<ButtonRelease-2>", self.clear)
        self.canvas.bind("<B2-Motion>",
                         self.range)  # only when right mouse dragged

        self.w.pack()
Beispiel #34
0
    def __init__(self,
                 job_def,
                 job_queue,
                 jobId=None,
                 revision=None,
                 region=None):
        self.region = region
        self.set_batch()
        self.region = Region(aws_region)

        self.job_def = job_def
        self.job_queue = job_queue
        # self.task_name = task_name
        #
        # self.filename = filename
        # self.bucket = bucket
        # self.prefix = prefix
        #
        # self.cpus = cpus
        # self.memory = memory
        #
        self.set_revision()
        # self.revision = revision
        # self.dependency = dependency
        # self.array_size = array_size
        #
        # self.set_batch()
        # self.set_jobdef()
        # self.set_jobname()
        # self.set_json()
        #
        #TODO: handle job dependencies
        # self.dependency = dependency
        self.jobName = jobName
        self.jobId = jobId
Beispiel #35
0
    def add_regions(self):
        """ add regions to the country"""

        if not hasattr(self, 'regions'):
            self.regions = []
            for regionid in xrange(self.regioncount):
                self.regions.append(Region(self.redis, {'country': self}))
Beispiel #36
0
def downsampling_map(scale_factor, filename):
    # Inizializzazione scaled map vuota
    scaled_map = np.empty((int(2275 / scale_factor), int(1875 / scale_factor)),
                          dtype=object)
    for x in range(0, scaled_map.shape[0]):
        for y in range(0, scaled_map.shape[1]):
            scaled_map[x][y] = Region(coord=(x, y))

    with open(filename) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        i = 0
        j = 0
        for row in csv_reader:
            scaled_map[int(i / scale_factor)][int(
                j / scale_factor)].add_list_sim(row)
            line_count += 1
            j += 1
            if j >= 1875:
                i += 1
                j = 0
            if line_count % 10000 == 0:
                print("line count = ", line_count)

    return scaled_map
Beispiel #37
0
    def createRegion(self, addSubTerms=False, *args, **keywordArgs):
        """
        Create a new region optionally associated with an ontology term.
        
        >>> region = network.createRegion(name = 'Glomerulus 2')
        
        To associate the region with an ontology term pass in a term from an ontology in the library:
        
        >>> flyBrainOnt = library.ontology('flybrain')
        >>> ellipsoidBody = network.createRegion(ontologyTerm = flyBrainOnt.findTerm(name = 'Ellipsoid body'))
        
        If addSubTerms is true then sub-regions will be created for all sub-terms in the ontology.
         
        Returns the :class:`region <Network.Region.Region>` that is created.
        """

        region = Region(self, *args, **keywordArgs)
        self.addObject(region)

        if region.ontologyTerm is not None and addSubTerms:
            for term in region.ontologyTerm.parts:
                self.createRegion(ontologyTerm=term,
                                  parentRegion=region,
                                  addSubTerms=True)

        return region
 def range(self, event):
     """Initiate a range search using a selected rectangular region."""
     
     p = (event.x, self.toCartesian(event.y))
      
     if self.selectedRegion is None:
         self.selectedStart = Region(p[X],p[Y],  p[X],p[Y])
     self.selectedRegion = self.selectedStart.unionPoint(p)
     
     self.paint()
     
     # return (node,status) where status is True if draining entire tree rooted at node. Draw these
     # all in Yellow using another inorder traversal
     for pair in self.tree.range(self.selectedRegion):
         
         if pair[1]:
             self.canvas.create_rectangle(pair[0].region.x_min, self.toTk(pair[0].region.y_min), 
                                          pair[0].region.x_max, self.toTk(pair[0].region.y_max),
                                          fill='Red', stipple='gray12')
         else:
             p = pair[0][0]   # ignore data and grab point
             self.canvas.create_rectangle(p[X] - RectangleSize, self.toTk(p[Y]) - RectangleSize, 
                                          p[X] + RectangleSize, self.toTk(p[Y]) + RectangleSize, fill='Red')
     
     
     self.queryRect = self.canvas.create_rectangle(self.selectedRegion.x_min, self.toTk(self.selectedRegion.y_min),  
                                                  self.selectedRegion.x_max, self.toTk(self.selectedRegion.y_max), 
                                                  outline='Red', dash=(2, 4))
def change_fill_color_all_regions_based_on_my_count(soup):
    max_my_count = get_max_my_count_for_all_regions()
    for region in Region.create_all():
        change_fill_color_of_path(
            soup, region.name, get_region_count_fraction_color(
                region.my_count / max_my_count))
    prepare_legend(soup)
def load_vatic_regions(path):
    """Parse a VATIC output file to the list of lists consisting of regions for each time step.

    :param path: path of xml file
    :return: list of lists consisting of regions for each time step
    """
    max_polygon = 10000000000000
    tree = ElementTree.parse(path)
    root = tree.getroot()
    all_right_measures = [[] for i in range(250)]
    for child in root.findall('object'):
        print(child.tag)
        for act_count, subchild in enumerate(child):
            if subchild.tag != 'polygon':
                continue
            if act_count > max_polygon:
                raise RuntimeWarning("File has to many objects")

            polygon = list(subchild)
            t = int(polygon[0].text)
            down_lef_point = (int(polygon[1].find("x").text), int(polygon[1].find("y").text))
            up_right_point = (int(polygon[3].find("x").text), int(polygon[3].find("y").text))
            w = up_right_point[0]-down_lef_point[0]
            h = up_right_point[1]-down_lef_point[1]
            measure = Region(down_lef_point[0], down_lef_point[1], w, h)

            if len(all_right_measures) < t+1:
                _resize_list(all_right_measures, t + 1)
            all_right_measures[t].append(measure)
    for t, t_measure_list in enumerate(all_right_measures):
        print(len(t_measure_list), "|t=", t)
    print("Finish")
    return all_right_measures
Beispiel #41
0
    def range(self, event):
        """Initiate a range search using a selected rectangular region."""
        
        p = (event.x, self.toCartesian(event.y))
         
        if self.selectedRegion is None:
            self.selectedStart = Region(p[X],p[Y],  p[X],p[Y])
        self.selectedRegion = self.selectedStart.unionPoint(p)
        
        self.paint()
        
        # return (node,sub-tree) where sub-tree is True if draining entire tree
        # rooted at node. Draw these as shaded red rectangle to identify whole
        # sub-tree is selected.
        for pair in self.tree.range(self.selectedRegion):
            p = pair[0].point
            
            if pair[1]:
                self.canvas.create_rectangle(pair[0].region.x_min, self.toTk(pair[0].region.y_min), 
                                             pair[0].region.x_max, self.toTk(pair[0].region.y_max),
                                             fill='Red', stipple='gray12')
            else:
                self.canvas.create_rectangle(p[X] - BoxSize, self.toTk(p[Y]) - BoxSize, 
                                             p[X] + BoxSize, self.toTk(p[Y]) + BoxSize, fill='Red')

        self.queryRect = self.canvas.create_rectangle(self.selectedRegion.x_min, self.toTk(self.selectedRegion.y_min),  
                                                     self.selectedRegion.x_max, self.toTk(self.selectedRegion.y_max), 
                                                     outline='Red', dash=(2, 4))
Beispiel #42
0
    def fix_vertical_ratio(self, w1, h1, w_box, h_box, org_frame_heigth, org_frame_width):
        h_box_round = h_box // self.original_ratio.denominator * self.original_ratio.denominator
        if h_box_round < h_box:
            h_box_round = h_box_round + self.original_ratio.denominator

        w_round = (h_box_round * self.original_ratio.numerator) // self.original_ratio.denominator

        if h_box_round + h1 > org_frame_heigth:
            h_box_round = h_box_round - self.original_ratio.denominator
        h2 = h1 + h_box_round

        w_added = w_round - w_box
        if w_added >= 0:
            w1_temp = w1 - w_added // 2
            if w1_temp < 0:
                w_added = w_added - w1 - 1
                w1 = 0
                w2 = w1 + w_round
            else:
                w1 = w1_temp
                w2_temp = w1 + w_round
                if w2_temp >= org_frame_width:
                    excess = w2_temp - org_frame_width + 1
                    w1 = w1 - excess
                    if w1 < 0:
                        w1 = 0
                        w_box = org_frame_width
                        h1 = h1 + h_box//2
                        h_box = 1
                        return self.fix_vertical_ratio(w1, h1, w_box, h_box, org_frame_heigth, org_frame_width)
                w2 = w1 + w_round
        else:
            w1 = w1 + abs(w_added)//2
            w2 = w1 + w_round
        return Region(w1=w1, h1=h1, w2=w2, h2=h2)
Beispiel #43
0
    def fix_horizontal_ratio(self, w1, h1, w_box, h_box, org_frame_heigth, org_frame_width):
        w_box_round = w_box // self.original_ratio.numerator * self.original_ratio.numerator
        if w_box_round < w_box:
            w_box_round = w_box_round + self.original_ratio.numerator

        h_round = (w_box_round * self.original_ratio.denominator) // self.original_ratio.numerator

        if w_box_round + w1 > org_frame_width:
            w_box_round = w_box_round - self.original_ratio.numerator
        w2 = w1 + w_box_round

        h_added = h_round - h_box
        if h_added >=0:
            h1_temp = h1 - h_added // 2
            if h1_temp < 0:
                h_added = h_added - h1 - 1
                h1 = 0
                h2 = h1 + h_round
            else:
                h1 = h1_temp
                h2_temp = h1 + h_round
                if h2_temp >= org_frame_heigth:
                    excess = h2_temp - org_frame_heigth + 1
                    h1 = h1 - excess
                    if h1 < 0:
                        h1 = 0
                        h_box = org_frame_heigth
                        w1 = w1 + w_box//2
                        w_box = 1
                        return self.fix_vertical_ratio(w1, h1, w_box, h_box, org_frame_heigth, org_frame_width)
                h2 = h1 + h_round
        else:
            h1 = h1 + abs(h_added) // 2
            h2 = h1 + h_round
        return Region(w1=w1, h1=h1, w2=w2, h2=h2)
Beispiel #44
0
	def reset(self, region=None, exemptions=None):
		'''
		Method: reset
		Description: Reset cells inside the provided region whose coordinates do not also fall within any of the provided exemption ranges.
		Parameters: region=None, exemptions=None
			region: Region - A region for maze reset to span
			exemptions: Regions - A collection of regions for maze reset to avoid
		Return: None
		'''

		# Ensure that valid boundaries are set.
		if region is None:
			region = Region((0, 0), (self.get_width(), self.get_height()))

		# Reset all cells that do not fall inside any of the provided exempt ranges.
		for row in self.m_cells:

			# If the current row is inside the reset boundary, check for cells to reset inside that row.
			for cell in row:
				exempt = False

				# If the current cell is outside the reset boundary, move on to the next cell.
				if not region.contains(cell.m_position):
					continue

				# Check for the inclusion of each cell in each provided exempt range.
				if exemptions is not None:
					for exemption in exemptions:

						# Reset the boundary walls of the provided exempt ranges.
						border_directions = exemption.on_border(cell.m_position)
						for border_direction in border_directions:
							self.set_wall(cell, border_direction, True)

						# If the cell falls inside any of the provided exempt ranges, do not reset it.
						if exemption.contains(cell.m_position):
							exempt = True
							break

					# Do not reset exempt cells.
					if exempt:
						continue

				# Completely reset non-exempt cells.
				self.unvisit(cell)
				for direction in list(Direction):
					self.set_wall(cell, direction, True)
def testWithTweet():
    cnt = 0
    corpus_all = buildAllCorpus(element_type='tweets', debug=False)
    ei = EventInterface()
    ei.setDB('citybeat_experiment')
    ei.setCollection('twitter_candidate_events')
    cur = ei.getAllDocuments()
    print TwitterFeature.GenerateArffFileHeader()
    for event in cur:
        region = Region(event['region'])
        event = TwitterFeature(event, corpus=corpus_all[region.getKey()])
        if event.getActualValue() < 8:
            print '< 8'
            continue
        cnt += 1
        print event.extractFeatures()
    print  cnt, cur.count()
Beispiel #46
0
    def __init__(self, element_type, event=None):
        assert element_type in ['photos', 'tweets']
        self._element_type = element_type
        if not event is None:
            if type(event) is types.DictType:
                self._event = event
            else:
                self._event = event.toDict()

            r = Region(self._event['region'])
            r._roundTo8Digits()
            self._event['region'] = r.toDict()

            self.setActualValue(self._getActualValueByCounting())
        else:
            self._event = {}
            self._event[self._element_type] = []
Beispiel #47
0
 def createRegionObjects ( self, rIndeces, rEPs ):
     regionVertices = self.indexToVertex( self.vertices, rIndeces )
     # print len(regionVertices)
     for region, regionIndex in zip(regionVertices, rIndeces):
         for i in range(0, len(rEPs)):
             if self.pointInRegion ( rEPs[i], region ):
                 self.regions[i] = Region( i, rEPs[i], regionIndex )
                 continue
Beispiel #48
0
    def get_PCR_regions(self, global_seq):
        """Define PCR regions (left & right) delimited by the primer set.

        Args:
            global_seq (Bio.Seq.Seq): template sequence.
        Returns:
            pcr_dict (dict of str:regions.Region): dictionary of PCR1
                (left) and PCR2 (right) regions.
        """
        pcr1_start = self.PCR1F.s()
        pcr1_end = self.PCR1R.e()
        pcr2_start = self.PCR2F.s()
        pcr2_end = self.PCR2R.e()
        pcr1_region = Region((pcr1_start, pcr1_end), global_seq)
        pcr2_region = Region((pcr2_start, pcr2_end), global_seq)
        pcr_dict = {"PCR1": pcr1_region, "PCR2": pcr2_region}
        return pcr_dict
def get_all_regions_with_active_mysec():
    all_active_mysec_positions = Position.create_all_fitting_data(
        [["end_date", "=", ""]], title="MYSec")
    all_regions_with_active_mysec = set()
    for mysec in all_active_mysec_positions:
        all_regions_with_active_mysec.add(
            Region.create_by_name(mysec.region))
    return all_regions_with_active_mysec
Beispiel #50
0
 def correct(self, measure):
     """Correct the model based on real measures."""
     measures_array = np.array([measure.x, measure.y, measure.w, measure.h],
                               dtype=np.float32)
     estimated = self.kalman_filter.correct(measures_array)
     estimated = KalmanTracker.__decapsulate_measure(estimated)
     self.act_prediction = Region.from_matrix(estimated)
     return self.act_prediction
Beispiel #51
0
	def trailblaze(self, source_cell, direction=None, region=None, exemptions=None):
		'''
		Method: trailblaze
		Description: Trailblaze from the source cell in the specified direction, knocking down both sides of the wall between the source and the target.
		Parameters: source_cell, direction=None, region=None, exemptions=None
			source_cell: Cell - The cell to trailblaze from
			direction: Direction - The direction to trailblaze in (None simply visits the source cell)
			region: Region - A region for trailblazing to span
			exemptions: Regions - A collection of regions for trailblazing to avoid
		Return: Cell - The target cell is trailblazing was successful, and None otherwise
		'''

		# If the direction is None, "trailblaze" to the source cell by marking it as visited.
		if direction is None:
			self.visit(source_cell)
			return source_cell

		# Ensure that valid boundaries are set.
		if region is None:
			region = Region((0, 0), (self.get_width(), self.get_height()))

		# Grab the target cell.
		target_cell = self.get_neighbor_cell(source_cell, direction)

		# If the target cell is invalid, return without trailblazing.
		if target_cell is None:
			return None

		# If the target cell is exempt, return without trailblazing.
		if exemptions is not None:
			for exemption in exemptions:
				if exemption.contains(target_cell.m_position):
					return None

		# If non-exempt target cell is valid, trailblaze to it.
		if not target_cell.is_visited() and region.contains(target_cell.m_position):

			# Remove wall between source and target cells.
			self.set_wall(source_cell, direction, False)

			# Visit the target cell.
			self.visit(target_cell)

			return target_cell
def test():
    coordinates = [InstagramConfig.photo_min_lat,
                   InstagramConfig.photo_min_lng,
                   InstagramConfig.photo_max_lat,
                   InstagramConfig.photo_max_lng
    ]
    huge_region = Region(coordinates)
    regions = huge_region.divideRegions(5, 5)  #Warning: DO NOT SET THIS BELOW 5 OR MEMORY OVERFLOW

    for i in range(25):
        test_region = regions[i]
        test_region.display()
        test_region._region['min_lat'] = 40.7329
        test_region._region['min_lng'] = -73.9957
        test_region._region['max_lat'] = 40.7383
        test_region._region['max_lng'] = -73.9844
        ts = InstagramTimeSeries(test_region, str(1360519908), str(1365519908))
        ts = ts.buildTimeSeries()
        for t in ts:
            print t
        break
    def get_region_from_seeds(self, seed_cords):
        '''
        Get corresponding region from seeds.
        Inputs:
              seed_cords: the cordinates of the seed

        '''
        if not isinstance(seed_cords, np.ndarray):
            raise ValueError('get_region_from_seeds: get_region_from_seeds is not np.ndarray!')

        region = None
        if self._unique_image != None:
            region_ids = self._unique_image[seed_cords[:, 0], seed_cords[:, 1], seed_cords[:, 2]]
            if len(region_ids) == 1:
                region = Region(seed_cords, region_ids[0], self._image.shape, None, None)
            else:
                for region_id in region_ids:
                    sub_region = self.get_region_from_index(region_id - 1)
                    region.add_region()

        return region
Beispiel #54
0
 def getRegions(self):
     plaza_squares = Region(self.coordinates)
     plaza_squares = plaza_squares.divideRegions(25,25)
     valid_squares = []
     ei = ElementInterface('citybeat_production', 'photos', 'photos')
     bad_number = 0
     all_number = 0
     for region in plaza_squares:
         all_number += 1
         mid_point = region.getMidCoordinates()
         point = Point( mid_point )
         if not point.within( self.valid_poly ):
             print 'not valid ' 
             continue
         cnt = 0
         bad_number += 1
         for p in ei.rangeQuery(region):
             cnt += 1
         valid_squares.append( (region, cnt) )
         print 'cnt = ',cnt 
     self.plaza_squares = valid_squares
     print "all number = ",all_number, " bad_number = ",bad_number
Beispiel #55
0
def main():
    """Creates a specified region and downloads files from USGS."""
    # example:
    # ./GetRegion.py --name BlockIsland --ymax 41.2378 --ymin 41.1415 --xmin -71.6202 --xmax -71.5332

    # defaults
    default_elevationIDs = ','.join(Region.productIDs['elevation'])
    default_landcoverIDs = ','.join(Region.productIDs['landcover'])

    # parse options and get results
    parser = argparse.ArgumentParser(description='Create regions and download files from USGS.')
    parser.add_argument('--name', required=True, type=str, help='name of the region to be generated')
    parser.add_argument('--xmax', required=True, type=float, help='easternmost longitude (west is negative)')
    parser.add_argument('--xmin', required=True, type=float, help='westernmost longitude (west is negative)')
    parser.add_argument('--ymax', required=True, type=float, help='northernmost latitude (south is negative)')
    parser.add_argument('--ymin', required=True, type=float, help='southernmost longitude (south is negative)')
    parser.add_argument('--tilesize', type=int, help='tilesize value (default %d)' % Region.tilesize)
    parser.add_argument('--scale', type=int, help='scale value (default %d)' % Region.scale)
    parser.add_argument('--vscale', type=int, help='vscale value (default %d)' % Region.vscale)
    parser.add_argument('--trim', type=int, help='trim value (default %d)' % Region.trim)
    parser.add_argument('--sealevel', type=int, help='sealevel value (default %d)' % Region.sealevel)
    parser.add_argument('--maxdepth', type=int, help='maxdepth value (default %d)' % Region.maxdepth)
    parser.add_argument('--elevationIDs', default=default_elevationIDs, type=checkElevationIDs, help='ordered list of product IDs (default %s)' % default_elevationIDs)
    parser.add_argument('--landcoverIDs', default=default_landcoverIDs, type=checkLandcoverIDs, help='ordered list of product IDs (default %s)' % default_landcoverIDs)
    parser.add_argument('--disable-ore', action='store_false', dest='doOre', default=True, help='disable ore generation')
    parser.add_argument('--enable-schematics', action='store_true', dest='doSchematics', default=False, help='enable schematic usage')
    parser.add_argument('--debug', action='store_true', help='enable debug output')
    args = parser.parse_args()

    # enable debug
    if (args.debug):
        logging.getLogger('suds.client').setLevel(logging.DEBUG)

    # create the region
    print "Creating new region %s..." % args.name
    myRegion = Region(name=args.name, xmax=args.xmax, xmin=args.xmin, ymax=args.ymax, ymin=args.ymin, scale=args.scale, vscale=args.vscale, trim=args.trim, tilesize=args.tilesize, sealevel=args.sealevel, maxdepth=args.maxdepth, lcIDs=args.landcoverIDs, elIDs=args.elevationIDs, doOre=args.doOre, doSchematics=args.doSchematics)

    print "Retrieving files..."
    myRegion.getfiles()
Beispiel #56
0
def _polygonCircle(sp):
	sp.order("polygon")
	p = sp.shapes[0]
	c0 = sp.shapes[1]
	
	intersectList = []
	for segment in p.segments():
		c = c0.copy()
		s = segment.copy()
		
		# Maps circle's center to origin, line to horizontal
		toMove = c.center.mul(-1)
		toRotate = -s.angle()
		c.move(toMove)
		s.move(toMove)
		s.rotate(toRotate)
		
		# Calculates intersects
		segmentHeight = s.p1.y
		segmentSpan = Region(s.p1.x, s.p2.x)
		segmentPoints = []
		if abs(segmentHeight) >= abs(c.radius):
			continue
		else:
			xMaxPt = math.sqrt(c.radius ** 2 - segmentHeight ** 2)
			xMinPt = -xMaxPt
			if segmentSpan.contains(xMinPt):
				segmentPoints.append(Vector(xMinPt, segmentHeight))
			if segmentSpan.contains(xMaxPt):
				segmentPoints.append(Vector(xMaxPt, segmentHeight))
		
		# Translates solutions back to original coordinates
		for spt in segmentPoints:
			spt = spt.rotate(-toRotate)
			spt = spt.sub(toMove)
			intersectList.append(spt)
		
	return intersectList
def test():
    coordinates = [InstagramConfig.photo_min_lat,
                   InstagramConfig.photo_min_lng,
                   InstagramConfig.photo_max_lat,
                   InstagramConfig.photo_max_lng
    ]
    huge_region = Region(coordinates)
    alarm_region_size = 25
    regions = huge_region.divideRegions(25, 25)
    filtered_regions = huge_region.filterRegions(region_list=regions, test=True, n=alarm_region_size,
                                                 m=alarm_region_size)

    for i in range(1):
        test_region = regions[i]
        test_region._region['min_lat'] = 40.7329
        test_region._region['min_lng'] = -73.9957
        test_region._region['max_lat'] = 40.7383
        test_region._region['max_lng'] = -73.9844
        test_region.display()
        ts = TwitterTimeSeries(test_region, '1364829908', '1365693908')
        ts = ts.buildTimeSeries()
        for d in ts:
            print d
Beispiel #58
0
    def __from_encoded(service, encoded_droplet):
        size = Size.get(service, encoded_droplet['size_id'])
        image = Image.get(service, encoded_droplet['image_id'])
        region = Region.get(service, encoded_droplet['region_id'])
        backups = encoded_droplet['backups_active'] is not None
        status = encoded_droplet['status']

        droplet = Droplet(
            status=status,
            droplet_id=encoded_droplet['id'],
            name=encoded_droplet['name'],
            size=size,
            image=image,
            ip_address=encoded_droplet['ip_address'],
            region=region,
            backups=backups
        )
        return droplet
Beispiel #59
0
	def __init__(self, size=(DEFAULT_WIDTH, DEFAULT_HEIGHT), scale=DEFAULT_SCALE):
		'''
		Method: __init__
		Description: Maze constructor
		Parameters: size=(DEFAULT_WIDTH, DEFAULT_HEIGHT), scale=DEFAULT_SCALE
			size: 2-Tuple - The dimensional lengths of the maze
				[0] - Maze x-dimensional length
				[1] - Maze y-dimensional length
			scale: The printing scale of the maze, used to determine spacing
		Return: None
		'''

		# The width/height of the maze.
		self.m_size = size
		# Scale must be an even number for proper pretty-printing.
		self.m_scale = 2 * scale
		# The individual cells of the maze.
		self.m_cells = [[Cell(Cell.UNVISITED_STRING, (x, y)) for x in range(self.get_width())] for y in range(self.get_height())]
		# A region representing the span of the maze.
		self.m_region = Region((0, 0), (self.get_width(), self.get_height()))
Beispiel #60
0
    def _region_leaf( level, op ):

        token, details = op['token'], op['orig']

        if token != 'KW_Region':
            parse_def = token + '<' + ' '.join( details ) + '>'
            region = Region('leaf', rdef, domain, parse_def=parse_def)

        if token == 'KW_Region':
            details = details[1][2:]
            aux = regions.find( details )
            if not aux:
                raise ValueError, 'region %s does not exist' % details
            else:
                if rdef[:4] == 'copy':
                    region = aux.copy()
                else:
                    region = aux

        elif token == 'KW_All':
            region.set_vertices( nm.arange( domain.mesh.n_nod,
                                            dtype = nm.int32 ) )
        elif token == 'E_NIR':
            where = details[2]

            if where[0] == '[':
                out = nm.array( eval( where ), dtype = nm.int32 )
                assert_( nm.amin( out ) >= 0 )
                assert_( nm.amax( out ) < domain.mesh.n_nod )
            else:
                coors = domain.get_mesh_coors()
                x = coors[:,0]
                y = coors[:,1]
                if domain.mesh.dim == 3:
                    z = coors[:,2]
                else:
                    z = None
                coor_dict = {'x' : x, 'y' : y, 'z': z}

                out = nm.where( eval( where, {}, coor_dict ) )[0]
            region.set_vertices( out )

        elif token == 'E_NOS':

            if domain.fa: # 3D.
                fa = domain.fa
            else:
                fa = domain.ed

            flag = fa.mark_surface_facets()
            ii = nm.where( flag > 0 )[0]
            aux = nm.unique(fa.facets[ii])
            if aux[0] == -1: # Triangular faces have -1 as 4. point.
                aux = aux[1:]

            region.can_cells = False
            region.set_vertices( aux )

        elif token == 'E_NBF':
            where = details[2]

            coors = domain.get_mesh_coors()

            fun = functions[where]
            out = fun(coors, domain=domain)

            region.set_vertices( out )

        elif token == 'E_EBF':
            where = details[2]

            coors = domain.get_mesh_coors()

            fun = functions[where]
            out = fun(coors, domain=domain)

            region.set_cells( out )

        elif token == 'E_EOG':

            group = int( details[3] )

            ig = domain.mat_ids_to_i_gs[group]
            group = domain.groups[ig]
            region.set_from_group( ig, group.vertices, group.shape.n_el )

        elif token == 'E_NOG':

            try:
                group = int(details[3])
                group_nodes = nm.where(domain.mesh.ngroups == group)[0]

            except ValueError:
                try:
                    group_nodes = domain.mesh.nodal_bcs[details[3]]

                except KeyError:
                    msg = 'undefined nodal group! (%s)' % details[3]
                    raise ValueError(msg)

            region.set_vertices(group_nodes)

        elif token == 'E_ONIR':
            aux = regions[details[3][2:]]
            region.set_vertices( aux.all_vertices[0:1] )

        elif token == 'E_NI':
            region.set_vertices(nm.array([int(ii) for ii in details[1:]],
                                         dtype=nm.int32))

        elif token == 'E_EI1':
            region.set_cells({0 : nm.array([int(ii) for ii in details[1:]],
                                           dtype=nm.int32)})

        elif token == 'E_EI2':
            num = len(details[1:]) / 2

            cells = {}
            for ii in range(num):
                ig, iel = int(details[1+2*ii]), int(details[2+2*ii])
                cells.setdefault(ig, []).append(iel)

            region.set_cells(cells)

        else:
            output( 'token "%s" unkown - check regions!' % token )
            raise NotImplementedError
        return region