def Initialize(credentials=None, opt_url=None): """Initialize the EE library. If this hasn't been called by the time any object constructor is used, it will be called then. If this is called a second time with a different URL, this doesn't do an un-initialization of e.g.: the previously loaded Algorithms, but will overwrite them and let point at alternate servers. Args: credentials: OAuth2 credentials. opt_url: The base url for the EarthEngine REST API to connect to. """ data.initialize(credentials, (opt_url + '/api' if opt_url else None), opt_url) # Initialize the dynamically loaded functions on the objects that want them. ApiFunction.initialize() Element.initialize() Image.initialize() Feature.initialize() Collection.initialize() ImageCollection.initialize() FeatureCollection.initialize() Filter.initialize() Geometry.initialize() List.initialize() Number.initialize() String.initialize() Date.initialize() Dictionary.initialize() _InitializeGeneratedClasses() _InitializeUnboundMethods()
def __init__(self, **kwargs): Coordinate.__init__(self, **kwargs) #半径 self.radius = kwargs['radius'] #角度 self.angle = kwargs.get('angle', 90.0) #圆心 self.center = (0, 0) x = Geometry.sin(self.angle / 2) * self.radius y = Geometry.cos(self.angle / 2) * self.radius self.source = x, y self.target = -x, y #外切圆心,外切半径 if self.angle < 90: #三点求圆 self.wrap_center = Geometry.circle_center(self.source, self.target, self.center) self.wrap_radius = Geometry.distance(self.wrap_center, self.center) elif self.angle < 180: #两侧点中点 self.wrap_center = (0, y) self.wrap_radius = x else: #所在的圆 self.wrap_center = self.center self.wrap_radius = self.radius
def reset(self): self.geometry = Geometry(self.size) self.geometry.add_padding(self.padding) self.queued_face_rotations = Queue(0) self.tween = Tween() self.state = State.IDLE self.current_face_rotation = None
def wheel(width, height, n, occupancy, separation, material, priority='None'): """Produces a geometry consisting of n rods of specified material with specified cell occupancy in a cell of default area = 1. The distance between the center of the cell and the body of each rod is adjustable using separation. """ distance = lambda point1, point2: \ sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2) r = occupancy_radius(occupancy, n, width * height) if n == 1: return Geometry(width, height, [Rod(0, 0, material, r)]) R = r + separation wheel_point = lambda N: (R * cos(N * 2 * pi / n), R * sin(N * 2 * pi / n)) wheel_priority = { 'None': lambda R, r, n: (R, r, n), 'Occupancy': lambda R, r, n: (distance(wheel_point(0), wheel_point(1)) > 2 * r and (R, r, n) or (r / sin(2 * pi / (2 * n)), r, n)), 'Distance': lambda R, r, n: (distance(wheel_point(0), wheel_point(1)) > 2 * r and (R, r, n) or (R, R * sin(2 * pi / (2 * n)), n)) } R, r, n = wheel_priority[priority](R, r, n) return Geometry(width, height, [ Rod(*wheel_point(N), material=copy(material), radius=r) for N in range(n) ])
def __init__(self, filepath): config_data = json.load(open(filepath)) self.default_object_name = config_data.get("default_object") self.phase_count = config_data.get("phases") self.module_name = config_data.get("module", "student_module") self.callback_name = config_data.get("callback", "compor_cena") self.enable_depth = config_data.get("depth", False) self.geometry = Geometry() obj_filepaths = config_data.get("obj_files", []) for obj_filepath in obj_filepaths: self.geometry.read_obj(obj_filepath) self.fit_objects = config_data.get("fit_objects") self.sequence = config_data.get("sequence", ["UserCallback"]) center = config_data.get("center") if center is not None: self.center = tuple(map(float, center)) bounds = config_data.get("bounds") if bounds is not None: self.bounds_min = (float(min(bounds[0][0], bounds[1][0])), float(min(bounds[0][1], bounds[1][1]))) self.bounds_max = (float(max(bounds[0][0], bounds[1][0])), float(max(bounds[0][1], bounds[1][1])))
def Initialize(credentials="persistent", opt_url=None): """Initialize the EE library. If this hasn't been called by the time any object constructor is used, it will be called then. If this is called a second time with a different URL, this doesn't do an un-initialization of e.g.: the previously loaded Algorithms, but will overwrite them and let point at alternate servers. Args: credentials: OAuth2 credentials. 'persistent' (default) means use credentials already stored in the filesystem, or raise an explanatory exception guiding the user to create those credentials. opt_url: The base url for the EarthEngine REST API to connect to. """ if credentials == "persistent": credentials = _GetPersistentCredentials() data.initialize(credentials, (opt_url + "/api" if opt_url else None), opt_url) # Initialize the dynamically loaded functions on the objects that want them. ApiFunction.initialize() Element.initialize() Image.initialize() Feature.initialize() Collection.initialize() ImageCollection.initialize() FeatureCollection.initialize() Filter.initialize() Geometry.initialize() List.initialize() Number.initialize() String.initialize() Date.initialize() Dictionary.initialize() Terrain.initialize() _InitializeGeneratedClasses() _InitializeUnboundMethods()
def __init__(self, geom=Geometry()): """(Body, Geometry) -> NoneType *Description* """ Geometry.__init__(self, geom.pb) self.geom = geom self.p = self.empty_uv_xyz() self.name = "Empty"
def __init__(self, material): geometry = Geometry() # position and UV data are the same vertexData = [[0,0], [1,0], [1,1], [0,0], [1,1], [0,1]] geometry.setAttribute("vec2", "vertexData", vertexData) geometry.vertexCount = 6 super().__init__(geometry, material)
def process_image_file(): 'Display the set pixels in a single image (for testing)' frame = cv2.imread('media/cpx.png') bright_areas = cv2.inRange(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), REG_COLOR_RANGE[0], REG_COLOR_RANGE[1]) cv2.imwrite('bright.png', bright_areas) geom = Geometry(bright_areas) p = [power for power in range(5) if geom.pel_on(power)] cv2.imshow('', bright_areas) cv2.waitKey(0) print(p)
def is_edge_valid(target_node, node, obstacle): for i in range(len(obstacle.x_list) - 1): p1 = Geometry.Point(target_node.x, target_node.y) p2 = Geometry.Point(node.x, node.y) p3 = Geometry.Point(obstacle.x_list[i], obstacle.y_list[i]) p4 = Geometry.Point(obstacle.x_list[i + 1], obstacle.y_list[i + 1]) if Geometry.is_seg_intersect(p1, p2, p3, p4): return False return True
def __init__(self): Geometry.__init__(self) # A 4xV numpy array of vertex positions. They are homogeneous coordinates # where self.vertex_pos[3, i] is always 1. This facilitates transform # *all* the points by X * v. self.vertex_pos = None # A 3xF numpy array of face normals. This facilitates transforming normals # by taking xform.rotation() * v. self.face_normals = None # A length V list of MeshVertex instances. self.vertices = [] # A length F list of MeshFace instances. self.faces = []
def process_video(): 'Process the input video file and write the result to a new file' video_in = cv2.VideoCapture(INPUT_VIDEO_FILENAME) read_return_code, frame = video_in.read() height, width = frame.shape[:2] video_out = cv2.VideoWriter(OUTPUT_VIDEO_FILENAME, cv2.VideoWriter_fourcc(*'avc1'), DECODED_VID_FPS, (width, height)) # The greatest number found between pixels-off times is likely to be the correct number. greatest_sum_of_on_powers = None message = '' while read_return_code: bright_areas = cv2.inRange(frame, REG_COLOR_RANGE[0], REG_COLOR_RANGE[1]) color_bright_areas = cv2.bitwise_and(frame, frame, mask=bright_areas) geom = Geometry(frame, color_bright_areas) def on_powers() -> Iterable[int]: 'Return those powers of two corresponding to the lit pels' return (power for power in range(5) if geom.pel_on(power)) if geom.registration_pels_found(): sum_of_on_powers = sum(1 << power for power in on_powers()) if LOG and sum_of_on_powers > 0: print(sum_of_on_powers, '', end='') if sum_of_on_powers > 0: if greatest_sum_of_on_powers is None or sum_of_on_powers > greatest_sum_of_on_powers: greatest_sum_of_on_powers = sum_of_on_powers else: if greatest_sum_of_on_powers: if LOG: print(greatest_sum_of_on_powers) letter = ' ' if greatest_sum_of_on_powers == 27 else chr( greatest_sum_of_on_powers + ord('a') - 1) print(letter, end=('\n' if LOG else '')) message += letter greatest_sum_of_on_powers = None cf = centered_frame(frame, geom.center) cv2.putText(cf, message, (30, frame.shape[0] - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (200, 200, 100), 2) video_out.write(cf) if SHOW_FRAMES: cv2.imshow('Bright', color_bright_areas) cv2.imshow('Decoded', cf) cv2.waitKey(0) read_return_code, frame = video_in.read() video_in.release() video_out.release()
def __init__(self, render_area): self.render_area = render_area self.approximation_step = 0 self.radius = 0 self.projection_name = "default" # Координаты источника света self.light_x = 0 self.light_y = 0 self.light_z = -1000 self.geom = Geometry()
def read_input(input_file): ''' Takes an open input_file returns a dict with the processed options read from file and a geometry object ''' local_options = DEFAULT_OPTIONS.copy() geometry = Geometry() for i, line in enumerate(input_file): tokens = _tokenize(line) if tokens[0] == '': continue if len(tokens) != 2: raise ValueError( "In line {}: Wrong format\nGot: {}".format(i, line) ) key, value = tokens[0].upper(), tokens[1].upper() if key in local_options: local_options[key] = value elif key == "BOUNDARY": geometry.add_boundary(value) elif key == "BODY": geometry.add_body_from_file(value) elif key[:4] == "GEO_": geometry.add_geometry(key, value) else: raise ValueError( "In line {}: Invalid option {}".format(i, key) ) return local_options, geometry
def Reset(): """Reset the library. Useful for re-initializing to a different server.""" data.reset() ApiFunction.reset() Image.reset() Feature.reset() Collection.reset() ImageCollection.reset() FeatureCollection.reset() Filter.reset() Geometry.reset() Number.reset() String.reset() _ResetGeneratedClasses() global Algorithms Algorithms = _AlgorithmsContainer()
def __init__(self, universe_material, nbins, diameter=100., detector_width=100., detector='plane'): self.universe_material = universe_material self.geometry = Geometry() self.source = np.array([-diameter / 2., 0.]) if detector == 'plane': self.detector = DetectorPlane([diameter / 2., 0.], detector_width, nbins) elif detector == 'arc': self.detector = DetectorArc(self.source, diameter, detector_width / 2., -detector_width / 2., nbins)
def __init__(self): self.wind_speed = 5.0 # default wind speed self.coherent_pow_flg = True # add coherent power self.coh_integrate_time = 0.001 # coherent integrateed time self.num_angles = 360 # integrated angle resolution self.interface_flg = 1 # curvature surface self.ddm_cov_factor = 5 # cov mode factor for ddm # # atmosphere loss for signal propagation 0.5 dB self.atmospheric_loss = pow(10.0, (0.5 / 10.0)) # # members self.geometry = Geometry() self.nadir_RF = Antenna() self.zenith_RF = Antenna() self.signal = Signal() self.power_waveform = Waveform(True, 1000) self.interface = Interface()
def case_from_input_file(cls, file, cwd=''): ''' return an instance of Case by reading its data from an input file ''' lines = file.readlines() lines = filter_lines(lines) lineno = 0 name = lines[0] mach_no = float(lines[1].split()[0]) symmetry = lines[2].split() symmetry = [int(symmetry[0]), int(symmetry[1]), float(symmetry[2])] ref_area, ref_chord, ref_span = [ float(value) for value in lines[3].split()[:3] ] ref_cg = [float(value) for value in lines[4].split()[:3]] lineno = 5 try: CD_p = float(lines[5].split()[0]) lineno = 6 except ValueError: CD_p = 0.0 geometry = Geometry.create_from_lines(lines, lineno, cwd=cwd) case = Case(name=name, mach_no=mach_no, symmetry=symmetry, ref_area=ref_area, ref_chord=ref_chord, ref_span=ref_span, ref_cg=ref_cg, CD_p=CD_p, geometry=geometry, cwd=cwd) return case
def main(): desc = "Add noise to a radiance spectrum or image" parser = argparse.ArgumentParser(description=desc) parser.add_argument('config', type=str, metavar='INPUT') args = parser.parse_args(sys.argv[1:]) config = json_load_ascii(args.config, shell_replace=True) configdir, configfile = split(abspath(args.config)) infile = expand_path(configdir, config['input_radiance_file']) outfile = expand_path(configdir, config['output_radiance_file']) instrument = Instrument(config['instrument_model']) geom = Geometry() if infile.endswith('txt'): rdn, wl = spectrumLoad(infile) Sy = instrument.Sy(rdn, geom) rdn_noise = rdn + multivariate_normal(zeros(rdn.shape), Sy) with open(outfile, 'w') as fout: for w, r in zip(wl, rdn_noise): fout.write('%8.5f %8.5f' % (w, r)) else: raise ValueError('image cubes not yet implemented')
def __init__(self, geometry: Geometry): """ Constructs the grid based on the geometry :param geometry: """ minx, miny, maxx, maxy = geometry.get_bounding_box() x = np.arange(minx - CELLSIZE, maxx + 2 * CELLSIZE, CELLSIZE) y = np.arange(miny - CELLSIZE, maxy + 2 * CELLSIZE, CELLSIZE) xv, yv = np.meshgrid(x, y, indexing='ij') dimX = len(x) dimY = len(y) self.gridX = xv self.gridY = yv self.dimX = dimX self.dimY = dimY self.cellsize = CELLSIZE self.inside_cells = self.__get_inside_cells(geometry) self.outside_cells = self.__get_outside_cells(geometry) self.door_cells = self.__get_door_cells(geometry) self.entrance_cells = self.__get_entrance_cells(geometry) self.exit_cells = self.__get_exit_cells(geometry)
def basic_test(): test_geom = Geometry(1,1,[Rod(0,0,Dielectric(11.8), \ occupancy_radius(0.3,1))]) sim = Simulation('basic_test', test_geom) sim.run_simulation() sim.post_process() return True
def find_coordinates(city, address, number_of_house, test=False): """Функция ищет координаты по задонному адресу""" coordinates = [] try: if not test: coordinate_path = os.path.join("./test_base", "Russia_coordinates.db") buildings_path = os.path.join("./test_base", "Russia_buildings.db") else: coordinate_path = os.path.join("./test_base", "test_coordinates.db") buildings_path = os.path.join("./test_base", "test_buildings.db") con1 = sqlite3.connect(coordinate_path) cur1 = con1.cursor() con2 = sqlite3.connect(buildings_path) cur2 = con2.cursor() sql = "SELECT Links FROM address_base WHERE City=? AND Address=? AND House_number=?" cur2.execute(sql, [city, address, number_of_house]) links = cur2.fetchone()[0] links = links.split() res = [] for link in links: res.append(int(link)) for i in res: sql2 = "SELECT Lat,Lon FROM coordinates_base WHERE Link=?" cur1.execute(sql2, [i]) c = cur1.fetchall() coordinates.append([c[0][0], c[0][1]]) coordinates = numpy.array(coordinates) return Geometry.find_centroid(coordinates, len(coordinates)) except TypeError: print('Нет такого адреса в базе: {}'.format( str.join(" ", [city, address, number_of_house])))
def test_the_hypotenuse(self): Geometry.square = MagicMock(method='square') Geometry.square.side_effect = [9, 16] result = Geometry.hypotenuse(3, 4) self.assertEqual(result, 5)
def Reset(): """Reset the library. Useful for re-initializing to a different server.""" data.reset() ApiFunction.reset() Element.reset() Image.reset() Feature.reset() Collection.reset() ImageCollection.reset() FeatureCollection.reset() Filter.reset() Geometry.reset() Number.reset() String.reset() _ResetGeneratedClasses() global Algorithms Algorithms = _AlgorithmsContainer()
def main(): global gl global test_model # Initialize the library if not glfwInit(): sys.exit() # Initilize GL gl = pygloo.init() if not gl: sys.exit() # Create a windowed mode window and its OpenGL context window = glfwCreateWindow(640, 480, "Hello World", None, None) if not window: glfwTerminate() sys.exit() # Make the window's context current glfwMakeContextCurrent(window) # Install a input handlers glfwSetKeyCallback(window, on_key) glfwSetMouseButtonCallback(window, on_mouse) glfwSetCursorPosCallback(window, on_mouse_move) glfwSetScrollCallback(window, on_scroll) # Load an obj # test_model = Geometry.from_OBJ(gl, "assets/sphere.obj") # Loop until the user closes the window while not glfwWindowShouldClose(window): # Render width, height = glfwGetFramebufferSize(window) gl.glViewport(0, 0, width, height) gl.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) gl.glClearColor(1.0, 1.0, 1.0, 1.0) # white gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gl.glEnable(GL_DEPTH_TEST) # gl.glDepthFunc(GL_LESS); gl.glDepthFunc(GL_LEQUAL) # Render # render(width, height) # Poll for and process events glfwPollEvents() # Swap front and back buffers glfwSwapBuffers(window) glfwTerminate()
def __init__(self, **kwargs): Coordinate.__init__(self, **kwargs) Motion.__init__(self, **kwargs) #长度 self.length = kwargs['length'] middle = kwargs['middle'] #中间点,middle=0为圆 self.middle = (middle, self.length / 2) #源点 self.source = (0, 0) #目标点 if middle: self.target = (0, self.length) else: self.target = self.source #圆弧的圆心 if middle: self.center = Geometry.circle_center(self.source, self.target, self.middle) else: self.center = self.middle #半径 self.radius = Geometry.distance(self.source, self.center) #角度 center_x, center_y = self.center if middle > 0: self.angle = 360 - 2 * Geometry.acos(center_x / self.radius) elif middle < 0: self.angle = 2 * Geometry.acos(center_x / self.radius) else: self.angle = 360 #距离 self.distance = Geometry.radian(self.angle) * self.radius #上一个点 self.last_step = self.source
def makeBody(self, Nlines=21, Npoints=5): x = np.zeros([Nlines, 5]) y = np.zeros([Nlines, 5]) z = np.zeros([Nlines, 5]) for il in np.arange(Nlines): theta = 2 * math.pi * float(il) / float(Nlines - 1) x[il, 0] = 0 y[il, 0] = 0 z[il, 0] = 0 x[il, 1] = self.cone_L y[il, 1] = -self.cylinder_R * math.sin(theta) z[il, 1] = self.cylinder_R * math.cos(theta) x[il, 2] = self.cone_L + self.cylinder_L y[il, 2] = -self.cylinder_R * math.sin(theta) z[il, 2] = self.cylinder_R * math.cos(theta) x[il, 3] = self.cone_L + self.cylinder_L + self.boattail_L y[il, 3] = -self.boattail_R * math.sin(theta) z[il, 3] = self.boattail_R * math.cos(theta) # x[il, 4] = self.cone_L + self.cylinder_L + self.boattail_L # y[il, 4] = 0 # z[il, 4] = 0 def _interpBody(x): NpC = Npoints NpB = int(np.ceil(Npoints / 2)) NpF = int(np.ceil(Npoints / 2.5)) xout = np.zeros([Nlines, NpC + NpF + NpB]) for il in np.arange(Nlines): for ip in np.arange(NpC): xout[il, 0 + ip] = (x[il, 0] + (x[il, 1] - x[il, 0]) * (ip / NpC)) for ip in np.arange(NpF): xout[il, NpC + ip] = (x[il, 1] + (x[il, 2] - x[il, 1]) * (ip / NpF)) for ip in np.arange(NpB): xout[il, NpC + NpF + ip] = (x[il, 2] + (x[il, 3] - x[il, 2]) * (ip / (NpB - 1))) # xout[il, -1] = x[il, 4] return xout xmat = _interpBody(x) ymat = _interpBody(y) zmat = _interpBody(z) return Geometry(matricesToStrips(xmat, ymat, zmat), tangent_method='cone', ref_area=np.pi * self.cylinder_R**2)
def wrap_collide(self, shape): for c1 in self.compose: for c2 in shape.compose: #先根据扇形和矩形自身的坐标调整 r1 = self.adjust(c1.adjust(c1.wrap_center)) #用缓存避免重复计算 r2 = shape.adjust(c2.adjust(c2.wrap_center)) distance = Geometry.distance(r1, r2) if distance < c1.wrap_radius + c2.wrap_radius: return True return False
def __init__(self): tracks.logger.info(""" opencv version: """ + cv2.__version__) tracks.logger.info("capturing camera port " + str(tracks.config["camera"])) self._detection_status = False firstFrame = None camera = cv2.VideoCapture(tracks.config['camera']) low = np.array( tracks.config['detection']['from_color']) # [h,v,s] color format heigh = np.array(tracks.config['detection']['to_color']) blur_radius = tracks.config['detection']['blur_radius'] self.geometry = Geometry() self.comm = TableManager(self.set_detection_status) while True: (grabbed, frame) = camera.read() if not grabbed: break # blure image blur = cv2.blur(frame, (blur_radius, blur_radius)) # convert to hsv hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV) # mask by low / heigh hsv values mask = cv2.inRange(hsv, low, heigh) dialateElm = cv2.getStructuringElement(cv2.MORPH_RECT, (24, 24)) erodeElm = cv2.getStructuringElement(cv2.MORPH_RECT, (12, 12)) mask = cv2.erode(mask, erodeElm, iterations=2) mask = cv2.dilate(mask, dialateElm, iterations=2) final = mask self.debug('frame', final) if self._detection_status == False: continue cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] if (len(cnts) > 1): self.find_and_report_target(cnts, mask)
def __init__(self): super(DREA, self).__init__() self.command = ['drea'] self.add('geo_in', Geometry()) self.add('geo_out', Geometry()) self.add('flow_in', MEflows()) self.add('flow_out', MEflows()) self.ist = None self.ifab = None self.external_files = [ FileMetadata(path='control.in', input=True), FileMetadata(path='flocond.in', input=True), FileMetadata(path='expnd.in', input=True), FileMetadata(path='zrdmix.in', input=True), FileMetadata(path='hwall.in', input=True), FileMetadata(path='ejectd.out'), FileMetadata(path=self.stderr), ]
def _build_geometry(self, points, cells): geometry = Geometry() for cell in cells: cell_type, cell = cell[0], cell[1:] if cell_type == CellType.VTK_TRIANGLE: poly, name = self._build_triangle(cell, points) if cell_type == CellType.VTK_QUAD: poly, name = self._build_quadrilateral(cell, points) if cell_type == CellType.VTK_PIXEL: poly, name = self._build_pixel(cell, points) if cell_type == CellType.VTK_TETRA: poly, name = self._build_tetrahedron(cell, points) elif cell_type == CellType.VTK_VOXEL: poly, name = self._build_voxel(cell, points) geometry.add_named_polyhedron(poly, name, self.current_id) self.current_id += 1 return geometry
def step(self, pos, step): angle = Geometry.angle(step / self.radius) middle = self.middle[0] if str(middle)[0] != '-': #逆时针 angle = 360 - angle x, y = Geometry.rotate(pos, self.center, angle) last = self.last_step[0] #上一个位置x的值,用来判断圆形的时候是否超出范围 self.last_step = x, y #每次移动不超过半圈 if middle * x < 0: return self.target elif middle == 0: if str(middle)[0] != '-': if last < 0 and x > 0: return self.target else: if last > 0 and x < 0: return self.target return x, y
def select_area(epsg_code: str, areas_json: [dict], point_json: dict) -> dict: epsg_code = 'epsg:' + epsg_code areas = [ Area(json['name'], Geometry.from_geojson(json['geometry'], epsg_code)) for json in areas_json ] point = Geometry.from_geojson(point_json, epsg_code) selected_area = Model(areas).select_area(point) selected_area.boundary_distance(point) if selected_area is None: return None return { 'selected_area': selected_area.representation(), 'boundary_distance': selected_area.boundary_distance(point) }
def _calculate_geometry(self): slot_centers = [bc.center() for bc in self._barcodes] # Use empty slots as points if not enough barcodes if self.plate_type == Geometry.UNIPUCK: use_emptys = len(self._barcodes) < 8 if use_emptys: empty_circles = EmptySlotDetector.detect(self._frame_img, self._barcodes) empty_centers = [c.center() for c in empty_circles] slot_centers.extend(empty_centers) geometry = Geometry.calculate_geometry(self.plate_type, slot_centers) return geometry
def __get_inside_cells(self, geometry: Geometry): """ :param geometry: Geometry to check :return: matrix with 1 for cells inside the geometry, 0 otherwise """ inside = np.zeros_like(self.gridX) for i in range(self.dimX): for j in range(self.dimY): x, y = self.get_coordinates(i, j) if geometry.is_in_geometry(x, y): inside[i][j] = 1 inside = inside + self.__get_entrance_cells(geometry) return inside
def run_perspect(mesh, qi, p_D, m_D, rho): # Define boundaries class Endo(df.SubDomain): def inside(self, x, on_boundary): return on_boundary and df.near(x[0], 0) markers = {'ENDO': (30, 1)} ffun = df.MeshFunction("size_t", mesh, mesh.topology().dim() - 1) ffun.set_all(0) endo = Endo() endo.mark(ffun, markers['ENDO'][0]) markerfunctions = MarkerFunctions(ffun=ffun) # define fiber structure VFS = df.VectorFunctionSpace(mesh, 'P', 1) f0 = df.interpolate(df.Constant((1.0, 0.0, 0.0)), VFS) s0 = df.interpolate(df.Constant((0.0, 1.0, 0.0)), VFS) n0 = df.interpolate(df.Constant((0.0, 0.0, 1.0)), VFS) microstructure = Microstructure(f0=f0, s0=s0, n0=n0) # create geometry geometry = Geometry(mesh, markers=markers, microstructure=microstructure, markerfunctions=markerfunctions) # Setup simulation parameters = { 'mechanics': False, 'K': [1], 'qi': qi, 'qo': 0, 'dt': 1.0, 'theta': 1, 'steps': 1, 'rho': rho } solver_parameters = {'linear_solver': 'cg', 'preconditioner': 'sor'} pspect = perspect.Perspect(geometry, parameters=parameters, solver_parameters=solver_parameters) bcs = [ df.DirichletBC(pspect.pprob.state.function_space(), m_D, "on_boundary") ] pspect.pprob.prescribed_pressure(p_D) pspect.solve_porous(bcs) m = pspect.pprob.state return m
def __init__(self, **kwargs): Coordinate.__init__(self, **kwargs) #宽度 self.width = kwargs['width'] #高度 self.height = kwargs['height'] #包络圆心 self.wrap_center = (0, self.height / 2) #包络半径 self.wrap_radius = Geometry.distance(self.wrap_center, (self.width / 2, 0))
def _calculate_geometry(self): slot_centers = [bc.center() for bc in self._barcodes] # Use empty slots as points if not enough barcodes if self.plate_type == Geometry.UNIPUCK: use_emptys = len(self._barcodes) < 8 if use_emptys: empty_circles = EmptySlotDetector.detect( self._frame_img, self._barcodes) empty_centers = [c.center() for c in empty_circles] slot_centers.extend(empty_centers) geometry = Geometry.calculate_geometry(self.plate_type, slot_centers) return geometry
def shp2geo(sf): geometry = Geometry() index_admin = sf.get_field("ADMIN") index_iso2 = sf.get_field("ISO_A2") p = 0 for s, shaperecord in enumerate(sf.records()): shaperecord = sf.shapeRecord(s) admin = shaperecord.record[index_admin] iso2 = shaperecord.record[index_iso2] parts = shaperecord.shape.parts part_shapes = [] for i, point in enumerate(shaperecord.shape.points): if i in parts: part_shapes.append([]) part_shapes[-1].append(point) p += len(part_shapes) for part_shape in part_shapes: point_numbers = [] for point in part_shape[:-1]: # because it's closed point_number = geometry.add_point(trunc(point[0]), trunc(point[1]), 0.0) point_numbers.append(point_number) prim_number = geometry.add_prim(point_numbers) geometry.set_prim_attr_string('iso2', prim_number, iso2) geometry.set_prim_attr_int('prim', prim_number, prim_number) log.warning(repr((s, p))) d = defaultdict(int) for p, point in enumerate(geometry.points): d[point] += 1 for p, point in enumerate(geometry.points): geometry.set_point_attr_int('freq', p, d[point]) return geometry
def turn(self, rotate): angle = Geometry.standard(rotate - self.toward) if not angle: return direct = self.velocity if angle > 0 else -self.velocity #顺时针或逆时针的步长 self.residual += abs(angle) #需要旋转的总长度 start = self.toward while self.residual >= self.velocity: #还能再旋转一个时间片 end = start + direct if (end - rotate) * direct > 0: end = rotate yield {'type': 'rotate', 'start': start, 'end': end} self.residual -= self.velocity start = end self.toward = rotate
def move(self): for route in self.compose: for frame in route.move(): frame = [self.adjust(route.adjust(pos)) for pos in frame] #根据地图偏移进行调整 start = frame[0] #起点 end = frame[-1] #终点 frame = frame[1:] #包含的帧 rotate = Geometry.atan((end[0] - start[0]) / (end[1] - start[1])) #方向,可能跳过 if self.velocity: #角速度为0不旋转 for rotate_frame in self.turn(rotate): yield rotate_frame yield {'type': 'move', 'start': start, 'end': end, 'frame': frame}
def from_string(string): """ Creates a scan record object from a semi-colon separated string. This is used when reading a stored record back from file. """ items = string.strip().split(Record.ITEM_SEPARATOR) id = items[Record.IND_ID] timestamp = float(items[Record.IND_TIMESTAMP]) image = items[Record.IND_IMAGE] plate_type = items[Record.IND_PLATE] barcodes = items[Record.IND_BARCODES].split(Record.BC_SEPARATOR) geo_class = Geometry.get_class(plate_type) geometry = geo_class.deserialize(items[Record.IND_GEOMETRY]) return Record(plate_type=plate_type, barcodes=barcodes, timestamp=timestamp, image_path=image, id=id, geometry=geometry)
def recalculate(self): # Настройка шагов аппроксимации circle_count = self.approximation_step circle_points_count = self.approximation_step + 2 # Считаем окружность self.geom.clear() angle_step = 2*math.pi/circle_points_count for circle_number in range(0, circle_count): radius_for_point_1 = self.radius * math.sqrt(1 - math.pow((circle_count - (circle_number+1))/circle_count, 2)) z_axis_for_point_1 = self.radius * (circle_count-(circle_number+1))/circle_count radius_for_point_2 = self.radius * math.sqrt(1 - math.pow((circle_count - circle_number)/circle_count, 2)) z_axis_for_point_2 = self.radius * (circle_count - circle_number) / circle_count angle = 0 while angle < 2*math.pi: self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle, z_axis_for_point_1)) self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle+angle_step, z_axis_for_point_1)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle, z_axis_for_point_2)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle+angle_step, z_axis_for_point_2)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) angle += angle_step angle = 2*math.pi while angle > 0: self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle, -z_axis_for_point_1)) self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle-angle_step, -z_axis_for_point_1)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle, -z_axis_for_point_2)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle-angle_step, -z_axis_for_point_2)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) angle -= angle_step for index in range(0, len(self.geom.points), 4): self.geom.faces.append((index, index+1, index+3, index+2)) self.geom.apply_projection(self.projection_name)
def shp2geo(sf): geometry = Geometry() index_admin = sf.get_field("ADMIN") index_iso2 = sf.get_field("ISO_A2") p = 0 for s, shaperecord in enumerate(sf.records()): shaperecord = sf.shapeRecord(s) admin = shaperecord.record[index_admin] iso2 = shaperecord.record[index_iso2] parts = shaperecord.shape.parts part_shapes = [] for i, point in enumerate(shaperecord.shape.points): if i in parts: part_shapes.append([]) part_shapes[-1].append(point) p += len(part_shapes) for part_shape in part_shapes: point_numbers = [] for point in part_shape[:-1]: # because it's closed point_number = geometry.add_point(trunc(point[0]), trunc(point[1]), 0.0) point_numbers.append(point_number) prim_number = geometry.add_prim(point_numbers) geometry.set_prim_attr_string("iso2", prim_number, iso2) geometry.set_prim_attr_int("prim", prim_number, prim_number) log.warning(repr((s, p))) d = defaultdict(int) for p, point in enumerate(geometry.points): d[point] += 1 for p, point in enumerate(geometry.points): geometry.set_point_attr_int("freq", p, d[point]) return geometry
def is_face_visible(self, face): """ Определение видимости грани на основе алгоритма Робертса :param face: грань :return: True, если видимо, иначе False """ p1_index = face[0] x0 = self.geom.points[p1_index][0] y0 = self.geom.points[p1_index][1] z0 = self.geom.points[p1_index][2] p2_index = face[1] x1 = self.geom.points[p2_index][0] y1 = self.geom.points[p2_index][1] z1 = self.geom.points[p2_index][2] p3_index = face[2] x2 = self.geom.points[p3_index][0] y2 = self.geom.points[p3_index][1] z2 = self.geom.points[p3_index][2] a = y0*(z1 - z2) + y1*(z2 - z0) + y2*(z0 - z1) b = z0*(x1 - x2) + z1*(x2 - x0) + z2*(x0 - x1) c = x0*(y1 - y2) + x1*(y2 - y0) + x2*(y0 - y1) d = -(x0*(y1*z2 - y2*z1) + x1*(y2*z0 - y0*z2) + x2*(y0*z1 - y1*z0)) """ Знак result = Ax + By + Cz + D определяет, с какой стороны по отношению к плоскости находится точка s(x,y,z,w). Если result > 0, то точка внутри тела Если result < 0 - на противаположной стороне, а в случае result = 0 точка принадлежит плоскости. """ s = np.array([[1, 1, -1000, 1]]) p = np.array([[a], [b], [c], [d]]) result = Geometry.multiplication_matrix(s, p) return True if result[0][0] < 0 else False
def case_from_input_file(cls, file): ''' return an instance of Case by reading its data from an input file ''' lines = file.readlines() lines = filter_lines(lines) lineno = 0 casename = lines[0] mach_no = float(lines[1]) symmetry = lines[2].split() symmetry = [int(symmetry[0]), int(symmetry[1]), float(symmetry[2])] ref_area, ref_chord, ref_span = [float(value) for value in lines[3].split()] ref_cg = [float(value) for value in lines[4].split()] lineno = 5 try: CD_p = float(lines[5]) lineno = 6 except ValueError: CD_p = None geometry = Geometry.create_from_lines(lines, lineno) case = Case(casename, mach_no, symmetry, ref_area, ref_chord, ref_span, ref_cg, CD_p, geometry) return case
def missinggeo(csv_path): log.info(csv_path) with codecs.open(csv_path, "r", "utf-8") as csv_file: geometry = Geometry() p = 0 for line in csv_file.read().splitlines(): line = re.sub("#.*$", "", line) line = line.strip() if not line: continue parts = [part.strip() for part in line.split(DELIMITER)] (iso2, name) = parts[:2] (latitude, longitude) = [float(value) for value in parts[2:]] geometry.add_point(longitude, latitude, 0) geometry.set_point_attr_string("iso2", p, iso2) geometry.set_point_attr_string("name", p, name) p += 1 sys.stdout.write(geometry.render().encode("utf-8"))
def shp2geo(sf, iso32, border_switch, border_deny): geometry = Geometry() index_iso3_left = sf.get_field("adm0_a3_l") index_iso3_right = sf.get_field("adm0_a3_r") index_type = sf.get_field("type") p = 0 for s, shaperecord in enumerate(sf.records()): shaperecord = sf.shapeRecord(s) iso3_left = shaperecord.record[index_iso3_left] iso3_right = shaperecord.record[index_iso3_right] type_ = shaperecord.record[index_type] try: iso2_left = iso32[iso3_left] iso2_right = iso32[iso3_right] except KeyError as e: log.warning(repr((iso3_left, iso3_right, str(e)))) raise e border_key = tuple(sorted([iso2_left, iso2_right])) if border_key in border_switch: log.warning(repr(border_switch)) log.warning("switch %s -> %s" % (repr(border_key), repr(border_switch[border_key]))) iso2_left, iso2_right = border_switch[border_key] border_key = tuple(sorted([iso2_left, iso2_right])) log.info(shaperecord.shape.parts) if border_key in border_deny: log.warning("inhibit %s" % repr(border_key)) continue if iso2_left == iso2_right: continue if hasattr(shaperecord.shape, "parts"): parts = shaperecord.shape.parts else: log.warning(s) parts = [] part_shapes = [] for i, point in enumerate(shaperecord.shape.points): if i in parts: part_shapes.append([]) part_shapes[-1].append(point) p += len(part_shapes) for part_shape in part_shapes: point_numbers = [] for point in part_shape[:]: # because it's open point_number = geometry.add_point(trunc(point[0]), trunc(point[1]), 0.0) point_numbers.append(point_number) prim_number = geometry.add_prim(point_numbers, closed=False) geometry.set_prim_attr_string('iso2_left', prim_number, iso2_left) geometry.set_prim_attr_string('iso2_right', prim_number, iso2_right) geometry.set_prim_attr_string('type', prim_number, type_) geometry.set_prim_attr_int('prim', prim_number, prim_number) d = defaultdict(int) for p, point in enumerate(geometry.points): d[point] += 1 for p, point in enumerate(geometry.points): geometry.set_point_attr_int('freq', p, d[point]) return geometry
class Sphere: """ Класс для общего описания сферы """ def __init__(self, render_area): self.render_area = render_area self.approximation_step = 0 self.radius = 0 self.projection_name = "default" # Координаты источника света self.light_x = 0 self.light_y = 0 self.light_z = -1000 self.geom = Geometry() def recalculate(self): # Настройка шагов аппроксимации circle_count = self.approximation_step circle_points_count = self.approximation_step + 2 # Считаем окружность self.geom.clear() angle_step = 2*math.pi/circle_points_count for circle_number in range(0, circle_count): radius_for_point_1 = self.radius * math.sqrt(1 - math.pow((circle_count - (circle_number+1))/circle_count, 2)) z_axis_for_point_1 = self.radius * (circle_count-(circle_number+1))/circle_count radius_for_point_2 = self.radius * math.sqrt(1 - math.pow((circle_count - circle_number)/circle_count, 2)) z_axis_for_point_2 = self.radius * (circle_count - circle_number) / circle_count angle = 0 while angle < 2*math.pi: self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle, z_axis_for_point_1)) self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle+angle_step, z_axis_for_point_1)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle, z_axis_for_point_2)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle+angle_step, z_axis_for_point_2)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) angle += angle_step angle = 2*math.pi while angle > 0: self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle, -z_axis_for_point_1)) self.geom.points.append(Geometry.from_polar(radius_for_point_1, angle-angle_step, -z_axis_for_point_1)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle, -z_axis_for_point_2)) self.geom.points.append(Geometry.from_polar(radius_for_point_2, angle-angle_step, -z_axis_for_point_2)) self.geom.edges.append((len(self.geom.points)-2, len(self.geom.points)-1)) angle -= angle_step for index in range(0, len(self.geom.points), 4): self.geom.faces.append((index, index+1, index+3, index+2)) self.geom.apply_projection(self.projection_name) def is_face_visible(self, face): """ Определение видимости грани на основе алгоритма Робертса :param face: грань :return: True, если видимо, иначе False """ p1_index = face[0] x0 = self.geom.points[p1_index][0] y0 = self.geom.points[p1_index][1] z0 = self.geom.points[p1_index][2] p2_index = face[1] x1 = self.geom.points[p2_index][0] y1 = self.geom.points[p2_index][1] z1 = self.geom.points[p2_index][2] p3_index = face[2] x2 = self.geom.points[p3_index][0] y2 = self.geom.points[p3_index][1] z2 = self.geom.points[p3_index][2] a = y0*(z1 - z2) + y1*(z2 - z0) + y2*(z0 - z1) b = z0*(x1 - x2) + z1*(x2 - x0) + z2*(x0 - x1) c = x0*(y1 - y2) + x1*(y2 - y0) + x2*(y0 - y1) d = -(x0*(y1*z2 - y2*z1) + x1*(y2*z0 - y0*z2) + x2*(y0*z1 - y1*z0)) """ Знак result = Ax + By + Cz + D определяет, с какой стороны по отношению к плоскости находится точка s(x,y,z,w). Если result > 0, то точка внутри тела Если result < 0 - на противаположной стороне, а в случае result = 0 точка принадлежит плоскости. """ s = np.array([[1, 1, -1000, 1]]) p = np.array([[a], [b], [c], [d]]) result = Geometry.multiplication_matrix(s, p) return True if result[0][0] < 0 else False def get_face_light(self, face, color): """ Закраска грани с учётом освещения на основе вычисления угла между нормалью грани и вектором освещения :param face: грань :param color: цвет грани :return: цвет """ p1_index = face[0] x0 = self.geom.clear_points[p1_index][0] y0 = self.geom.clear_points[p1_index][1] z0 = self.geom.clear_points[p1_index][2] p2_index = face[1] x1 = self.geom.clear_points[p2_index][0] y1 = self.geom.clear_points[p2_index][1] z1 = self.geom.clear_points[p2_index][2] p3_index = face[2] x2 = self.geom.clear_points[p3_index][0] y2 = self.geom.clear_points[p3_index][1] z2 = self.geom.clear_points[p3_index][2] # Вычисляем два вектора, принадлежащих грани a_x = x1 - x0 a_y = y1 - y0 a_z = z1 - z0 b_x = x2 - x1 b_y = y2 - y1 b_z = z2 - z1 # Считаем нормаль к грани по найденным векторам normal_x = a_y * b_z - a_z * b_y normal_y = a_x * b_z - a_z * b_x normal_z = a_x * b_y - a_y * b_x # Длина нормали normal_length = math.sqrt(math.pow(normal_x, 2) + math.pow(normal_y, 2) + math.pow(normal_z, 2)) # Зная координаты источника света, можно вычислить длину вектора от источника света до точки рассмотрения: light_length = math.sqrt(math.pow(self.light_x, 2) + math.pow(self.light_y, 2) + math.pow(self.light_z, 2)) normal_length = normal_length if normal_length != 0 else 0.0001 light_length = light_length if light_length != 0 else 0.0001 # Косинус угла между данными векторами находим следующим образом: result = (normal_x * self.light_x + normal_y * self.light_y + normal_z * self.light_z)/(normal_length * light_length) # Находим интенсивность return QColor(int(color.red() * (0.5 + 0.5 * result)), int(color.green() * (0.5 + 0.5 * result)), int(color.blue() * (0.5 + 0.5 * result))) def set_approximation_step(self, step): self.approximation_step = step self.render_area.update() def set_radius(self, radius): self.radius = radius * 6 self.render_area.update() def set_x_rotate_angle(self, angle): self.geom.x_rotate_angle = angle self.render_area.update() def set_y_rotate_angle(self, angle): self.geom.y_rotate_angle = angle self.render_area.update() def set_z_rotate_angle(self, angle): self.geom.z_rotate_angle = angle self.render_area.update() def set_x_move(self, value): self.geom.x_move = value self.render_area.update() def set_y_move(self, value): self.geom.y_move = value self.render_area.update() def set_z_move(self, value): self.geom.z_move = value self.render_area.update() def set_x_scale(self, value): self.geom.x_scale = value self.render_area.update() def set_y_scale(self, value): self.geom.y_scale = value self.render_area.update() def set_z_scale(self, value): self.geom.z_scale = value self.render_area.update() def set_axonometric_angle_fi(self, value): self.geom.axonometric_angle_fi = value self.render_area.update() def set_axonometric_angle_psi(self, value): self.geom.axonometric_angle_psi = value self.render_area.update() def set_oblique_angle_alpha(self, value): self.geom.oblique_angle_alpha = value self.render_area.update() def set_oblique_L(self, value): self.geom.oblique_L = value self.render_area.update() def set_perspective_angle_fi(self, value): self.geom.perspective_angle_fi = value self.render_area.update() def set_perspective_angle_teta(self, value): self.geom.perspective_angle_teta = value self.render_area.update() def set_perspective_ro(self, value): self.geom.perspective_ro = value self.render_area.update() def set_perspective_d(self, value): self.geom.perspective_d = value self.render_area.update() def set_light_x(self, x): self.light_x = x*10 self.render_area.update() def set_light_y(self, y): self.light_y = -y*10 self.render_area.update() def set_light_z(self, z): self.light_z = -z*10 self.render_area.update()
start_time = time.time() #centerbody= STL('nozzle/Centerbody.stl') centerbody= STL('NozzleSurfacesBin/Centerbody_Bin.stl') print "STL Load Time: ", time.time()-start_time start_time = time.time() n_c = 3 body = Body(centerbody,controls=n_c) #just makes n_C evenly spaced points #body = Body(centerbody,C,name="centerbody") #uses given tuples of points body0 = body.copy() geom = Geometry() #geom.add(body0,name="cb0") geom.add(body,name="centerbody") #params = geom.get_params() #params['centerbody'] = [(0,0),] print "Bspline Compute Time: ", time.time()-start_time start_time = time.time() deltaC_x = np.zeros((n_c,)) deltaC_r = np.zeros((n_c,)) deltaC_r[-1] = 10 #second to last element, set to 10 deltaC = np.array(zip(deltaC_x,deltaC_r)) geom.deform(centerbody=deltaC)
maxThreads = 1024*1024*2 if nParticles <= maxThreads: grid = ( (nParticles - 1)//block[0] + 1, 1, 1 ) else: grid = ( (maxThreads - 1)//block[0] + 1, 1, 1 ) maxTimeIndx = block[0]*4 #Number of points for avrRadius sampling deltaTime_radius = float( maxTime )/maxTimeIndx deltaTime_anim = 3 def configAnimation(): global collisionsPerRun, deltaTime_radius, deltaTime_anim collisionsPerRun = 20 deltaTime_anim = 3 ########################################################################### ########################################################################### #Initialize the frontier geometry radius = 0.3 geometry = Geometry() #geometry.addCircle( (-0.5, 0.5), 0.25 ) #geometry.addCircle( ( 0.5, 0.5), 0.25 ) #geometry.addCircle( ( 0.5, -0.5), 0.25 ) #geometry.addCircle( (-0.5, -0.5), 0.25 ) geometry.addCircle( ( 0., 0.), radius ) geometry.addLine( (-0.5, 0), (-1, 0), type=1 ) #type: 1->Periodic, 0->Real geometry.addLine( ( 0, 0.5), ( 0, 1), type=1 ) geometry.addLine( ( 0.5, 0), ( 1, 0), type=1 ) geometry.addLine( ( 0, -0.5), ( 0,-1), type=1 ) nCircles, circlesCaract_h, nLines, linesCaract_h = geometry.prepareCUDA( cudaP=cudaP ) if usingAnimation: pAnim.nPoints = nParticles pAnim.viewXmin, pAnim.viewXmax = -2500., 2500. pAnim.viewYmin, pAnim.viewYmax = -2500., 2500.
def test_square_with_negative(self): result = Geometry.square(-3) self.assertEqual(result, 9)
def test_square_with_positive(self): result = Geometry.square(3) self.assertEqual(result, 9)
def main(): global gl global test_model # Initialize the library if not glfwInit(): sys.exit() # Initilize GL gl = pygloo.init() if not gl: sys.exit() # Create a windowed mode window and its OpenGL context window = glfwCreateWindow(640, 480, "Hello World", None, None) if not window: glfwTerminate() sys.exit() # Make the window's context current glfwMakeContextCurrent(window) # Install a input handlers glfwSetKeyCallback(window, on_key) glfwSetMouseButtonCallback(window, on_mouse) glfwSetCursorPosCallback(window, on_mouse_move) glfwSetScrollCallback(window, on_scroll) # Load an obj # test_model = Geometry.from_OBJ(gl, "assets/sphere.obj") # Loop until the user closes the window while not glfwWindowShouldClose(window): # Render width, height = glfwGetFramebufferSize(window) gl.glViewport(0, 0, width, height) gl.glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); gl.glClearColor(1.0, 1.0, 1.0, 1.0) # white gl.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gl.glEnable(GL_DEPTH_TEST); # gl.glDepthFunc(GL_LESS); gl.glDepthFunc(GL_LEQUAL); # Render # render(width, height) # Poll for and process events glfwPollEvents() # Swap front and back buffers glfwSwapBuffers(window) glfwTerminate()
def __init__(self): Geometry.__init__(self)
def TriHolesSlab3D( material, radius, thickness, numbands=8, k_interpolation=11, resolution=32, mesh_size=7, supercell_z=6, runmode='sim', num_processors=2, save_field_patterns=True, convert_field_patterns=True, containing_folder='./', job_name_suffix='', bands_title_appendix='', custom_k_space=None, modes=('zeven', 'zodd'), substrate_material=None): """Create a 3D MPB Simulation of a slab with a triangular lattice of holes. :param material: can be a string (e.g. SiN, 4H-SiC-anisotropic_c_in_z; defined in data.py) or just the epsilon value (float) :param radius: the radius of holes in units of the lattice constant :param thickness: slab thickness in units of the lattice constant :param numbands: number of bands to calculate :param k_interpolation: number of the k-vectors between every two of the used high symmetry points Gamma, M, K and Gamma again, so the total number of simulated k-vectors will be 3*k_interpolation + 4 :param resolution: described in MPB documentation :param mesh_size: described in MPB documentation :param supercell_z: the height of the supercell in units of the lattice constant :param runmode: can be one of the following: '' : just create and return the simulation object 'ctl' : create the sim object and save the ctl file 'sim' (default): run the simulation and do all postprocessing 'postpc' : do all postprocessing; simulation should have run before! 'display': display all pngs done during postprocessing. This is the only mode that is interactive. :param num_processors: number of processors used during simulation :param save_field_patterns: indicates whether field pattern h5 files are generated during the simulation (at points of high symmetry) :param convert_field_patterns: indicates whether field pattern h5 files should be converted to png (only when postprocessing) :param containing_folder: the path to the folder which will contain the simulation subfolder. :param job_name_suffix: Optionally specify a job_name_suffix (appendix to the folder name etc.) which will be appended to the jobname created automatically from the most important parameters. :param bands_title_appendix: will be added to the title of the bands diagram. :param custom_k_space: By default, KSpaceTriangular with k_interpolation interpolation steps are used. Provide any KSpace object here to customize this. k_interpolation will then be ignored. :param modes: a list of modes to run. Possible are 'zeven', 'zodd' or '' (latter meaning no distinction). Default: ['zeven', 'zodd'] :param substrate_material: the material of an optional substrate, see param material. Holes will not be extended into the substrate. Default: None, i.e. the substrate is air. :return: the Simulation object """ mat = Dielectric(material) geom = Geometry( width=1, height=1, depth=supercell_z, triangular=True, objects=[ Block( x=0, y=0, z=0, material=mat, #make it bigger than computational cell, just in case: size=(2, 2, thickness)), Rod( x=0, y=0, material='air', radius=radius)]) if substrate_material: geom.add_substrate( Dielectric(substrate_material), start_at=-0.5 * thickness) if isinstance(custom_k_space, KSpace): kspace = custom_k_space else: kspace = KSpaceTriangular( k_interpolation=k_interpolation, use_uniform_interpolation=defaults.newmpb) # points of interest: (output mode patterns at these points) if save_field_patterns: poi = kspace.points()[0:-1] else: poi = [] runcode = '' for mode in modes: if mode == '': runcode += ( '(run %s)\n' % ( defaults.default_band_func( poi, ' '.join(defaults.output_funcs_other)) ) + '(print-dos 0 1.2 121)\n\n') else: if mode == 'zeven': outputfunc = ' '.join(defaults.output_funcs_te) else: outputfunc = ' '.join(defaults.output_funcs_tm) runcode += ( '(run-%s %s)\n' % ( mode, defaults.default_band_func(poi, outputfunc) ) + '(print-dos 0 1.2 121)\n\n') jobname = 'TriHolesSlab_{0}_r{1:03.0f}_t{2:03.0f}'.format( mat.name, radius * 1000, thickness * 1000) sim = Simulation( jobname=jobname + job_name_suffix, geometry=geom, kspace=kspace, numbands=numbands, resolution=resolution, mesh_size=mesh_size, initcode=defaults.default_initcode, postcode='', runcode=runcode, work_in_subfolder=path.join( containing_folder, jobname + job_name_suffix), clear_subfolder=runmode.startswith('s') or runmode.startswith('c')) draw_bands_title = ('Hex. PhC slab; ' '{0}, thickness={1:0.3f}, radius={2:0.3f}'.format( mat.name, geom.objects[0].size[2], geom.objects[1].radius) + bands_title_appendix) return do_runmode( sim, runmode, num_processors, draw_bands_title, plot_crop_y=0.8 / geom.substrate_index, convert_field_patterns=convert_field_patterns, field_pattern_plot_filetype=defaults.field_dist_filetype, field_pattern_plot_k_selection=None, x_axis_hint=[defaults.default_x_axis_hint, kspace][kspace.has_labels()] )
optParser= OptionParser() [ optParser.add_option(opt) for opt in [ make_option('-s', '--shapes', default= None, help= 'json file containing the shapes') ]] opts, args= optParser.parse_args() # if shape file was not pased in, display error and usage if opts.shapes == None: print >> stderr, "--shape=<filename> argument required" optParser.print_help() exit(-1) return args, opts if __name__ == '__main__': # parse cmd line args (args, opts)= parse_args(argv) # load the json file properties= load(open(opts.shapes, 'r')) # process our geometry plane geometry= Geometry(**properties.get('geometry')) for relation in geometry.relations(): print relation