def __init__(self, geom, opt_properties=None): """Creates a feature a geometry or computed object. Features can be constructed from one of the following arguments plus an optional dictionary of properties: 1) An ee.Geometry. 2) A GeoJSON Geometry. 3) A GeoJSON Feature. 4) A computed object - reinterpreted as a geometry if properties are specified, and as a feature if they aren't. Args: geom: A geometry or feature. opt_properties: A dictionary of metadata properties. If the first parameter is a Feature (instead of a geometry), this is unused. Raises: EEException: if the given geometry isn't valid. """ if isinstance(geom, Feature): if opt_properties is not None: raise ee_exception.EEException( 'Can\'t create Feature out of a Feature and properties.') # A pre-constructed Feature. Copy. super(Feature, self).__init__(geom.func, geom.args) return self.initialize() feature_constructor = apifunction.ApiFunction.lookup('Feature') if geom is None or isinstance(geom, geometry.Geometry): # A geometry object. super(Feature, self).__init__(feature_constructor, { 'geometry': geom, 'metadata': opt_properties or None }) elif isinstance(geom, computedobject.ComputedObject): # A custom object to reinterpret as a Feature. super(Feature, self).__init__(geom.func, geom.args) elif isinstance(geom, dict) and geom.get('type') == 'Feature': # Try to convert a GeoJSON Feature. super(Feature, self).__init__( feature_constructor, { 'geometry': geometry.Geometry(geom.get('geometry', None)), 'metadata': geom.get('properties', None) }) else: # Try to convert the geometry arg to a Geometry, in the hopes of it # turning out to be GeoJSON. super(Feature, self).__init__( feature_constructor, { 'geometry': geometry.Geometry(geom), 'metadata': opt_properties or None })
def main(): if loadcase is Cases.FAT: Wind_mult = wind_multipliers.Wind_multipliers(render_hc) Wind = wind.Wind(Wind_mult, loadcase) Geom = geometry.Geometry(Wind) Geom.st_geom_picker() if Geom.structure_type is Structure_type.RHS: #TODO - Add API calls st.warning("Not yet implemented, try selecting SIGNS") pass if Geom.structure_type is Structure_type.CHS: Geom.calc_drag_CHS_AASHTO() Geom.calc_wind_pressure_sign_fat() if Geom.structure_type is Structure_type.SIGN: Geom.calc_drag_sign_AASHTO() Geom.calc_wind_pressure_sign_fat() #plot_sign = Geom.st_plot_wind_pressure() #st.bokeh_chart(plot_sign,False) else: Wind_mult = wind_multipliers.Wind_multipliers(render_hc) Wind_mult.st_region_inputs() Wind_mult.st_terrain_inputs() Wind_mult.terrain_multiplier() Wind_mult.st_wind_multipliers_input() Wind_mult.st_wind_direction_inputs() Wind_mult.calc_wind_direction_multiplier() Wind_mult.render_multipliers() Wind = wind.Wind(Wind_mult, loadcase) Wind.st_wind_speed_inputs() Wind.calc_regional_wind_speed() Wind.st_display_regional_wind_speed() Wind.calc_site_wind_speed() Geom = geometry.Geometry(Wind) Geom.st_geom_picker() if Geom.structure_type is Structure_type.RHS: Geom.calc_drag_RHS_AS1170() Geom.calc_wind_pressure_RHS() plot_RHS = Geom.st_RHS_plotting() st.bokeh_chart(plot_RHS, False) elif Geom.structure_type is Structure_type.CHS: Geom.calc_drag_CHS_AS1170() if Geom.frame_type is Frame.NONE: Geom.calc_wind_pressure_CHS() else: Geom.calc_drag_frame_CHS_AS1170() Geom.calc_wind_pressure_CHS() elif Geom.structure_type is Structure_type.SIGN: Geom.calc_drag_sign_AS1170() Geom.calc_solidity_factor() Geom.calc_wind_pressure_sign() plot_sign = Geom.st_plot_wind_pressure() st.bokeh_chart(plot_sign, False)
def __init__(self, focal_length, image_shape, sensor, eye_z=50, min_fit=60, max_fit=120): self.min_fit = min_fit self.max_fit = max_fit self.mm2px_scaling = None self.sensor_size = sensor self.update_mm2px_scaling(image_shape) self.focal_length = focal_length * self.mm2px_scaling self.pupil_radius = 2 * self.mm2px_scaling self.eye_z = eye_z * self.mm2px_scaling self.aver_eye_radius = None self.eyeball = None self.proj_eyeball_center = None self.geo = geometry.Geometry(self.focal_length, self.eye_z) self.curr_state = { "gaze_pos": None, "gaze_neg": None, "pupil3D_pos": None, "pupil3D_neg": None, "ell_center": None } self.data = { "gaze_pos": np.empty((0,3), float), "gaze_neg": np.empty((0,3), float), "pupil3D_pos": np.empty((0,3), float), "pupil3D_neg": np.empty((0,3), float), "ell_center": np.empty((0,2), float) } self.center_axis = None self.candidates = { 'x':[], 'y':[] }
def test_boom_areas(self): # problem 20.1 taken from Megson. Solution is given on the book neutral_axis = (0, 1, 0) # set up boom architecture boom0 = boom.Boom(0, [0, 150], 1000, neutral_axis) boom1 = boom.Boom(1, [500, 150], 50 * 8 + 30 * 8, neutral_axis) boom2 = boom.Boom(2, [500, -150], 50 * 8 + 30 * 8, neutral_axis) boom3 = boom.Boom(3, [0, -150], 1000, neutral_axis) edge01 = edges.Edge([0, 1], 10, 500) edge03 = edges.Edge([0, 3], 10, 300) edge12 = edges.Edge([1, 2], 8, 300) edge23 = edges.Edge([2, 3], 10, 500) booms = [boom0, boom1, boom2, boom3] edge_list = [edge01, edge03, edge12, edge23] problem_20_1 = geometry.Geometry(4, booms, edge_list, [0.], 0.) problem_20_1.construct_geometry() # calculate boom area for each boom for element in booms: element.calculate_area(problem_20_1) self.assertTrue(abs(boom0.area - 4000) < 1) self.assertTrue(abs(boom0.area - boom3.area) < 0.01) self.assertTrue(abs(boom1.area - 3540) < 1) self.assertTrue(abs(boom1.area - boom2.area) < 0.01)
def solveSN(spacing, order, savepath): print "\nSolving SN, order %d, spacing %g" % (order, spacing) f.write("\nSolving SN, order %d, spacing %g" % (order, spacing)) # setup mesh cells mesh = geometry.Geometry(pitch, spacing, fwidth, fuel, moderator) mesh.setMesh(tally_fuel_corner) cell_width = mesh.getWidth(pitch, spacing) fuel_width = mesh.getWidth(fwidth, spacing) plot_cells = mesh.getPlotCells(cell_width, fuel_width) plotter.plotMaterial(mesh, spacing, plot_cells, savepath) f.write("\nTotal number of mesh cells: \t%g" % (mesh.n_cells**2)) print "\nTotal number of mesh cells: \t%g" % (mesh.n_cells**2) f.write("\nTotal number of unknowns: \t%g" % ((mesh.n_cells**2) * order)) print "\nTotal number of unknowns: \t%g" % ((mesh.n_cells**2) * order) # give order, mesh to solver solve = solver.SN(order, mesh.cells, spacing, mesh.n_cells, mesh.n_fuel, mesh.n_mod, tol, mesh.fuel_area, mesh.mod_area, timestr, mesh.top_right_corner_fuel) solve.solveSN(max_iters, plotter, mesh, savepath, update_source) f.write( "\nConverged in %d iterations! \nAvg fuel flux = %f \nAvg mod flux = %f \nAverage Flux = %f \nFlux ratio = %f" "\nTop right fuel corner flux\t %g\nCorner flux over fuel source\t %g" % (solve.results[0], solve.results[1], solve.results[2], solve.results[3], solve.results[4], solve.results[5], solve.results[5] / q_fuel)) return solve.results[4]
def main(args): """ Generates a file containing the coordinates of a body. Parameters ---------- args: namespace Arguments parsed from the command-line. """ if args.body_type == 'file': body = geometry.Geometry(file_path=args.file_path) elif args.body_type == 'circle': body = geometry.Circle(radius=args.circle[0], center=geometry.Point(args.circle[1], args.circle[2]), n=args.n, ds=args.ds) elif args.body_type == 'line': body = geometry.Line(length=args.line[0], start=geometry.Point(args.line[1], args.line[2]), n=args.n, ds=args.ds) elif args.body_type == 'rectangle': body = geometry.Rectangle(bottom_left=geometry.Point(args.rectangle[0], args.rectangle[1]), top_right=geometry.Point(args.rectangle[2], args.rectangle[3]), nx=args.n, ny=args.n, ds=args.ds) elif args.body_type == 'sphere': body = geometry.Sphere(radius=args.sphere[0], center=geometry.Point(args.sphere[1], args.sphere[2], args.sphere[3]), n=args.n, ds=args.ds) body.scale(ratio=args.scale) body.rotation(center=args.rotation, roll=args.roll, yaw=args.yaw, pitch=args.pitch, mode=args.mode) body.translation(displacement=args.translation) if body.dimensions == 2 and args.body_type == 'file': body.discretization(n=args.n, ds=args.ds) if body.dimensions == 2 and args.extrusion: body = body.extrusion(limits=args.extrusion, n=args.n, ds=args.ds, force=args.force) if args.save: output_path = os.path.join(args.save_directory, args.save_name + '.' + args.extension) body.write(file_path=output_path) if args.show: body.plot()
def test_geo(): # Test geometry surface = geo.hex_surface() root_node = geo.GeometryNode(surface) g = geo.Geometry([root_node], voxel_scale=2.0) #print len(geo.voxel_dict.values()) #print len([val for val in geo.voxel_dict.values() if len(val) > 0]) ray = geo.Ray(np.array([0, 0, -20]), np.array([0, 0, 1])) print g.ray_trace(ray) print g.ray_trace(ray, all_intersections=True)
def GenerateHSGrid(lrho,ltheta,lphi): """ Generate a grid of geometries in hyperspherical coordinates a list of geometry class objects are returned. lrho/ltheta/lphi : list of values """ lhs = [] for rho in lrho: for theta in ltheta: for phi in lphi: hc = geometry.Geometry(rho,theta,phi) lhs.append(hc) return lhs
def test_shear_flow_pure_torsion(self): # this problem is a generic pure torsion problem # initialise booms neutral_axis = (0, 1, 0) boom_list = [] boom0 = boom.Boom(0, [900, 250], 0.0, neutral_axis) boom_list.append(boom0) boom1 = boom.Boom(1, [900, -250], 0.0, neutral_axis) boom_list.append(boom1) boom2 = boom.Boom(2, [400, -250], 0.0, neutral_axis) boom_list.append(boom2) boom3 = boom.Boom(3, [0, -250], 0.0, neutral_axis) boom_list.append(boom3) boom4 = boom.Boom(4, [0, 250], 0.0, neutral_axis) boom_list.append(boom4) boom5 = boom.Boom(5, [400, 250], 0.0, neutral_axis) boom_list.append(boom5) # initialise edges edge_list = [] edge01 = edges.Edge([0, 1], 4, 500) edge_list.append(edge01) edge12 = edges.Edge([1, 2], 4, 500) edge_list.append(edge12) edge23 = edges.Edge([2, 3], 2, 400) edge_list.append(edge23) edge34 = edges.Edge([3, 4], 2, 500) edge_list.append(edge34) edge45 = edges.Edge([4, 5], 2, 400) edge_list.append(edge45) edge50 = edges.Edge([5, 0], 4, 500) edge_list.append(edge50) edge52 = edges.Edge([5, 2], 3, 500) edge_list.append(edge52) # initialise geometry problem_torsion = geometry.Geometry(6, boom_list, edge_list, [400 * 500, 500**2], 27 * 10**3) problem_torsion.cells = [[edge50, edge01, edge12, edge52], [edge45, edge52, edge34, edge23]] problem_torsion.construct_geometry() # calculate torsion shear flows problem_torsion_section = DiscreteSection.DiscreteSection( neutral_axis, problem_torsion) problem_torsion_section.calc_torsion_shear_flow(2.0329 * 10**9, edge52) # verify twist rate self.assertTrue( abs(problem_torsion_section.twist_rate * 10**5 - 8.73) < 1)
def clip(self, clip_geometry): """Clips an image by a Geometry, Feature or FeatureCollection. Args: clip_geometry: The Geometry, Feature or FeatureCollection to clip to. Returns: The clipped image. """ try: # Need to manually promote GeoJSON, because the signature does not # specify the type so auto promotion won't work. clip_geometry = geometry.Geometry(clip_geometry) except ee_exception.EEException: pass # Not an ee.Geometry or GeoJSON. Just pass it along. return apifunction.ApiFunction.call_('Image.clip', self, clip_geometry)
def makeGeometry(): pitch = 1.27 circle = geom.Circle(pitch / 2, pitch / 2, 0.4) fuelCell = geom.SurfaceNode(circle, False) waterCell = geom.SurfaceNode(circle, True) fuel = geom.Region('fuel') fuel.cell = fuelCell fuel.volume = circle.area() water = geom.Region('water') water.cell = waterCell water.volume = pitch**2 - circle.area() g = geom.Geometry(pitch, pitch) g.addRegion(fuel) g.addRegion(water) return g
def test_inertia0(self): # test moment of inertia calculation comparing it to results of example 20.2 in Megson # IMPORTANT: this only passes the test if on the moment of inertia calculator the line where the list of # distances is calculated is COMMENTED OUT. This is because the list of distances that should be used is given # directly on the example so they should NOT be recalculated. example_20_2 = geometry.Geometry(16, [0], [], [], 0.0) example_20_2.boom_areas = [ 640, 600, 600, 600, 620, 640, 640, 850, 640, 600, 600, 600, 620, 640, 640, 850 ] example_20_2.y_dists = np.array([ 660, 600, 420, 228, 25, -204, -396, -502, -540, 600, 420, 228, 25, -204, -396, -502 ]) example_20_2.centroid = (0, 0) example_20_2.moment_inertia_Izz() # 1 is a good enough error because in Megson they round the contribution of each boom, so they accumulate error # from the 16 components self.assertTrue(abs(example_20_2.Izz * 10**(-6) - 1854) < 1)
def makePlotSegments(num_azim, spacing, t, savepath): f = open('%s.txt' % resultsfile, 'a+') print "\nPlotting segments, n_azim %d, track spacing %g, mesh spacing %g" % ( num_azim, t, spacing) mesh = geom.Geometry(pitch, spacing, fwidth, fuelmat, moderator) mesh.setMesh(tally_fuel_corner) setup = InitializeTracks(num_azim, t, pitch, pitch, n_p, r, fsr, fuelgeom) setup.getTrackParams() setup.makeTracks() setup.findIntersection() #setup.plotTracks(savepath) setup.findAllTrackCellIntersect(mesh.cells, spacing) #setup.plotCellSegments(spacing, savepath) f.write( "n_azim \t%d \ttrack spacing %g\tmesh spacing\t%g\tsegments\t%g\n" % (num_azim, t, spacing, setup.tot_num_segments)) #f.write("\nTotal number of segments \t %g\n\n" % (setup.tot_num_segments)) print "\nTotal number of segments \t %g\n\n" % (setup.tot_num_segments) f.close()
def test_areas_centroid_inertia(self): # following the example on slide 43 of https://www.slideshare.net/scemd3/lec6aircraft-structural-idealisation-1 # set up boom architecture neutral_axis = (0, 1, 0) boom0 = boom.Boom(0, [-250, 150], 1000, neutral_axis) boom1 = boom.Boom(1, [250, 150], 640, neutral_axis) boom2 = boom.Boom(2, [250, -150], 640, neutral_axis) boom3 = boom.Boom(3, [-250, -150], 1000, neutral_axis) edge01 = edges.Edge([0, 1], 10, 500) edge03 = edges.Edge([0, 3], 10, 300) edge12 = edges.Edge([1, 2], 8, 300) edge23 = edges.Edge([2, 3], 10, 500) # calculate area for each boom example_43 = geometry.Geometry(4, [boom0, boom1, boom2, boom3], [edge01, edge03, edge12, edge23], [0.0], 0.) example_43.construct_geometry() for element in [boom0, boom1, boom2, boom3]: element.calculate_area(example_43) # test the boom areas example_43.get_areas() self.assertTrue( abs(example_43.boom_areas[0] - example_43.boom_areas[3]) < 0.01 and abs(example_43.boom_areas[0] - 4000) < 0.01) self.assertTrue( abs(example_43.boom_areas[1] - example_43.boom_areas[1]) < 0.01 and abs(example_43.boom_areas[1] - 3540) < 0.01) # test centroid example_43.calc_centroid() self.assertTrue(abs(abs(example_43.centroid[0]) - 15.25) < 0.1) self.assertTrue(abs(abs(example_43.centroid[1]) - 0.0) < 0.1) # test moments of inertia example_43.moment_inertia_Izz() example_43.moment_inertia_Iyy() self.assertTrue(abs(example_43.Izz - 339300000) < 1) self.assertTrue(abs(example_43.Iyy - 938992042.5) < 1) self.assertTrue(abs(example_43.Izy) < 1)
def test_propagation(): surface = geo.hex_surface() root_node = geo.GeometryNode(surface) root_node.properties = materials.get_properties(92) g = geo.Geometry([root_node], voxel_scale=2.0) position = np.random.uniform(size=3) direction = -position / np.linalg.norm(position) position *= 2 #print position, direction #position, direction = (np.array([0, 0, -20]), np.array([0, 0, 1])) mass = tracking.muon_mass energy = 1 track = tracking.Track(position, direction, mass, energy, g) #print track.ray.p, track.ray.d prop = tracking.Propagator(track) while True: result = prop.propagate_step() #print track.ray.p, track.ray.d if not track.geometry.volume.contains_point(track.ray.p) or not result: break
def test_boom_normal_stress(self): # taken from http://www.ltas-cm3.ulg.ac.be/MECA0028-1/StructAeroAircraftComp.pdf # exercise on slide 26 # set up boom list and areas boom_list = [] neutral_axis = (0, 1, 0) boom0 = boom.Boom(0, [300, -600], 0.0, neutral_axis) boom_list.append(boom0) boom0.area = 900 boom1 = boom.Boom(1, [300, 0], 0.0, neutral_axis) boom_list.append(boom1) boom1.area = 1200 boom2 = boom.Boom(2, [300, 600], 0.0, neutral_axis) boom_list.append(boom2) boom2.area = 900 boom3 = boom.Boom(3, [-300, 600], 0.0, neutral_axis) boom_list.append(boom3) boom3.area = 900 boom4 = boom.Boom(4, [-300, 0], 0.0, neutral_axis) boom_list.append(boom4) boom4.area = 1200 boom5 = boom.Boom(5, [-300, -600], 0.0, neutral_axis) boom_list.append(boom5) boom5.area = 900 # initialise Geometry instance anc calculate geometrical properties example_liege = geometry.Geometry(6, boom_list, [], [], 0.0) example_liege.get_areas() example_liege.calc_centroid() example_liege.moment_inertia_Iyy() example_liege.moment_inertia_Izz() # calculate and test normal stresses for element in example_liege.booms: element.calc_z_dist(example_liege) element.calc_y_dist(example_liege) element.calc_bending_stress(0, -200 * 10**2, example_liege) self.assertTrue(abs(abs(element.bending_stress) - 0.0111) < 0.01)
def test_detection(n=1): tank_node = geo.GeometryNode(geo.regular_prism_surface(r=.92, l=2, n=12, center=np.array( [0, 0, 0]), rotation=None), name='tank') tank_node.properties = materials.get_properties(13) water_node = geo.GeometryNode(geo.regular_prism_surface(r=.915, l=1.98, n=12, center=np.array( [0, 0, 0]), rotation=None), parent=tank_node, name='water') water_node.properties = materials.get_properties('water') rod_node = geo.GeometryNode(geo.regular_prism_surface(r=.064, l=1.96, n=6, center=np.array( [0, 0, 0]), rotation=None), parent=water_node, name='metal_rod') rod_node.properties = materials.get_properties(13) U_node = geo.GeometryNode(geo.regular_prism_surface(r=.06, l=1.5, n=6, center=np.array( [0, 0, 0]), rotation=None), parent=rod_node, name='U') U_node.properties = materials.get_properties(92) scale = np.array([3., .1, 3.]) big_scale = np.array([6., 6., 6.]) big = np.array([0., 0., 0.]) upper = np.array([0., -1., 1.]) lower = np.array([0., 1., -1.]) big_det_surface = geo.Surface( geo.Voxel(big, big_scale, vol=True).get_faces()) #upper_det_surface = geo.Surface(geo.Voxel(upper, scale, vol=True).get_faces()) #lower_det_surface = geo.Surface(geo.Voxel(lower, scale, vol=True).get_faces()) #upper_node = geo.GeometryNode(upper_det_surface) #lower_node = geo.GeometryNode(lower_det_surface) big_node = geo.GeometryNode(big_det_surface, name='big_detector') big_node.properties = materials.get_properties(7) #upper_node.properties = materials.get_properties(6) #lower_node.properties = materials.get_properties(6) big_node.properties['det'] = 'big' #upper_node.properties['det'] = 'upper' #lower_node.properties['det'] = 'lower' #g = geo.Geometry([tank_node, upper_node, lower_node], voxel_scale=1) big_node.add_child(tank_node) g = geo.Geometry([big_node], voxel_scale=1) node = big_node while node is not None: print node.level, ':', node.properties['Z'] if len(node.children) == 0: node = None else: node = node.children[0] sim_scale = np.array([12., 12., 12.]) sim = np.array([0., 0., 0.]) sim_v = geo.Voxel(sim, sim_scale, vol=True) # Define energy spectrum parameters gamma = -2. E0 = 10. E1 = 100. logs = [] maxZs = [] for i in xrange(n): if i % 100 == 0: print i print collections.Counter(maxZs) phi = 2 * np.pi * np.random.uniform() theta = np.arccos(1. - 2. * np.random.uniform()) position = geo.deflect_vector(np.array([0., 0., 5.5]), theta, phi, preserve_mag=True) direction = np.array([0, 0, 0]) - position direction = direction / np.linalg.norm(direction) phi = 2 * np.pi * np.random.uniform() theta = np.arccos(1. - 0.03 * np.random.uniform()) direction = geo.deflect_vector(direction, theta, phi, preserve_mag=False) mass = tracking.muon_mass y = np.random.uniform() energy = ((E1**(gamma + 1) - E0**(gamma + 1)) * y + E0**(gamma + 1))**(1 / (gamma + 1)) track = tracking.Track(position, direction, mass, energy, g) prop = tracking.Propagator(track) start = time.time() while True: try: result = prop.propagate_step() except KeyboardInterrupt: raise outside_sim_v = not sim_v.contains_point(prop.track.ray.p) hit_detector = len(track.detector_log) >= 2 if outside_sim_v or hit_detector: #print 'hit:', hit_detector, ', outside:', outside_sim_v, ', point:', prop.track.ray.p #print track.detector_log prop.finish() break end = time.time() duration = end - start log = track.detector_log if len(log) == 2: #log = [[log[0][0], log[0][1]], [log[1][0], log[1][1]]] maxZ = max(prop.material_log, key=lambda x: x[1])[1] maxZs.append(maxZ) logs.append(log) return logs, maxZs
def initialise_problem(): stringer_area = 42 * 10**(-6) neutral_axis = (0, 1, 0) # CREATE LIST OF COORDINATES FOR BOOMS # give the coordinates of the booms with respect to the hinge point # for the first eight, they are on a straight line coordinates = [] for n in range(16): coordinates.append([((43.45 - 5.43125 / 2 * (n + 1)) * 10) * 10**(-3), ((1.40625 / 2 * (n + 1)) * 10) * 10**(-3)]) # booms 8, 9 and 10 are along a semi-circle coordinates.append([ -112.5 * math.sin(math.pi / 8) * 10**(-3), 112.5 * math.cos(math.pi / 8) * 10**(-3) ]) coordinates.append([ -112.5 * math.sin(math.pi / 4) * 10**(-3), 112.5 * math.cos(math.pi / 4) * 10**(-3) ]) coordinates.append([ -112.5 * math.sin(3 * math.pi / 8) * 10**(-3), 112.5 * math.cos(3 * math.pi / 8) * 10**(-3) ]) coordinates.append([-112.5 * 10**(-3), 0.0]) # the last 8 are symmetric to the first eight wrt the z-axis for i in range(18, -1, -1): coords = coordinates[i] coordinates.append([coords[0], -coords[1]]) # the ones on the spar are always at z=0 and distributed equally along the height of the spar coordinates.append([0.0, (22.5 + 45) * 10**(-3)]) coordinates.append([0.0, 22.5 * 10**(-3)]) coordinates.append([0.0, -22.5 * 10**(-3)]) coordinates.append([0.0, (-22.5 - 45) * 10**(-3)]) # CREATE BOOM INSTANCES AND INSERT THEM IN GEOMETRY booms = [] boom0 = boom.Boom(0, coordinates[0], 0.0, neutral_axis) booms.append(boom0) boom1 = boom.Boom(1, coordinates[1], stringer_area, neutral_axis) booms.append(boom1) boom2 = boom.Boom(2, coordinates[2], 0.0, neutral_axis) booms.append(boom2) boom3 = boom.Boom(3, coordinates[3], stringer_area, neutral_axis) booms.append(boom3) boom4 = boom.Boom(4, coordinates[4], 0.0, neutral_axis) booms.append(boom4) boom5 = boom.Boom(5, coordinates[5], stringer_area, neutral_axis) booms.append(boom5) boom6 = boom.Boom(6, coordinates[6], 0.0, neutral_axis) booms.append(boom6) boom7 = boom.Boom(7, coordinates[7], stringer_area, neutral_axis) booms.append(boom7) boom8 = boom.Boom(8, coordinates[8], 0.0, neutral_axis) booms.append(boom8) boom9 = boom.Boom(9, coordinates[9], stringer_area, neutral_axis) booms.append(boom9) boom10 = boom.Boom(10, coordinates[10], 0.0, neutral_axis) booms.append(boom10) boom11 = boom.Boom(11, coordinates[11], stringer_area, neutral_axis) booms.append(boom11) boom12 = boom.Boom(12, coordinates[12], 0.0, neutral_axis) booms.append(boom12) boom13 = boom.Boom(13, coordinates[13], stringer_area, neutral_axis) booms.append(boom13) boom14 = boom.Boom(14, coordinates[14], 0.0, neutral_axis) booms.append(boom14) boom15 = boom.Boom(15, coordinates[15], 0.0, neutral_axis) booms.append(boom15) # semi circle booms boom16 = boom.Boom(16, coordinates[16], 0.0, neutral_axis) booms.append(boom16) boom17 = boom.Boom(17, coordinates[17], stringer_area, neutral_axis) booms.append(boom17) boom18 = boom.Boom(18, coordinates[18], 0.0, neutral_axis) booms.append(boom18) boom19 = boom.Boom(19, coordinates[19], stringer_area, neutral_axis) booms.append(boom19) boom20 = boom.Boom(20, coordinates[20], 0.0, neutral_axis) booms.append(boom20) boom21 = boom.Boom(21, coordinates[21], stringer_area, neutral_axis) booms.append(boom21) boom22 = boom.Boom(22, coordinates[22], 0.0, neutral_axis) booms.append(boom22) # lower straight line booms boom23 = boom.Boom(23, coordinates[23], 0.0, neutral_axis) booms.append(boom23) boom24 = boom.Boom(24, coordinates[24], 0.0, neutral_axis) booms.append(boom24) boom25 = boom.Boom(25, coordinates[25], stringer_area, neutral_axis) booms.append(boom25) boom26 = boom.Boom(26, coordinates[26], 0.0, neutral_axis) booms.append(boom26) boom27 = boom.Boom(27, coordinates[27], stringer_area, neutral_axis) booms.append(boom27) boom28 = boom.Boom(28, coordinates[28], 0.0, neutral_axis) booms.append(boom28) boom29 = boom.Boom(29, coordinates[29], stringer_area, neutral_axis) booms.append(boom29) boom30 = boom.Boom(30, coordinates[30], 0.0, neutral_axis) booms.append(boom30) boom31 = boom.Boom(31, coordinates[31], stringer_area, neutral_axis) booms.append(boom31) boom32 = boom.Boom(32, coordinates[32], 0.0, neutral_axis) booms.append(boom32) boom33 = boom.Boom(33, coordinates[33], stringer_area, neutral_axis) booms.append(boom33) boom34 = boom.Boom(34, coordinates[34], 0.0, neutral_axis) booms.append(boom34) boom35 = boom.Boom(35, coordinates[35], stringer_area, neutral_axis) booms.append(boom35) boom36 = boom.Boom(36, coordinates[36], 0.0, neutral_axis) booms.append(boom36) boom37 = boom.Boom(37, coordinates[37], stringer_area, neutral_axis) booms.append(boom37) boom38 = boom.Boom(38, coordinates[38], 0.0, neutral_axis) booms.append(boom38) # booms on the spar boom39 = boom.Boom(39, coordinates[39], 0.0, neutral_axis) booms.append(boom39) boom40 = boom.Boom(40, coordinates[40], 0.0, neutral_axis) booms.append(boom40) boom41 = boom.Boom(41, coordinates[41], 0.0, neutral_axis) booms.append(boom41) boom42 = boom.Boom(42, coordinates[42], 0.0, neutral_axis) booms.append(boom42) # CREATE EDGES INSTANCES AND PUT THEM IN A LIST edge_list = [] edge10 = edges.Edge([1, 0], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge10) edge21 = edges.Edge([2, 1], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge21) edge32 = edges.Edge([3, 2], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge32) edge43 = edges.Edge([4, 3], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge43) edge54 = edges.Edge([5, 4], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge54) edge65 = edges.Edge([6, 5], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge65) edge76 = edges.Edge([7, 6], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge76) edge87 = edges.Edge([8, 7], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge87) edge98 = edges.Edge([9, 8], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge98) edge109 = edges.Edge([10, 9], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge109) edge1110 = edges.Edge([11, 10], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge1110) edge1211 = edges.Edge([12, 11], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge1211) edge1312 = edges.Edge([13, 12], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge1312) edge1413 = edges.Edge([14, 13], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge1413) edge1514 = edges.Edge([15, 14], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge1514) # booms on semicircle edge1615 = edges.Edge([16, 15], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge1615) edge1716 = edges.Edge([17, 16], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge1716) edge1817 = edges.Edge([18, 17], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge1817) edge1918 = edges.Edge([19, 18], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge1918) edge2019 = edges.Edge([20, 19], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge2019) edge2120 = edges.Edge([21, 20], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge2120) edge2221 = edges.Edge([22, 21], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge2221) edge2322 = edges.Edge([23, 22], 1.1 * 10**(-3), 44.179 * 10**(-3)) edge_list.append(edge2322) # booms on lower spar edge2423 = edges.Edge([24, 23], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge2423) edge2524 = edges.Edge([25, 24], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge2524) edge2625 = edges.Edge([26, 25], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge2625) edge2726 = edges.Edge([27, 26], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge2726) edge2827 = edges.Edge([28, 27], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge2827) edge2928 = edges.Edge([29, 28], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge2928) edge3029 = edges.Edge([30, 29], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3029) edge3130 = edges.Edge([31, 30], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3130) edge3231 = edges.Edge([32, 31], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3231) edge3332 = edges.Edge([33, 32], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3332) edge3433 = edges.Edge([34, 33], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3433) edge3534 = edges.Edge([35, 34], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3534) edge3635 = edges.Edge([36, 35], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3635) edge3736 = edges.Edge([37, 36], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3736) edge3837 = edges.Edge([38, 37], 1.1 * 10**(-3), 56.103 * 0.5 * 10**(-3)) edge_list.append(edge3837) edge038 = edges.Edge([0, 38], 1.1 * 10**(-3), 56.103 * 10**(-3)) edge_list.append(edge038) # booms on the vertical spar edge3915 = edges.Edge([39, 15], 2.9 * 10**(-3), 45 * 10**(-3)) edge_list.append(edge3915) edge4039 = edges.Edge([40, 39], 2.9 * 10**(-3), 45 * 10**(-3)) edge_list.append(edge4039) edge4140 = edges.Edge([41, 40], 2.9 * 10**(-3), 45 * 10**(-3)) edge_list.append(edge4140) edge4241 = edges.Edge([42, 41], 2.9 * 10**(-3), 45 * 10**(-3)) edge_list.append(edge4241) edge2342 = edges.Edge([23, 42], 2.9 * 10**(-3), 45 * 10**(-3)) edge_list.append(edge2342) # CREATE INSTANCE OF AILERON GEOMETRY WITH ALL THE BOOMS aileron_geometry = geometry.Geometry( 43, booms, edge_list, [19880.391 * 10**(-6), 36225 * 10**(-6)], 28 * 10**9) aileron_geometry.construct_geometry() aileron_geometry.cells = [[ edge038, edge3837, edge3736, edge3635, edge3534, edge3433, edge3332, edge3231, edge3130, edge3029, edge2928, edge2827, edge2726, edge2625, edge2524, edge2423, edge2342, edge4241, edge4140, edge4039, edge3915, edge1514, edge1413, edge1312, edge1211, edge1110, edge109, edge98, edge87, edge76, edge65, edge54, edge43, edge32, edge21, edge10 ], [ edge2019, edge1918, edge1817, edge1716, edge1615, edge3915, edge4039, edge4140, edge4241, edge2342, edge2322, edge2221, edge2120 ]] # calculate areas of all booms for element in booms: element.calculate_area(aileron_geometry) # insert them in aileron_geometry object aileron_geometry.get_areas() # calculate centroid position aileron_geometry.calc_centroid() for boom_element in booms: boom_element.calc_y_dist(aileron_geometry) boom_element.calc_z_dist(aileron_geometry) # calculate moments of inertia aileron_geometry.moment_inertia_Izz() aileron_geometry.moment_inertia_Iyy() # PLOT AND PRINT GEOMETRICAL PROPERTIES FOR VERIFICATION aileron_geometry.plot_edges() for it, el in enumerate(booms): print('area of boom ', it, ' : ', aileron_geometry.boom_areas[it], '[mm^2]') print('centroid position : ', aileron_geometry.centroid) print('z moment of inertia : ', aileron_geometry.Izz, ' [mm^4]') print('y moment of inertia : ', aileron_geometry.Iyy, ' [mm^4]') print('zy moment of inertia : ', aileron_geometry.Izy, '[mm^4]') # GET THE LIST OF FORCES AND MOMENTS file_name = "Loads.txt" x_i_array = helpers.get_array_x_i(file_name) Mx_array = helpers.get_array_Mx_i(file_name) My_array = helpers.get_array_My_i(file_name) Mz_array = helpers.get_array_Mz_i(file_name) Sz_array = helpers.get_array_Sz_i(file_name) Sy_array = helpers.get_array_Sy_i(file_name) # create a matrix of stresses stress_matrix = np.zeros((43, 101)) for j, location in enumerate(x_i_array): for i, boom_member in enumerate(aileron_geometry.booms): boom_member.calc_bending_stress(Mz_array[j], My_array[j], aileron_geometry) stress_matrix[i][j] = boom_member.bending_stress # find maximum stress max_stress_matrix = np.amax(stress_matrix, axis=1) # set up matrix of shear stresses stress_matrix_shear = np.zeros((len(aileron_geometry.edges), 101)) # set up lists twist_rate_list = [] thetas_list = [] section_numbers = 100 step = 2.771 / section_numbers thetas_list.append(0.453786) file = open("thetas_list.txt", "w") for i, x_i in enumerate(x_i_array): # create new instance of section with new location aileron_section = DiscreteSection.DiscreteSection( neutral_axis, aileron_geometry) # calculate shear flows due to pure shear and torque aileron_section.calc_total_shear_flow(Sz_array[i], Sy_array[i], Mx_array[i], edge2342) # calculate shear stress due to total shear flows and insert in the shear stress matrix aileron_section.calc_shear_stress() for n1, edge_ex in enumerate(aileron_geometry.edges): stress_matrix_shear[n1][i] = edge_ex.shear_stress # append the twist rate (computed at the same time as torque shear flow) in the twist rate list twist_rate_list.append(aileron_section.twist_rate) # calculate theta with finite differences, append to the list and copy to the txt file theta = twist_rate_list[i - 1] * step + thetas_list[i - 1] thetas_list.append(theta) file.write(str(float(theta)) + '\n') # find the maximum shear stress on each rib print('the maximum shear stress in rib A : ', np.max(stress_matrix_shear[:, 97])) print('the maximum shear stress in rib B : ', np.max(stress_matrix_shear[:, 51])) print('the maximum shear stress in rib C : ', np.max(stress_matrix_shear[:, 41])) print('the maximum shear stress in rib D : ', np.max(stress_matrix_shear[:, 18])) # find the maximum normal stress on each rib print('the maximum normal stress in rib A : ', np.max(stress_matrix[:, 97])) print('the maximum normal stress in rib A : ', np.max(stress_matrix[:, 51])) print('the maximum normal stress in rib A : ', np.max(stress_matrix[:, 41])) print('the maximum normal stress in rib A : ', np.max(stress_matrix[:, 18]))
import geometry as gm import simulator as simu import material as mt import time def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. if __name__ == '__main__': cell0 = gm.Cell(2, -80, -50, 1000, -1000, 1000, -1000) cell1 = gm.Cell(1, -50, 50, 1000, -1000, 1000, -1000) cell2 = gm.Cell(2, 50, 80, 1000, -1000, 1000, -1000) mat1 = mt.Material(1, 0.7, 0.0092, 0.010) mat2 = mt.Material(2, 0.9, 0.002, 0) cell_list = [cell0, cell1, cell2] geo = gm.Geometry(cell_list) mat_list = [mat1, mat2] mode1 = simu.Mode(100, 50, 30, False) runner = simu.Simulate(geo, mat_list, mode1) t1 = time.time() runner.run() t2 = time.time() - t1 print_hi(f'succeed, run in {t2} seconds')
def test_shear_flow_pure_shear0(self): # following the problem 23.6 in Megson # set up booms and edges neutral_axis = (0, 1, 0) boom0 = boom.Boom(0, [1092, 153], 0.0, neutral_axis) boom1 = boom.Boom(1, [736, 153], 0.0, neutral_axis) boom2 = boom.Boom(2, [380, 153], 0.0, neutral_axis) boom3 = boom.Boom(3, [0, 153], 0.0, neutral_axis) boom4 = boom.Boom(4, [0, -153], 0.0, neutral_axis) boom5 = boom.Boom(5, [380, -153], 0.0, neutral_axis) boom6 = boom.Boom(6, [736, -153], 0.0, neutral_axis) boom7 = boom.Boom(7, [1092, -153], 0.0, neutral_axis) boom_list = [boom0, boom1, boom2, boom3, boom4, boom5, boom6, boom7] edge10 = edges.Edge([1, 0], 0.915, 356) edge07 = edges.Edge([0, 7], 1.250, 306) edge21 = edges.Edge([2, 1], 0.915, 356) edge32 = edges.Edge([3, 2], 0.783, 380) edge52 = edges.Edge([5, 2], 1.250, 306) edge34 = edges.Edge([3, 4], 1.250, 610) edge54 = edges.Edge([5, 4], 0.783, 380) edge65 = edges.Edge([6, 5], 0.915, 356) edge76 = edges.Edge([7, 6], 0.915, 356) edge_list = [ edge52, edge21, edge10, edge07, edge76, edge65, edge32, edge34, edge54 ] problem_23_6 = geometry.Geometry(8, boom_list, edge_list, [217872, 167780], 24.2 * 10**9) problem_23_6.cells = [[edge10, edge07, edge76, edge65, edge52, edge21], [edge34, edge32, edge52, edge54]] boom0.area = 1290 boom1.area = 645 boom2.area = 1290 boom3.area = 645 boom4.area = 645 boom5.area = 1290 boom6.area = 645 boom7.area = 1290 # calculate geometrical properties problem_23_6.get_areas() problem_23_6.construct_geometry() problem_23_6.calc_centroid() problem_23_6.moment_inertia_Iyy() problem_23_6.moment_inertia_Izz() for boom_element in boom_list: boom_element.calc_y_dist(problem_23_6) boom_element.calc_z_dist(problem_23_6) # test moment of inertia self.assertTrue(abs(problem_23_6.Izz * 10**(-6) - 181.2) < 1) # calculate shear flow due to shear forces problem_23_6_section = DiscreteSection.DiscreteSection( neutral_axis, problem_23_6) problem_23_6_section.calc_shear_flow_q_B(0, 66750, edge52) problem_23_6_section.calc_closed_section_pure_shear_flow_q_0(edge52) # test open section shear flow self.assertTrue(abs(edge10.q_B - 0.0) < 1) self.assertTrue(abs(edge07.q_B - (-72.6)) < 1) self.assertTrue(abs(edge32.q_B - (-36.2)) < 1) self.assertTrue(abs(edge21.q_B - 36.2) < 1) self.assertTrue(abs(edge34.q_B) < 0.1) self.assertTrue(abs(edge54.q_B - (-36.3)) < 1) self.assertTrue(abs(edge52.q_B - 145.3) < 1) self.assertTrue(abs(edge65.q_B - 36.3) < 1) self.assertTrue(abs(edge76.q_B) < 1) # test closed section shear flow self.assertTrue( abs(edge21.q_0 - (-39.2)) < 1 and abs(edge10.q_0 - (-39.2)) < 1 and abs(edge07.q_0 - (-39.2)) < 1 and abs(edge76.q_0 - (-39.2)) < 1 and abs(edge65.q_0 - (-39.2)) < 1) self.assertTrue( abs(edge32.q_0 - 17.8) < 1 and abs(edge34.q_0 - 17.8) < 1 and abs(edge54.q_0 - 17.8) < 1) self.assertTrue(abs(edge52.q_0 - (-57)) < 1)
thetaLoc = numpy.linspace(1,n,n)*numpy.pi/(2.0*n) bref = 10.0 yLoc = 0.5*bref*numpy.cos(thetaLoc) chordLoc = dvs['chordLoc'] aIncGeometricLoc = dvs['aIncGeometricLoc'] aeroCLaRoot = numpy.array([0.0, 0.0, 2*numpy.pi, 0.0]) aeroCLaTip = numpy.array([0.0, 0.0, 2*numpy.pi, 0.0]) #aeroCLaRoot = numpy.array([ -28.2136, 16.4140, 0.9568,-0.4000]) #aeroCLaTip = numpy.array([ -28.2136, 16.4140, 0.9568, -0.4000]) clPolyLoc = numpy.zeros((4,n)) #setup lift slope curves for each station for i in range(n): clPolyLoc[:,i] = aeroCLaRoot[:] + 2.0*(aeroCLaTip[:] - aeroCLaRoot[:])*yLoc[i]/bref geom = geometry.Geometry(thetaLoc, chordLoc, yLoc, aIncGeometricLoc, clPolyLoc, bref, n) (makeMeZero, alphaiLoc, CL, CDi) = setupImplicitFunction(dvs['operAlpha'], dvs['An'], geom) outputsFcn = C.SXFunction([dvs.cat], [alphaiLoc, CL, CDi, geom.sref]) outputsFcn.init() g = CT.struct_SX([ CT.entry("makeMeZero",expr=makeMeZero), CT.entry('alphaiLoc',expr=alphaiLoc), CT.entry("CL",expr=CL), CT.entry("CDi",expr=CDi), CT.entry("sref",expr=geom.sref)]) obj = -CL / (CDi + 0.01) nlp = C.SXFunction(C.nlpIn(x=dvs),C.nlpOut(f=obj,g=g))
def solveMOC(num_azim, spacing, t, savepath): #resultfilename = '/' + resultsfile + '' f = open('%s.txt' % resultsfile, 'a+') print "\nSolving MOC, n_azim %d, track spacing %g, mesh spacing %g" % ( num_azim, t, spacing) f.write("\nSolving MOC, n_azim %d, track spacing %g, mesh spacing %g" % (num_azim, t, spacing)) check = ConvergenceTest() # setup mesh cells mesh = geom.Geometry(pitch, spacing, fwidth, fuelmat, moderator) mesh.setMesh(tally_fuel_corner) cell_width = mesh.getWidth(pitch, spacing) fuel_width = mesh.getWidth(fwidth, spacing) plot_cells = mesh.getPlotCells(cell_width, fuel_width) plotter.plotMaterial(mesh, spacing, plot_cells, savepath) ##################################### ########## GENERATE TRACKS ########## ##################################### setup = InitializeTracks(num_azim, t, pitch, pitch, n_p, r, fsr, fuelgeom) setup.getTrackParams() setup.makeTracks() setup.getAngularQuadrature() setup.getPolarWeight() setup.findIntersection() setup.plotTracks(savepath) setup.reflectRays() setup.findAllTrackCellIntersect(mesh.cells, spacing) setup.getFSRVolumes(fuel, mod, mesh) f.write("\nTotal number of angles \t %g\n" % (num_azim * 2)) f.write("\nTotal number of segments \t %g\n" % (setup.tot_num_segments)) print "\nTotal number of segments \t %g\n" % (setup.tot_num_segments) ###################################### ########## SOLVE FOR FLUXES ########## ###################################### flux = MethodOfCharacteristics(sigma_fuel_tot, sigma_mod_tot, fsr, setup, check, mesh) MOCresults = flux.solveFlux(num_iter_max, tol, update_source) midpt = mesh.n_cells / 2 - 1 plotter.plotScalarFlux(mesh, 0, mesh.mesh, 0, savepath) plotter.plotCenterFlux(mesh, mesh.cells, midpt, flux.results[0], 1, savepath) plotter.plotCenterFluxY(mesh, mesh.cells, midpt, flux.results[0], 2, savepath) if MOCresults: """ f.write("\nConverged in %d iterations! L2 \t%g \nAvgfuelflux\t %f \nAvgmodflux\t %f\nAverageFlux\t %f " "\nFluxratio\t %f\nfuelcornerflux\t %g\nCorner_normalized\t %g\n\n" % (flux.results[0], flux.l2 ,flux.results[1], flux.results[2], flux.results[3], flux.results[4], flux.results[5], flux.results[5] / q_fuel)) """ f.write("#seg\tAvgfuelfl\t Avgmodfl\t AvgFlux\t " "Fluxrat\t cornerfl\t Corner_norm\t \n" "%f\t%f\t%f\t%f\t%f\t%g\t%g\n\n\n" "\nConverged in %d iterations!\t L2 \t%g \n" % (setup.tot_num_segments, flux.results[1], flux.results[2], flux.results[3], flux.results[4], flux.results[5], flux.results[5] / q_fuel, flux.results[0], flux.l2)) #normalized = Corner flux over fuel source\t %g\n\n" f.close() elif not MOCresults: f.write( "\n*********************************\n" "Not converged after %d iterations. Rerun this case with more iterations. \nL2 \t%g" % (num_iter_max, flux.l2)) f.write( "\nAvg fuel flux = %f nAvg mod flux = %f \nAverage Flux = %f \nFlux ratio = %f" "\nTop right fuel corner flux\t %g\nCorner flux over fuel source\t %g\n" "\n ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * \n" % (flux.results[1], flux.results[2], flux.results[3], flux.results[4], flux.results[5], flux.results[5] / q_fuel)) f.close()
def test_shear_flow_pure_shear1(self): # using problem 23.5 in Megson. Some sign conventions are switched for consistency. # initialise booms neutral_axis = (0, 1, 0) boom0 = boom.Boom(0, [-635, -127], 0.0, neutral_axis) boom1 = boom.Boom(1, [0, -203], 0.0, neutral_axis) boom2 = boom.Boom(2, [763, -101], 0.0, neutral_axis) boom3 = boom.Boom(3, [763, 101], 0.0, neutral_axis) boom4 = boom.Boom(4, [0, 203], 0.0, neutral_axis) boom5 = boom.Boom(5, [-635, 127], 0.0, neutral_axis) boom_list = [boom0, boom1, boom2, boom3, boom4, boom5] # initialise edges edge45 = edges.Edge([4, 5], 0.915, 647) edge14 = edges.Edge([1, 4], 2.032, 406) edge10 = edges.Edge([1, 0], 0.915, 647) edge05 = edges.Edge([0, 5], 1.625, 254) edge43 = edges.Edge([4, 3], 0.559, 775) edge32 = edges.Edge([3, 2], 1.220, 202) edge21 = edges.Edge([2, 1], 0.559, 775) edge_list = [edge45, edge14, edge10, edge05, edge43, edge32, edge21] # initialise Geometry problem_23_5 = geometry.Geometry(6, boom_list, edge_list, [232000, 258000], 1.0) problem_23_5.cells = [[edge43, edge32, edge21, edge14], [edge45, edge14, edge10, edge05]] # set boom areas to given values boom0.area = 1290 boom1.area = 1936 boom2.area = 645 boom3.area = 645 boom4.area = 1936 boom5.area = 1290 problem_23_5.get_areas() # calculate and verify geometrical properties problem_23_5.construct_geometry() problem_23_5.calc_centroid() problem_23_5.moment_inertia_Iyy() problem_23_5.moment_inertia_Izz() self.assertTrue(abs(problem_23_5.Izy < 1)) self.assertTrue(abs(problem_23_5.Izz * 10**(-6) - 214.3) < 1) for boom_element in boom_list: boom_element.calc_y_dist(problem_23_5) boom_element.calc_z_dist(problem_23_5) # calculate shear flows problem_23_5_section = DiscreteSection.DiscreteSection( neutral_axis, problem_23_5) problem_23_5_section.calc_shear_flow_q_B(0, 44500, edge14) # test open section shear flows self.assertTrue(abs(edge45.q_B) < 0.1 and abs(edge21.q_B) < 0.1) self.assertTrue(abs(edge43.q_B) < 0.1 and abs(edge10.q_B) < 0.1) self.assertTrue(abs(edge32.q_B - (-13.6)) < 1) self.assertTrue(abs(edge14.q_B) - 81.7 < 1) self.assertTrue(abs(edge05.q_B) - 34.07 < 1) # calculate closed section shear flows problem_23_5_section.calc_closed_section_pure_shear_flow_q_0(edge14) # test open section shear flows self.assertTrue( abs(edge45.q_0 - 4.12) < 1 and abs(edge05.q_0 - 4.12) < 1 and abs(edge10.q_0 - 4.12) < 1) self.assertTrue( abs(edge43.q_0 - (-5.74)) < 1 and abs(edge21.q_0 - (-5.74)) < 1 and abs(edge32.q_0 - (-5.74)) < 1) self.assertTrue(abs(edge14.q_0 - (-9.85)) < 1)
def create_nbr_info(dbmain, dbnbr): assert (dbmain) assert (dbnbr) assert (os.path.exists(dbmain)) assert (os.path.exists(dbnbr)) # open both db files conMain = sqlite3.connect(dbmain) conMain.row_factory = sqlite3.Row curMain = conMain.cursor() conNbr = sqlite3.connect(dbnbr) conNbr.row_factory = sqlite3.Row curNbr = conNbr.cursor() # construct all geometry objects from main database curMain.execute("SELECT * from Geometry") lgeom = [] geom_row = curMain.fetchone() while geom_row: lgeom.append(geometry.Geometry(rho=geom_row["Rho"],theta=geom_row["Theta"],phi=geom_row["Phi"],id=geom_row["Id"])) geom_row = curMain.fetchone() # all geometries constructed # for every geometry, first construct a list of all possbile nearby geometries for geom in lgeom: # obtain list of all geometries which are supposed to be near to this geometry rho = geom.rho theta = geom.theta phi = geom.phi curMain.execute('''select * from Geometry where (rho between ? and ?) and (theta between ? and ?) and (phi between ? and ?)''', (rho-4.5,rho+4.5,\ theta-misc.ToRad(4.5),theta+misc.ToRad(4.5),\ phi-misc.ToRad(4.5),phi+misc.ToRad(4.5))) lrow = curMain.fetchall() lnear_all = [ geometry.Geometry(rho=row["Rho"],theta=row["Theta"],phi=row["Phi"],id=row["Id"]) for row in lrow if row["Id"] != geom.id ] # now sort this list in increasing order of distance from given geometry lnear_all.sort(key=lambda g: geom.krmsd(g)) assert (lnear_all) # consider first thirty geometries into this list lgeom_near = lnear_all[0:min(10,len(lnear_all))] # now add first three geometries to Geometry table assert(len(lgeom_near) >=3) curMain.execute('UPDATE Geometry SET NNId = ?, NNId1 = ?, NNId2 = ? where Id=?',\ (lgeom_near[0].id,lgeom_near[1].id,lgeom_near[2].id,geom.id)) # add all 30 to NbrTable curNbr.executemany("INSERT INTO NbrTable VALUES (?,?,?,?)",\ [(geom.id,lgeom_near[i].id,i,geom.krmsd(lgeom_near[i])) for i in range(len(lgeom_near))]) # done, commit now conMain.commit() conNbr.commit() return
lgeom.extend(llgeom) lghsc = [] for g in lgeom: (r,t,p) = g.to_hsc() lghsc.append((r,t,p,"")) # now insert this into data base cur.executemany("""INSERT INTO Geometry (Rho,Theta,Phi,Tags) VALUES (?, ?, ?, ?)""", lghsc) # done successfully, now we test other things # this should be saved by now lgeom = [] for row in cur.execute('SELECT Rho, Theta, Phi, Id FROM Geometry'): lgeom.append(geometry.Geometry(row[0],row[1],row[2],id=row[3])) # add linear and pathlogical tags cur.executemany("""UPDATE Geometry SET Tags=? WHERE Id=?""",[(gengrid.geom_tags(g),g.id) for g in lgeom]) # print the geometries currently listed in data base lgeom = [] for row in cur.execute('SELECT Rho, Theta, Phi, Id FROM Geometry'): lgeom.append(geometry.Geometry(row[0],row[1],row[2],id=row[3])) f = open("geomdata.txt",'w') for g in lgeom: f.write(str(g)) f.write("\n") f.close()
def _decodeValue(json_obj, named_values): """Decodes an object previously encoded using the EE API v2 (DAG) format. This uses a provided scopre for ValueRef lookup and does not not allow the input to be a CompoundValue. Args: json_obj: The serialied object to decode. named_values: The objects that can be referenced by ValueRefs. Returns: The decoded object. """ # Check for primitive values. if (json_obj is None or isinstance(json_obj, (bool, numbers.Number, basestring))): return json_obj # Check for array values. if isinstance(json_obj, (list, tuple)): return [_decodeValue(element, named_values) for element in json_obj] # Ensure that we've got a proper object at this point. if not isinstance(json_obj, dict): raise ee_exception.EEException('Cannot decode object: ' + json_obj) # Check for explicitly typed values. type_name = json_obj['type'] if type_name == 'ValueRef': if json_obj['value'] in named_values: return named_values[json_obj['value']] else: raise ee_exception.EEException('Unknown ValueRef: ' + json_obj) elif type_name == 'ArgumentRef': var_name = json_obj['value'] if not isinstance(var_name, basestring): raise ee_exception.EEException('Invalid variable name: ' + var_name) return customfunction.CustomFunction._variable(None, var_name) # pylint: disable=protected-access elif type_name == 'Date': microseconds = json_obj['value'] if not isinstance(microseconds, numbers.Number): raise ee_exception.EEException('Invalid date value: ' + microseconds) return datetime.datetime.utcfromtimestamp(microseconds / 1e6) elif type_name == 'Bytes': result = encodable.Encodable() result.encode = lambda encoder: json_obj return result elif type_name == 'Invocation': if 'functionName' in json_obj: func = apifunction.ApiFunction.lookup(json_obj['functionName']) else: func = _decodeValue(json_obj['function'], named_values) args = dict((key, _decodeValue(value, named_values)) for (key, value) in json_obj['arguments'].iteritems()) if isinstance(func, function.Function): return func.apply(args) elif isinstance(func, computedobject.ComputedObject): # We have to allow ComputedObjects for cases where invocations # return a function, e.g. Image.parseExpression(). return computedobject.ComputedObject(func, args) else: raise ee_exception.EEException( 'Invalid function value: ' + json_obj['function']) elif type_name == 'Dictionary': return dict((key, _decodeValue(value, named_values)) for (key, value) in json_obj['value'].iteritems()) elif type_name == 'Function': body = _decodeValue(json_obj['body'], named_values) signature = { 'name': '', 'args': [{'name': arg_name, 'type': 'Object', 'optional': False} for arg_name in json_obj['argumentNames']], 'returns': 'Object' } return customfunction.CustomFunction(signature, lambda *args: body) elif type_name in ('Point', 'MultiPoint', 'LineString', 'MultiLineString', 'Polygon', 'MultiPolygon', 'LinearRing', 'GeometryCollection'): return geometry.Geometry(json_obj) elif type_name == 'CompoundValue': raise ee_exception.EEException('Nested CompoundValues are disallowed.') else: raise ee_exception.EEException('Unknown encoded object type: ' + type_name)
def makeGeometry(): gamma = 0.5 L = 1.0 box = geom.Box box11 = box(0, 0, (1 - gamma) / 2, (1 - gamma) / 2) box12 = box(0, (1 - gamma) / 2, (1 - gamma) / 2, (1 + gamma) / 2) box13 = box(0, (1 + gamma) / 2, (1 - gamma) / 2, 1) box21 = box((1 - gamma) / 2, 0, (1 + gamma) / 2, (1 - gamma) / 2) box22 = box((1 - gamma) / 2, (1 - gamma) / 2, (1 + gamma) / 2, (1 + gamma) / 2) box23 = box((1 - gamma) / 2, (1 + gamma) / 2, (1 + gamma) / 2, 1) box31 = box((1 + gamma) / 2, 0, 1, (1 - gamma) / 2) box32 = box((1 + gamma) / 2, (1 - gamma) / 2, 1, (1 + gamma) / 2) box33 = box((1 + gamma) / 2, (1 + gamma) / 2, 1, 1) boxNode11 = geom.BoxNode(box11, False) boxNode12 = geom.BoxNode(box12, False) boxNode13 = geom.BoxNode(box13, False) boxNode21 = geom.BoxNode(box21, False) boxNode22 = geom.BoxNode(box22, False) boxNode23 = geom.BoxNode(box23, False) boxNode31 = geom.BoxNode(box31, False) boxNode32 = geom.BoxNode(box32, False) boxNode33 = geom.BoxNode(box33, False) stack11 = geom.AxialStack('stack11') stack11.cell = boxNode11 stack11.regions = [makeReg1('111'), makeReg1('112'), makeReg1('113')] stack12 = geom.AxialStack('stack12') stack12.cell = boxNode12 stack12.regions = [makeReg1('121'), makeReg1('122'), makeReg1('123')] stack13 = geom.AxialStack('stack13') stack13.cell = boxNode13 stack13.regions = [makeReg1('131'), makeReg1('132'), makeReg1('133')] stack21 = geom.AxialStack('stack21') stack21.cell = boxNode21 stack21.regions = [makeReg1('211'), makeReg1('212'), makeReg1('213')] stack22 = geom.AxialStack('stack22') stack22.cell = boxNode22 stack22.regions = [makeReg1('221'), makeReg2('222'), makeReg1('223')] stack22.regions[1].source = 1 / (4 * pi) stack23 = geom.AxialStack('stack23') stack23.cell = boxNode23 stack23.regions = [makeReg1('231'), makeReg1('232'), makeReg1('233')] stack31 = geom.AxialStack('stack31') stack31.cell = boxNode31 stack31.regions = [makeReg1('311'), makeReg1('312'), makeReg1('313')] stack32 = geom.AxialStack('stack32') stack32.cell = boxNode32 stack32.regions = [makeReg1('321'), makeReg1('322'), makeReg1('323')] stack33 = geom.AxialStack('stack33') stack33.cell = boxNode33 stack33.regions = [makeReg1('331'), makeReg1('332'), makeReg1('333')] g = geom.Geometry(1, 1, L) g.addStack(stack11) g.addStack(stack12) g.addStack(stack13) g.addStack(stack21) g.addStack(stack22) g.addStack(stack23) g.addStack(stack31) g.addStack(stack32) g.addStack(stack33) g.z_bottom = array([0, L * (1 - gamma) / 2, L * (1 + gamma) / 2]) # Calculate true volume of each region for stack in g: area = stack.cell.surface.area() stack.regions[0].volume = area * L * (1 - gamma) / 2 stack.regions[1].volume = area * L * gamma stack.regions[2].volume = area * L * (1 - gamma) / 2 return g
positions = [0, 497, 652, 1024, 1469, 1986, 2566, 3186, 3838, 4521, 5234, 5979]; ant = geometry.Geometry("Test antenna") n = 0 for l,p in zip(lengths, positions): x = p y = l/2000.0 z = 0 start = (x,-y,z) end = (x,y,z) r = 0.005 if n == 0: ant.addElement(wires.Wire(start, end, 0.005, "Reflector")) elif n == 1: ant.addElement(wires.ExcitedWire(start, end, 0.005, "Dipole", 0.5)) else: