def bounds_of(self) -> Bounds: box = Bounds() for child in self.members: cbox = child.parent_space_bounds_of() box.add_box(cbox) return box
def test_splitting_z_wide_box(self): box = Bounds(Point(-1, -2, -3), Point(5, 3, 7)) (left, right) = Bounds.split_bounds(box) self.assertEqual(left.min, Point(-1, -2, -3)) self.assertEqual(left.max, Point(5, 3, 2)) self.assertEqual(right.min, Point(-1, -2, 2)) self.assertEqual(right.max, Point(5, 3, 7))
def test_tranforming_bounding_box(self): box = Bounds(Point(-1, -1, -1), Point(1, 1, 1)) matrix = Transformations.rotation_x(math.pi / 4).dot( Transformations.rotation_y(math.pi / 4)) box2 = box.transform(matrix) self.assertEqual(box2.min, Point(-1.4142, -1.7071, -1.7071)) self.assertEqual(box2.max, Point(1.4142, 1.7071, 1.7071))
def test_splitting_perfect_cube(self): box = Bounds(Point(-1, -4, -5), Point(9, 6, 5)) (left, right) = Bounds.split_bounds(box) self.assertEqual(left.min, Point(-1, -4, -5)) self.assertEqual(left.max, Point(4, 6, 5)) self.assertEqual(right.min, Point(4, -4, -5)) self.assertEqual(right.max, Point(9, 6, 5))
def test_add_points_to_empty_bounding_box(self): box = Bounds() p1 = Point(-5, 2, 0) p2 = Point(7, 0, -3) box.add_point(p1) box.add_point(p2) self.assertEqual(box.min, Point(-5, 0, -3)) self.assertEqual(box.max, Point(7, 2, 0))
def __init__(self, filename=None): ''' filename: string, absolute or relative filename of an SVG file ''' self.filename = filename self.paths = [] self.path_by_id = {} self.bounds = Bounds() self.batch = None
def __init__(self, tag=None): self.id = None self.loops = [] self.color = (0, 0, 0) self.bounds = Bounds() self.triangles = None if tag: self.parse(tag)
def test_box_contains_box(self): box = Bounds(Point(5, -2, 0), Point(11, 4, 7)) BoundsResult = namedtuple("BoundsResult", ["min", "max", "result"]) bounds_results = [ BoundsResult(Point(5, -2, 0), Point(11, 4, 7), True), BoundsResult(Point(6, -1, 1), Point(10, 3, 6), True), BoundsResult(Point(4, -3, -1), Point(10, 3, 6), False), BoundsResult(Point(6, -1, 1), Point(12, 5, 8), False) ] for bounds_result in bounds_results: box2 = Bounds(bounds_result.min, bounds_result.max) self.assertEqual(box.box_contains_box(box2), bounds_result.result)
def flushAll(self): ''' Flush entire drawable ''' # bounds of entire drawable bounds = Bounds.initFromGIMPBounds(0, 0, self.parentDrawable.width, self.parentDrawable.height) self.flush(bounds)
def bounds_of(self) -> Bounds: a = abs(self.minimum) b = abs(self.maximum) limit = max(a, b) return Bounds(Point(-limit, self.minimum, -limit), Point(limit, self.maximum, limit))
def test_box_countains_point(self): box = Bounds(Point(5, -2, 0), Point(11, 4, 7)) PointResult = namedtuple("PointResult", ["point", "result"]) point_results = [ PointResult(Point(5, -2, 0), True), PointResult(Point(11, 4, 7), True), PointResult(Point(8, 1, 3), True), PointResult(Point(3, 0, 3), False), PointResult(Point(8, -4, 3), False), PointResult(Point(8, 1, -1), False), PointResult(Point(13, 1, 3), False), PointResult(Point(8, 5, 3), False), PointResult(Point(8, 1, 8), False) ] for point_result in point_results: p = point_result.point self.assertEqual(box.box_contains_point(p), point_result.result)
def test_intersect_ray_with_bounding_box_at_origin(self): box = Bounds(Point(-1, -1, -1), Point(1, 1, 1)) RayResult = namedtuple("RayResult", ["origin", "direction", "result"]) ray_results = [ RayResult(Point(5, 0.5, 0), Vector(-1, 0, 0), True), RayResult(Point(-5, 0.5, 0), Vector(1, 0, 0), True), RayResult(Point(0.5, 5, 0), Vector(0, -1, 0), True), RayResult(Point(0.5, -5, 0), Vector(0, 1, 0), True), RayResult(Point(0.5, 0, 5), Vector(0, 0, -1), True), RayResult(Point(0.5, 0, -5), Vector(0, 0, 1), True), RayResult(Point(0, 0.5, 0), Vector(0, 0, 1), True), RayResult(Point(-2, 0, 0), Vector(2, 4, 6), False), RayResult(Point(0, -2, 0), Vector(6, 2, 4), False), RayResult(Point(0, 0, -2), Vector(4, 6, 2), False), RayResult(Point(2, 0, 2), Vector(0, 0, -1), False), RayResult(Point(0, 2, 2), Vector(0, -1, 0), False), RayResult(Point(2, 2, 0), Vector(-1, 0, 0), False) ] for ray_result in ray_results: direction = Vector.normalize(ray_result.direction) r = Ray(ray_result.origin, direction) self.assertEqual(box.intersects(r), ray_result.result)
def get_bounds(self): max = np.max(self.geojson['coordinates'], axis=0) max_lon = max[0] max_lat = max[1] max_ele = max[2] min = np.min(self.geojson['coordinates'], axis=0) min_lon = min[0] min_lat = min[1] min_ele = min[2] self.bounds = Bounds(min_lon, max_lon, min_lat, max_lat)
def test_intersect_ray_with_noncubic_bouding_box(self): box = Bounds(Point(5, -2, 0), Point(11, 4, 7)) RayResult = namedtuple("RayResult", ["origin", "direction", "result"]) ray_results = [ RayResult(Point(15, 1, 2), Vector(-1, 0, 0), True), RayResult(Point(-5, -1, 4), Vector(1, 0, 0), True), RayResult(Point(7, 6, 5), Vector(0, -1, 0), True), RayResult(Point(9, -5, 6), Vector(0, 1, 0), True), RayResult(Point(8, 2, 12), Vector(0, 0, -1), True), RayResult(Point(6, 0, -5), Vector(0, 0, 1), True), RayResult(Point(8, 1, 3.5), Vector(0, 0, 1), True), RayResult(Point(9, -1, -8), Vector(2, 4, 6), False), RayResult(Point(8, 3, -4), Vector(6, 2, 4), False), RayResult(Point(9, -1, -2), Vector(4, 6, 2), False), RayResult(Point(4, 0, 9), Vector(0, 0, -1), False), RayResult(Point(8, 6, -1), Vector(0, -1, 0), False), RayResult(Point(12, 5, 4), Vector(-1, 0, 0), False) ] for ray_result in ray_results: direction = Vector.normalize(ray_result.direction) r = Ray(ray_result.origin, direction) self.assertEqual(box.intersects(r), ray_result.result)
def __init__(self, quantization=1e4, id_key='id', property_transform=property_transform, system=False, simplify=False, stitch_poles=False): self.ln = Line(quantization) self.id_func = lambda x: x[id_key] self.quantization = quantization self.system = system self.property_transform = property_transform self.bounds = Bounds() if simplify: self.simplify = Simplify(simplify) else: self.simplify = False if stitch_poles: self.stitch_poles = Stitch() else: self.stitch_poles = False self.feature_dir = mkdtemp() self.feature_path = [] self.feature_db = {} self.feature_length = 0 class Coincidences(Types): def __init__(self, ln): self.ln = ln def line(self, line): for point in line: lines = self.ln.arcs.coincidence_lines(point) if not line in lines: lines.append(line) self.coincidences = Coincidences(self.ln)
def bounds_of(self) -> Bounds: box = Bounds() left_cbox = self.left.parent_space_bounds_of() right_cbox = self.right.parent_space_bounds_of() box.add_box(left_cbox) box.add_box(right_cbox) return box
def Run(self): print("Analyzing problems") with open(self.options.currentProblemFile, 'rt') as problemsFile: problemIndex = 0 for line in problemsFile: problemIndex = problemIndex + 1 print("\n=> Problem #" + str(problemIndex) + " will be analyzed") builder = Builder(line, self.options) problem = self.LoadProblem(builder) problem.SetMeasure(Measure(problem)) problem.SetBounds(Bounds(problem)) problem.bounds.CalculateBounds() solver = Solver(problem) solver.Solve() problem.measure.Write() print("Finished analyzer run") # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
def get_rendering_bounds(self): center_lat = (self.bounds.se.lat + self.bounds.nw.lat) / 2.0 center_lon = (self.bounds.se.lon + self.bounds.nw.lon) / 2.0 center = Point(center_lon, center_lat) center.project(self.rendering_zoom) self.center = center top_left_x = center.x - (self.render_width / 2.0) top_left_y = center.y - (self.render_height / 2.0) top_left = Point.from_xy(top_left_x, top_left_y) top_left.unproject(self.rendering_zoom) bottom_x = center.x + (self.render_width / 2.0) bottom_y = center.y + (self.render_height / 2.0) bottom_right = Point.from_xy(bottom_x, bottom_y) bottom_right.unproject(self.rendering_zoom) self.rendering_bounds = Bounds(top_left.lon, bottom_right.lon, bottom_right.lat, top_left.lat) print self.rendering_bounds
def __init__(self): ## Cria os tipos que estão disponíveis self.bounds = Bounds() self.action = Action() self.loop = Functions() self.math = Math() self.variables = Variables() ## Adicona os tipos acima em uma lista self.buttons = [ self.bounds, self.action, self.loop, self.math, self.variables ] ##Variavel que armazena o valor do botão que está ativo. Em caso de False, nenhum está self.buttonActive = False ## Define o Botão de Compilar self.sizeButtonComp = [75, 50] self.buttonComp = pygame.image.load( os.path.join("img", "buttonCompilar.png")).convert_alpha() self.buttonComp = pygame.transform.scale(self.buttonComp, self.sizeButtonComp) self.posButtonComp = [10, 480]
from load_map import LoadMap from bounds import Bounds # from navigation import Navigation map = LoadMap('map.csv', start_row=4, start_col=0) current_loc = map.start_point bounds = Bounds(current_loc).interpret() print(bounds)
import numpy as np import math from bounds import Bounds from src.particleSwarmOptimization.pso import PSO from src.particleSwarmOptimization.structure.particle import Particle np.set_printoptions(suppress=True) errors = [] bounds = Bounds(-10, 10) # Create the pso with the nn weights num_particles = 7 inertia_weight = 0.729 cognitiveConstant = 1.49 socialConstant = 1.49 num_dimensions = 50 # Configure PSO pso = PSO(bounds, num_particles, inertia_weight, cognitiveConstant, socialConstant) def error(position): err = 0.0 for i in range(len(position)): xi = position[i] err += (xi * xi) - (10 * math.cos(2 * math.pi * xi)) + 10 return err
class Topology: def __init__(self, quantization=1e4, id_key='id', property_transform=property_transform, system=False, simplify=False, stitch_poles=False): self.ln = Line(quantization) self.id_func = lambda x: x[id_key] self.quantization = quantization self.system = system self.property_transform = property_transform self.bounds = Bounds() if simplify: self.simplify = Simplify(simplify) else: self.simplify = False if stitch_poles: self.stitch_poles = Stitch() else: self.stitch_poles = False self.feature_dir = mkdtemp() self.feature_path = [] self.feature_db = {} self.feature_length = 0 class Coincidences(Types): def __init__(self, ln): self.ln = ln def line(self, line): for point in line: lines = self.ln.arcs.coincidence_lines(point) if not line in lines: lines.append(line) self.coincidences = Coincidences(self.ln) def start(self): oversize = self.bounds.x0 < -180 - E or self.bounds.x1 > 180 + E or self.bounds.y0 < -90 - E or self.bounds.y1 > 90 + E if not self.system: if oversize: self.system = systems["cartesian"] else: self.system = systems["spherical"] if self.system == systems['spherical']: if self.bounds.x0 < -180 + E: self.bounds.x0 = -180 if self.bounds.x1 > 180 - E: self.bounds.x1 = 180 if self.bounds.y0 < -90 + E: self.bounds.y0 = -90 if self.bounds.y1 > 90 - E: self.bounds.y1 = 90 if is_infinit(self.bounds.x0): self.bounds.x0 = 0 if is_infinit(self.bounds.x1): self.bounds.x1 = 0 if is_infinit(self.bounds.y0): self.bounds.y0 = 0 if is_infinit(self.bounds.y1): self.bounds.y1 = 0 if not self.quantization: self.quantization = self.bounds.x1 + 1 self.bounds.x0 = self.bounds.y0 = 0 [self.kx, self.ky] = make_ks(self.quantization, self.bounds.x0, self.bounds.x1, self.bounds.y0, self.bounds.y1) self.quant = Quantize(self.bounds.x0, self.bounds.y0, self.kx, self.ky, self.system.distance) self.clock = Clock(self.system.ring_area) #Convert features to geometries, and stitch together arcs. class Topo(Types): def __init__(self, ln, id_func, property_transform): self.ln = ln self.id_func = id_func self.property_transform = property_transform def Feature(self, feature): geometry = feature["geometry"] if feature['geometry'] == None: geometry = {} if 'id' in feature: geometry['id'] = feature['id'] if 'properties' in feature: geometry['properties'] = feature['properties'] return self.geometry(geometry) def FeatureCollection(self, collection): collection['type'] = "GeometryCollection" collection['geometries'] = map(self.Feature, collection['features']) del collection['features'] return collection def GeometryCollection(self, collection): collection['geometries'] = map(self.geometry, collection['geometries']) def MultiPolygon(self, multiPolygon): multiPolygon['arcs'] = map( lambda poly: map(self.ln.line_closed, poly), multiPolygon['coordinates']) def Polygon(self, polygon): polygon['arcs'] = map(self.ln.line_closed, polygon['coordinates']) def MultiLineString(self, multiLineString): multiLineString['arcs'] = map(self.ln.line_open, multiLineString['coordinates']) def LineString(self, lineString): lineString['arcs'] = self.ln.line_open( lineString['coordinates']) def geometry(self, geometry): if geometry == None: geometry = {} else: Types.geometry(self, geometry) geometry['id'] = self.id_func(geometry) if geometry['id'] == None: del geometry['id'] properties0 = geometry['properties'] if properties0: properties1 = {} del geometry['properties'] for key0 in properties0: if self.property_transform(properties1, key0, properties0[key0]): geometry['properties'] = properties1 if 'arcs' in geometry: del geometry['coordinates'] return geometry self.topo = Topo(self.ln, self.id_func, self.property_transform) AddMessage('looping through ' + str(self.feature_length) + ' features again') for db in self.feature_db: for i in self.feature_db[db]: #AddMessage('on '+str(i)) self.tweak(self.feature_db[db], i) def dump(self, f): self.start() #print('writing') f.write('{"type":"Topology","bbox":') dump([self.bounds.x0, self.bounds.y0, self.bounds.x1, self.bounds.y1], f) f.write(',"transform":') dump( { 'scale': [1.0 / self.kx, 1.0 / self.ky], 'translate': [self.bounds.x0, self.bounds.y0] }, f) #print('dumping objects') f.write(',"objects":') i = 0 AddMessage('one last time') for thing in self.get_objects(): i += 1 #AddMessage('on ' + str(i) + ' for the last time') f.write(thing) #print('dumping arcs') f.write(',"arcs":[') first = True for arc in self.ln.get_arcs(): if first: first = False else: f.write(',') dump(arc, f) f.write(']}') def add(self, object, feature): if not (object in self.feature_db): path = self.feature_dir + '/' + object self.feature_path.append(path) self.feature_db[object] = shelve.open(path) storage = self.feature_db[object] if self.simplify: feature = self.simplify.Feature(feature) if self.stitch_poles: self.stitch_poles.Feature(feature) self.bounds.Feature(feature) self.feature_db[object][str(self.feature_length)] = feature self.feature_length += 1 def tweak(self, db, i): feature = db[i] self.quant.Feature(feature) feature = self.clock.clock(feature) self.coincidences.Feature(feature) db[i] = feature def get_objects(self): firstDB = True yield '{' for db in self.feature_db: if firstDB: firstDB = False else: yield ',' first = True yield '"' + db + '":{"type":"GeometryCollection","geometries":[' for object in self.feature_db[db]: if first: first = False else: yield ',' yield dumps(self.topo.Feature(self.feature_db[db][object])) self.feature_db[db].close() yield ']}' for path in self.feature_path: remove(path) yield '}' def object_factory(self, object): return partial(self.add, object)
def test_add_bounding_box_to_another(self): box1 = Bounds(Point(-5, -2, 0), Point(7, 4, 4)) box2 = Bounds(Point(8, -7, -2), Point(14, 2, 8)) box1.add_box(box2) self.assertEqual(box1.min, Point(-5, -7, -2)) self.assertEqual(box1.max, Point(14, 4, 8))
class SvgBatch(object): ''' Maintains an ordered list of paths, each one corresponding to a path tag from an SVG file. Creates a pylget Batch containing all these paths, for rendering as a single OpenGL GL_TRIANGLES indexed vert primitive. ''' def __init__(self, filename=None): ''' filename: string, absolute or relative filename of an SVG file ''' self.filename = filename self.paths = [] self.path_by_id = {} self.bounds = Bounds() self.batch = None @property def width(self): return self.bounds.width @property def height(self): return self.bounds.height def __getattr__(self, name): if hasattr(self.path_by_id, name): return getattr(self.path_by_id, name) raise AttributeError(name) def __getitem__(self, index): return self.path_by_id[index] def parse_svg(self): ''' Populates self.paths from the <path> tags in the svg file. ''' doc = xml.dom.minidom.parse(self.filename) path_tags = doc.getElementsByTagName('path') for path_tag in path_tags: path = Path(path_tag) self.paths.append(path) self.path_by_id[path.id] = path self.bounds.add_bounds(path.bounds) def center(self): ''' Offset all verts put center of svg at the origin ''' center = self.bounds.get_center() for path in self.paths: path.offset(-center[0], -center[1]) self.bounds.offset(-center[0], -center[1]) def create_batch(self): ''' Returns a new pyglet Batch object populated with indexed GL_TRIANGLES ''' if self.batch is None: self.batch = Batch() self.parse_svg() self.center() for path in self.paths: path.tessellate() path.add_to_batch(self.batch) return self.batch
def bounds_of(self) -> Bounds: box = Bounds() box.add_point(self.p1) box.add_point(self.p2) box.add_point(self.p3) return box
def bounds_of(self) -> Bounds: min = Point(-1, -1, -1) max = Point(1, 1, 1) return Bounds(min, max)
def bounds_of(self) -> Bounds: min = Point(-1, self.minimum, -1) max = Point(1, self.maximum, 1) return Bounds(min, max)
def __init__(self): self.loops = [] self.bounds = Bounds()
class Path(object): ''' id : string, copied from the svg tag's id attribute, or an autogenerated int if there is no id attr. loops : a list of loops. A loop is a list of vertices. A vertex is a pair of floats or ints. color : triple of unsigned bytes, (r, g, b) A Path corresponds to a single SVG path tag. It may contain many independant loops which represent either disjoint polygons or holes. ''' next_id = 1 def __init__(self, tag=None): self.id = None self.loops = [] self.color = (0, 0, 0) self.bounds = Bounds() self.triangles = None if tag: self.parse(tag) def get_id(self, attributes): if 'id' in attributes.keys(): return attributes['id'].value else: self.next_id += 1 return self.next_id - 1 def parse_color(self, color): ''' color : string, eg: '#rrggbb' or 'none' (where rr, gg, bb are hex digits from 00 to ff) returns a triple of unsigned bytes, eg: (0, 128, 255) ''' if color == 'none': return None return ( int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) def parse_style(self, style): ''' style : string, eg: fill:#ff2a2a;fill-rule:evenodd;stroke:none;stroke-width:1px; stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1 returns color as a triple of unsigned bytes: (r, g, b), or None ''' style_elements = style.split(';') while style_elements: element = style_elements.pop() if element.startswith('fill:'): return self.parse_color(element[5:]) return None def parse(self, tag): self.id = self.get_id(tag.attributes) if 'style' in tag.attributes.keys(): style_data = tag.attributes['style'].value self.color = self.parse_style(style_data) path_data = tag.attributes['d'].value parser = PathDataParser() path_tuple = parser.to_tuples(path_data) tracer = SvgLoopTracer() self.loops = tracer.to_loops(path_tuple) self.bounds.add_bounds(tracer.bounds) def offset(self, x, y): for loop in self.loops: for idx, vert in enumerate(loop): loop[idx] = (vert[0] + x, vert[1] + y) self.bounds.offset(x, y) def tessellate(self): if self.color: self.triangles = tesselate(self.loops) def _serialise_verts(self): for vert in self.triangles: yield vert[0] yield vert[1] def add_to_batch(self, batch): ''' Adds itself to the given batch, as as single primitive of indexed GL_TRIANGLES. Note that Batch will aggregate all such additions into a single large primitive. ''' if self.triangles: num_verts = len(self.triangles) serial_verts = list(self._serialise_verts()) colors = self.color * num_verts indices = range(num_verts) batch.add_indexed( num_verts, GL_TRIANGLES, None, indices, ('v2f/static', serial_verts), ('c3B/static', colors), )
def __init__(self, dimension): self.bounds = Bounds([Bound([0, 0], "continuous")] * dimension) self.global_optimum = [0] * dimension
class SvgLoopTracer(object): def __init__(self): self.loops = [] self.bounds = Bounds() def get_point(self, command): x = command[1] y = -command[2] self.bounds.add_point(x, y) return x, y def onMove(self, command): x, y = self.get_point(command) self.current_path = [(x, y)] def onLine(self, command): x, y = self.get_point(command) self.current_path.append((x, y)) def onClose(self, command): if self.current_path[0] == self.current_path[-1]: self.current_path = self.current_path[:-1] if len(self.current_path) < 3: raise ParseError('loop needs 3 or more verts') self.loops.append(self.current_path) self.current_path = None def onBadCommand(self, action): msg = 'unsupported svg path command: %s' % (action,) raise ParseError(msg) def to_loops(self, commands): ''' commands : list of tuples, as output from to_tuples() method, eg: [('M', 1, 2), ('L', 3, 4), ('L', 5, 6), ('z')] Interprets the command characters at the start of each tuple to return a list of loops, where each loop is a closed list of verts, and each vert is a pair of ints or floats, eg: [[1, 2, 3, 4, 5, 6]] Note that the final point of each loop is eliminated if it is equal to the first. SVG defines commands: M x,y: move, start a new loop L x,y: line, draw boundary H x: move horizontal V y: move vertical Z: close current loop - join to start point Lower-case command letters (eg 'm') indicate a relative offset. See http://www.w3.org/TR/SVG11/paths.html ''' lookup = { 'M': self.onMove, 'L': self.onLine, 'Z': self.onClose, 'z': self.onClose, } self.loops = [] self.current_path = None self.bounds.reset() for command in commands: action = command[0] if action in lookup: lookup[action](command) else: self.onBadCommand(action) return self.loops