def AddFallingItems(sys): # Shared contact materials for falling objects sph_mat = chrono.ChMaterialSurfaceNSC() sph_mat.SetFriction(0.2) box_mat = chrono.ChMaterialSurfaceNSC() cyl_mat = chrono.ChMaterialSurfaceNSC() # Create falling rigid bodies (spheres and boxes etc.) for bi in range(29): msphereBody = chrono.ChBodyEasySphere(1.1, # radius size 1000, # density True, # visualization? True, # collision? sph_mat) # contact material msphereBody.SetPos(chrono.ChVectorD(-5 + chrono.ChRandom() * 10, 4 + bi * 0.05, -5 + chrono.ChRandom() * 10)) sys.Add(msphereBody) mtexture = chrono.ChTexture() mtexture.SetTextureFilename(chrono.GetChronoDataFile("textures/bluewhite.png")) msphereBody.AddAsset(mtexture) mboxBody = chrono.ChBodyEasyBox(1.5, 1.5, 1.5, # x,y,z size 100, # density True, # visualization? True, # collision? box_mat) # contact material mboxBody.SetPos(chrono.ChVectorD(-5 + chrono.ChRandom() * 10, 4 + bi * 0.05, -5 + chrono.ChRandom() * 10)) sys.Add(mboxBody) mtexturebox = chrono.ChTexture() mtexturebox.SetTextureFilename(chrono.GetChronoDataFile("textures/cubetexture_bluewhite.png")) mboxBody.AddAsset(mtexturebox) mcylBody = chrono.ChBodyEasyCylinder(0.75, 0.5, # radius, height 100, # density True, # visualization? True, # collision? cyl_mat) # contact material mcylBody.SetPos(chrono.ChVectorD(-5 + chrono.ChRandom() * 10, 4 + bi * 0.05, -5 + chrono.ChRandom() * 10)) sys.Add(mcylBody) # optional, attach a texture for better visualization mtexturecyl = chrono.ChTexture() mtexturecyl.SetTextureFilename(chrono.GetChronoDataFile("textures/pinkwhite.png")) mcylBody.AddAsset(mtexturecyl)
def __init__(self, die_file='die.obj'): self.container_width = 200 self.container_length = 200 self.with_walls = True self.wall_height = 50 self.dice_num = 1 self.polygon = None self.normal_rotation_offset = chrono.Q_from_AngAxis(0, chrono.VECT_Z) if type(die_file) is Polygon: self.polygon = die_file self.die_file = self.polygon.get_chrono_mesh() angle, axis = self.polygon.align_normal_to_vector(0, [0, 1, 0], only_info=True) self.normal_rotation_offset = chrono.Q_from_AngAxis( angle, chrono.ChVectorD(*axis)) else: self.die_file = die_file self.cut_off = 0.0001 # Contact material for container self.ground_mat = chrono.ChMaterialSurfaceNSC() self.ground_mat.SetFriction(0.8) # Shared contact materials for falling objects self.dice_mat = chrono.ChMaterialSurfaceNSC() self.dice_mat.SetFriction(0.5) # initialise start parameters self.dice_position = [0, 5, 0] self.dice_speed = [0, 0, 0] self.dice_rotation = chrono.Q_from_AngAxis(30 * chrono.CH_C_DEG_TO_RAD, chrono.VECT_Z) self.dice_ang_speed = [0, 0, 0] self.past_start_params = [] self.run_results = [] # initialise other variables self.system = None self.dice = list() # init system self.initialise_system()
my_bus.SetTireType(tire_model) my_bus.SetTireStepSize(tire_step_size) my_bus.Initialize() tire_vis_type = veh.VisualizationType_MESH # : VisualizationType::PRIMITIVES my_bus.SetChassisVisualizationType(chassis_vis_type) my_bus.SetSuspensionVisualizationType(suspension_vis_type) my_bus.SetSteeringVisualizationType(steering_vis_type) my_bus.SetWheelVisualizationType(wheel_vis_type) my_bus.SetTireVisualizationType(tire_vis_type) # Create the terrain terrain = veh.RigidTerrain(my_bus.GetSystem()) if (contact_method == chrono.ChContactMethod_NSC): patch_mat = chrono.ChMaterialSurfaceNSC() patch_mat.SetFriction(0.9) patch_mat.SetRestitution(0.01) elif (contact_method == chrono.ChContactMethod_SMC): patch_mat = chrono.ChMaterialSurfaceSMC() patch_mat.SetFriction(0.9) patch_mat.SetRestitution(0.01) patch_mat.SetYoungModulus(2e7) patch = terrain.AddPatch(patch_mat, chrono.ChVectorD(0, 0, 0), chrono.ChVectorD(0, 0, 1), terrainLength, terrainWidth) patch.SetTexture(veh.GetDataFile("terrain/textures/tile4.jpg"), 200, 200) patch.SetColor(chrono.ChColor(0.8, 0.8, 0.5)) terrain.Initialize() # Create the vehicle Irrlicht interface
# # Create the simulation system and add items # # Change use_NSC to specify different contact method use_NSC = 0 ball_radius = 0.5 obst_radius = 2.0 obst_center = chrono.ChVectorD(2.9, 0, 2.9) obstacle = MyObstacle(obst_radius, obst_center) # Create the system and the various contact materials if use_NSC: sys = chrono.ChSystemNSC() g_mat = chrono.ChMaterialSurfaceNSC() g_mat.SetRestitution(0.9) g_mat.SetFriction(0.4) b_mat = chrono.ChMaterialSurfaceNSC() b_mat.SetRestitution(0.9) b_mat.SetFriction(0.5) o_mat = chrono.ChMaterialSurfaceNSC() o_mat.SetRestitution(0.9) o_mat.SetFriction(0.4) ground_mat = g_mat ball_mat = b_mat obst_mat = o_mat time_step = 1e-3 frame_skip = 10
def setSurfaceMaterial(self, friction, damping, compliance, complianceT): self.surface = chrono.ChMaterialSurfaceNSC() self.surface.SetFriction(friction) self.surface.SetDampingF(damping) self.surface.SetCompliance (compliance) self.surface.SetComplianceT(complianceT)
# Set the default outward/inward shape margins for collision detection, # this is epecially important for very large or very small objects. chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001) chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.001) # Maybe you want to change some settings for the solver. For example you # might want to use SetMaxItersSolverSpeed to set the number of iterations # per timestep, etc. #my_system.SetSolverType(chrono.ChSolver.Type_BARZILAIBORWEIN) # precise, more slow my_system.SetMaxItersSolverSpeed(70) # Create a contact material (surface property)to share between all objects. # The rolling and spinning parameters are optional - if enabled they double # the computational time. brick_material = chrono.ChMaterialSurfaceNSC() brick_material.SetFriction(0.5) brick_material.SetDampingF(0.2) brick_material.SetCompliance(0.0000001) brick_material.SetComplianceT(0.0000001) # brick_material.SetRollingFriction(rollfrict_param) # brick_material.SetSpinningFriction(0) # brick_material.SetComplianceRolling(0.0000001) # brick_material.SetComplianceSpinning(0.0000001) # Create the set of bricks in a vertical stack, along Y axis nbricks_on_x = 4 nbricks_on_y = 6 size_brick_x = 0.15
def main(): # ----------------- # Create the system # ----------------- mphysicalSystem = chrono.ChSystemNSC() mphysicalSystem.Set_G_acc(chrono.ChVectorD(0, 0, -9.81)) # ---------------------------------------- # add a floor, box and sphere to the scene # ---------------------------------------- phys_mat = chrono.ChMaterialSurfaceNSC() phys_mat.SetFriction(0.5) phys_mat.SetDampingF(0.00000) phys_mat.SetCompliance(1e-9) phys_mat.SetComplianceT(1e-9) floor = chrono.ChBodyEasyBox(10, 10, 1, 1000, True, True, phys_mat) floor.SetPos(chrono.ChVectorD(0, 0, -1)) floor.SetBodyFixed(True) mphysicalSystem.Add(floor) box = chrono.ChBodyEasyBox(1, 1, 1, 1000, True, True, phys_mat) box.SetPos(chrono.ChVectorD(0, 0, 5)) box.SetRot(chrono.Q_from_AngAxis(.2, chrono.ChVectorD(1, 0, 0))) mphysicalSystem.Add(box) sphere = chrono.ChBodyEasySphere(.5, 1000, True, True, phys_mat) sphere.SetPos(chrono.ChVectorD(0, 0, 8)) sphere.SetRot(chrono.Q_from_AngAxis(.2, chrono.ChVectorD(1, 0, 0))) mphysicalSystem.Add(sphere) sphere_asset = sphere.GetAssets()[0] visual_asset = chrono.CastToChVisualization(sphere_asset) vis_mat = chrono.ChVisualMaterial() vis_mat.SetAmbientColor(chrono.ChVectorF(0, 0, 0)) vis_mat.SetDiffuseColor(chrono.ChVectorF(.2, .2, .9)) vis_mat.SetSpecularColor(chrono.ChVectorF(.9, .9, .9)) visual_asset.material_list.append(vis_mat) # ----------------------- # Create a sensor manager # ----------------------- manager = sens.ChSensorManager(mphysicalSystem) manager.scene.AddPointLight(chrono.ChVectorF(100, 100, 100), chrono.ChVectorF(1, 1, 1), 1000.0) manager.scene.AddPointLight(chrono.ChVectorF(-100, -100, 100), chrono.ChVectorF(1, 1, 1), 1000.0) # ------------------------------------------------ # Create a camera and add it to the sensor manager # ------------------------------------------------ offset_pose = chrono.ChFrameD( chrono.ChVectorD(-8, 0, 1), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))) cam = sens.ChCameraSensor( floor, # body camera is attached to cam_update_rate, # update rate in Hz offset_pose, # offset pose image_width, # number of horizontal samples image_height, # number of vertical channels cam_fov # vertical field of view ) cam.SetName("Camera Sensor") cam.SetLag(cam_lag) cam.SetCollectionWindow(cam_collection_time) # ------------------------------------------------------------------ # Create a filter graph for post-processing the data from the camera # ------------------------------------------------------------------ # Visualizes the image if vis: cam.PushFilter( sens.ChFilterVisualize(image_width, image_height, "RGB Image")) # Save the current image to a png file at the specified path if (save): cam.PushFilter(sens.ChFilterSave(out_dir + "/rgb/")) # Provides the host access to this RGBA8 buffer cam.PushFilter(sens.ChFilterRGBA8Access()) # Filter the sensor to grayscale cam.PushFilter(sens.ChFilterGrayscale()) # Render the buffer again to see the new grayscaled image if (vis): cam.PushFilter( sens.ChFilterVisualize(int(image_width / 2), int(image_height / 2), "Grayscale Image")) # Save the grayscaled image at the specified path if (save): cam.PushFilter(sens.ChFilterSave(out_dir + "/gray/")) # Access the grayscaled buffer as R8 pixels cam.PushFilter(sens.ChFilterR8Access()) # Add a camera to a sensor manager manager.AddSensor(cam) # ------------------------------------------------ # Create a lidar and add it to the sensor manager # ------------------------------------------------ offset_pose = chrono.ChFrameD( chrono.ChVectorD(-8, 0, 1), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))) lidar = sens.ChLidarSensor( floor, # body lidar is attached to lidar_update_rate, # scanning rate in Hz offset_pose, # offset pose horizontal_samples, # number of horizontal samples vertical_samples, # number of vertical channels horizontal_fov, # horizontal field of view max_vert_angle, min_vert_angle, # vertical field of view 100 #max lidar range ) lidar.SetName("Lidar Sensor") lidar.SetLag(lidar_lag) lidar.SetCollectionWindow(lidar_collection_time) # ----------------------------------------------------------------- # Create a filter graph for post-processing the data from the lidar # ----------------------------------------------------------------- if vis: # Randers the raw lidar data lidar.PushFilter( sens.ChFilterVisualize(horizontal_samples, vertical_samples, "Raw Lidar Depth Data")) # Provides the host access to the Depth,Intensity data lidar.PushFilter(sens.ChFilterDIAccess()) # Convert Depth,Intensity data to XYZI point cloud data lidar.PushFilter(sens.ChFilterPCfromDepth()) if vis: # Visualize the point cloud lidar.PushFilter( sens.ChFilterVisualizePointCloud(640, 480, 1.0, "Lidar Point Cloud")) # Provides the host access to the XYZI data lidar.PushFilter(sens.ChFilterXYZIAccess()) # Add the lidar to the sensor manager manager.AddSensor(lidar) # ---------------------------------------------- # Create an IMU sensor and add it to the manager # ---------------------------------------------- offset_pose = chrono.ChFrameD( chrono.ChVectorD(-8, 0, 1), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))) imu = sens.ChIMUSensor( box, # body imu is attached to imu_update_rate, # update rate in Hz offset_pose, # offset pose imu_noise_none, # noise model ) imu.SetName("IMU Sensor") imu.SetLag(imu_lag) imu.SetCollectionWindow(imu_collection_time) # Provides the host access to the imu data imu.PushFilter(sens.ChFilterIMUAccess()) # Add the imu to the sensor manager manager.AddSensor(imu) # ---------------------------------------------- # Create an GPS sensor and add it to the manager # ---------------------------------------------- offset_pose = chrono.ChFrameD( chrono.ChVectorD(-8, 0, 1), chrono.Q_from_AngAxis(0, chrono.ChVectorD(0, 1, 0))) gps = sens.ChGPSSensor( box, # body imu is attached to gps_update_rate, # update rate in Hz offset_pose, # offset pose gps_reference, gps_noise_none # noise model ) gps.SetName("GPS Sensor") gps.SetLag(gps_lag) gps.SetCollectionWindow(gps_collection_time) # Provides the host access to the gps data gps.PushFilter(sens.ChFilterGPSAccess()) # Add the gps to the sensor manager manager.AddSensor(gps) # --------------- # Simulate system # --------------- t1 = time.time() ch_time = 0 while (ch_time < end_time): # Access the sensor data camera_data_RGBA8 = cam.GetMostRecentRGBA8Buffer() camera_data_R8 = cam.GetMostRecentR8Buffer() lidar_data_DI = lidar.GetMostRecentDIBuffer() lidar_data_XYZI = lidar.GetMostRecentXYZIBuffer() gps_data = gps.GetMostRecentGPSBuffer() imu_data = imu.GetMostRecentIMUBuffer() # Check data is present # If so, print out the max value if camera_data_RGBA8.HasData(): print("Camera RGBA8:", camera_data_RGBA8.GetRGBA8Data().shape, "max:", np.max(camera_data_RGBA8.GetRGBA8Data())) if camera_data_R8.HasData(): print("Camera R8:", camera_data_R8.GetChar8Data().shape, "max:", np.max(camera_data_R8.GetChar8Data())) if lidar_data_DI.HasData(): print("Lidar DI:", lidar_data_DI.GetDIData().shape, "max:", np.max(lidar_data_DI.GetDIData())) if lidar_data_XYZI.HasData(): print("Lidar XYZI:", lidar_data_XYZI.GetXYZIData().shape, "max:", np.max(lidar_data_XYZI.GetXYZIData())) if gps_data.HasData(): print("GPS:", gps_data.GetGPSData().shape, "max:", np.max(gps_data.GetGPSData())) if imu_data.HasData(): print("IMU:", imu_data.GetIMUData().shape, "max:", np.max(imu_data.GetIMUData())) # Update sensor manager # Will render/save/filter automatically manager.Update() # Perform step of dynamics mphysicalSystem.DoStepDynamics(step_size) # Get the current time of the simulation ch_time = mphysicalSystem.GetChTime() print("Sim time:", end_time, "Wall time:", time.time() - t1)
def AddContainer(sys): # Contact material for container ground_mat = chrono.ChMaterialSurfaceNSC() # Create the five walls of the rectangular container, using fixed rigid bodies of 'box' type floorBody = chrono.ChBodyEasyBox(20, 1, 20, 1000, True, True, ground_mat) floorBody.SetPos(chrono.ChVectorD(0, -5, 0)) floorBody.SetBodyFixed(True) sys.Add(floorBody) wallBody1 = chrono.ChBodyEasyBox(1, 10, 20.99, 1000, True, True, ground_mat) wallBody1.SetPos(chrono.ChVectorD(-10, 0, 0)) wallBody1.SetBodyFixed(True) sys.Add(wallBody1) wallBody2 = chrono.ChBodyEasyBox(1, 10, 20.99, 1000, True, True, ground_mat) wallBody2.SetPos(chrono.ChVectorD(10, 0, 0)) wallBody2.SetBodyFixed(True) sys.Add(wallBody2) wallBody3 = chrono.ChBodyEasyBox(20.99, 10, 1, 1000, False, True, ground_mat) wallBody3.SetPos(chrono.ChVectorD(0, 0, -10)) wallBody3.SetBodyFixed(True) sys.Add(wallBody3) wallBody4 = chrono.ChBodyEasyBox(20.99, 10, 1, 1000, True, True, ground_mat) wallBody4.SetPos(chrono.ChVectorD(0, 0, 10)) wallBody4.SetBodyFixed(True) sys.Add(wallBody4) # optional, attach textures for better visualization mtexturewall = chrono.ChTexture() mtexturewall.SetTextureFilename(chrono.GetChronoDataFile("textures/concrete.jpg")) wallBody1.AddAsset(mtexturewall) # note: most assets can be shared wallBody2.AddAsset(mtexturewall) wallBody3.AddAsset(mtexturewall) wallBody4.AddAsset(mtexturewall) floorBody.AddAsset(mtexturewall) # Add the rotating mixer mixer_mat = chrono.ChMaterialSurfaceNSC() mixer_mat.SetFriction(0.4) rotatingBody = chrono.ChBodyEasyBox(10, 5, 1, # x,y,z size 4000, # density True, # visualization? True, # collision? mixer_mat) # contact material rotatingBody.SetPos(chrono.ChVectorD(0, -1.6, 0)) sys.Add(rotatingBody) # .. a motor between mixer and truss my_motor = chrono.ChLinkMotorRotationSpeed() my_motor.Initialize(rotatingBody, floorBody, chrono.ChFrameD(chrono.ChVectorD(0, 0, 0), chrono.Q_from_AngAxis(chrono.CH_C_PI_2, chrono.VECT_X))) mfun = chrono.ChFunction_Const(chrono.CH_C_PI / 4.0) # speed 45 deg/s my_motor.SetSpeedFunction(mfun) sys.AddLink(my_motor) # NOTE: Instead of creating five separate 'box' bodies to make # the walls of the container, you could have used a single body # made of five box shapes, which build a single collision description, # as in the alternative approach: """ # create a plain ChBody (no colliding shape nor visualization mesh is used yet) mrigidBody = chrono.ChBody() # set as fixed body, and turn collision ON, otherwise no collide by default mrigidBody.SetBodyFixed(True) mrigidBody.SetCollide(True) # Clear model. The colliding shape description MUST be between ClearModel() .. BuildModel() pair. mrigidBody.GetCollisionModel().ClearModel() # Describe the (invisible) colliding shape by adding five boxes (the walls and floor) mrigidBody.GetCollisionModel().AddBox(ground_mat, 20, 1, 20, chrono.ChVectorD(0, -10, 0)) mrigidBody.GetCollisionModel().AddBox(ground_mat, 1, 40, 20, chrono.ChVectorD(-11, 0, 0)) mrigidBody.GetCollisionModel().AddBox(ground_mat, 1, 40, 20, chrono.ChVectorD(11, 0, 0)) mrigidBody.GetCollisionModel().AddBox(ground_mat, 20, 40, 1, chrono.ChVectorD(0, 0, -11)) mrigidBody.GetCollisionModel().AddBox(ground_mat, 20, 40, 1, chrono.ChVectorD(0, 0, 11)) # Complete the description of collision shape. mrigidBody.GetCollisionModel().BuildModel() # Attach some visualization shapes if needed: vshape = chrono.ChBoxShape() vshape.GetBoxGeometry().SetLengths(chrono.ChVectorD(20, 1, 20)) vshape.GetBoxGeometry().Pos = chrono.ChVectorD(0, -5, 0) this.AddAsset(vshape) # etc. for other 4 box shapes.. """ return rotatingBody
chvecs.append(npvec_to_chvec(npvec)) return chvecs dodeca = create_dodecahedron() dodeca.extend_side(0, 0.1) # dodeca.extend_side(4, 1.1) # dodeca.align_normal_to_vector(4, [0, 0, 1]) cut_off = 0.00001 run_visible = True system = chrono.ChSystemNSC() system.SetSolverType(chrono.ChSolver.Type_BARZILAIBORWEIN) # Contact material for container ground_mat = chrono.ChMaterialSurfaceNSC() ground_mat.SetFriction(0.8) # Shared contact materials for falling objects dice_mat = chrono.ChMaterialSurfaceNSC() dice_mat.SetFriction(0.5) # Create the five walls of the rectangular container, using fixed rigid bodies of 'box' type floor_body = chrono.ChBodyEasyBox(210, 1, 210, 1000, True, True, ground_mat) floor_body.SetPos(chrono.ChVectorD(0, 0, 0)) floor_body.SetBodyFixed(True) system.Add(floor_body) die_file = dodeca.get_chrono_mesh() die = chrono.ChBodyEasyMesh( die_file, # obj filename
mysystem = chrono.ChSystemNSC() # Set the global collision margins. This is expecially important for very large or # very small objects. Set this before creating shapes. Not before creating mysystem. chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001); chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.001); # --------------------------------------------------------------------- # # Create the simulation system and add items # # Create a contact material (with default properties, shared by all collision shapes) contact_material = chrono.ChMaterialSurfaceNSC() # Create a floor mfloor = chrono.ChBodyEasyBox(3, 0.2, 3, 1000,True,True, contact_material) mfloor.SetBodyFixed(True) mysystem.Add(mfloor) # Now we will create a falling object whose shape is defined by a .obj mesh. # # NOTE: collision detection with generic concave meshes is slower and less # robust than any other options for collision shapes, so use it if defining # collision shapes via primitives like spheres boxes cylinders or their # clusters is too complex. # # NOTE: the mesh shape is a .obj file in Wavefront file format,
# Create the simulation system and add items # mphysicalSystem = chrono.ChSystemNSC() # Create all the rigid bodies. mradius = 0.5 density = 1000 # Create a texture asset. It can be shared between bodies. textureasset = chrono.ChTexture( chrono.GetChronoDataFile("textures/bluewhite.png")) # Create some spheres that roll horizontally, with increasing rolling friction values for bi in range(10): mat = chrono.ChMaterialSurfaceNSC() mat.SetFriction(0.4) mat.SetRollingFriction((float(bi) / 10.) * 0.05) msphereBody = chrono.ChBodyEasySphere( mradius, # radius size 1000, # density True, # visualization? True, # collision? mat) # contact material # Set some properties msphereBody.SetPos( chrono.ChVectorD(-7, mradius - 0.5, -5 + bi * mradius * 2.5)) msphereBody.AddAsset(textureasset) # assets can be shared
def run_sim(traits, trial_num, gen_num, difficulty_level): my_system = chrono.ChSystemNSC() # Set the default outward/inward shape margins for collision detection chrono.ChCollisionModel.SetDefaultSuggestedEnvelope(0.001) chrono.ChCollisionModel.SetDefaultSuggestedMargin(0.001) # Sets simulation precision my_system.SetMaxItersSolverSpeed(70) # Create a contact material (surface property)to share between all objects. rollfrict_param = 0.5 / 10.0 * 0.05 brick_material = chrono.ChMaterialSurfaceNSC() brick_material.SetFriction(0.5) brick_material.SetDampingF(0.2) brick_material.SetCompliance(0.0000001) brick_material.SetComplianceT(0.0000001) brick_material.SetRollingFriction(rollfrict_param) brick_material.SetSpinningFriction(0.00000001) brick_material.SetComplianceRolling(0.0000001) brick_material.SetComplianceSpinning(0.0000001) # Create the set of bricks in a vertical stack, along Y axis block_bodies = [] # visualizes bodies block_shapes = [] # geometry purposes current_y = 0 for block_index in range(0, 4): size_brick_x = traits[block_index][0] size_brick_z = traits[block_index][1] size_brick_y = traits[block_index][2] if size_brick_y < settings.MIN_DIMENSIONS_THRESHOLD or size_brick_x < settings.MIN_DIMENSIONS_THRESHOLD or size_brick_z < settings.MIN_DIMENSIONS_THRESHOLD: return [-50, traits] mass_brick = settings.BLOCK_MASS inertia_brick_xx = 1 / 12 * mass_brick * (pow(size_brick_z, 2) + pow(size_brick_y, 2)) inertia_brick_yy = 1 / 12 * mass_brick * (pow(size_brick_x, 2) + pow(size_brick_z, 2)) inertia_brick_zz = 1 / 12 * mass_brick * (pow(size_brick_x, 2) + pow(size_brick_y, 2)) body_brick = chrono.ChBody() body_brick.SetPos(chrono.ChVectorD(0, current_y + 0.5 * size_brick_y, 0)) # set initial position current_y += size_brick_y # set tower block positions # setting mass properties body_brick.SetMass(mass_brick) body_brick.SetInertiaXX(chrono.ChVectorD(inertia_brick_xx, inertia_brick_yy, inertia_brick_zz)) # set collision surface properties body_brick.SetMaterialSurface(brick_material) # Collision shape body_brick.GetCollisionModel().ClearModel() body_brick.GetCollisionModel().AddBox(size_brick_x / 2, size_brick_y / 2, size_brick_z / 2) # must set half sizes body_brick.GetCollisionModel().BuildModel() body_brick.SetCollide(True) # Visualization shape, for rendering animation body_brick_shape = chrono.ChBoxShape() body_brick_shape.GetBoxGeometry().Size = chrono.ChVectorD(size_brick_x / 2, size_brick_y / 2, size_brick_z / 2) if block_index % 2 == 0: body_brick_shape.SetColor(chrono.ChColor(0.65, 0.65, 0.6)) # set gray color only for odd bricks body_brick.GetAssets().push_back(body_brick_shape) my_system.Add(body_brick) block_bodies.append(body_brick) block_shapes.append(body_brick_shape); # Create the room floor body_floor = chrono.ChBody() body_floor.SetBodyFixed(True) body_floor.SetPos(chrono.ChVectorD(0, -2, 0)) body_floor.SetMaterialSurface(brick_material) # Floor's collision shape body_floor.GetCollisionModel().ClearModel() body_floor.GetCollisionModel().AddBox(3, 1, 3) # hemi sizes default: 3,1,3 body_floor.GetCollisionModel().BuildModel() body_floor.SetCollide(True) # Visualization shape body_floor_shape = chrono.ChBoxShape() body_floor_shape.GetBoxGeometry().Size = chrono.ChVectorD(3, 1, 3) body_floor.GetAssets().push_back(body_floor_shape) body_floor_texture = chrono.ChTexture() # body_floor_texture.SetTextureFilename(chrono.GetChronoDataPath() + 'concrete.jpg') body_floor.GetAssets().push_back(body_floor_texture) my_system.Add(body_floor) # Create the shaking table, as a box size_table_x = 1 size_table_y = 0.2 size_table_z = 1 body_table = chrono.ChBody() body_table.SetPos(chrono.ChVectorD(0, -size_table_y / 2, 0)) body_table.SetMaterialSurface(brick_material) # Collision shape body_table.GetCollisionModel().ClearModel() body_table.GetCollisionModel().AddBox(size_table_x / 2, size_table_y / 2, size_table_z / 2) # hemi sizes body_table.GetCollisionModel().BuildModel() body_table.SetCollide(True) # Visualization shape body_table_shape = chrono.ChBoxShape() body_table_shape.GetBoxGeometry().Size = chrono.ChVectorD(size_table_x / 2, size_table_y / 2, size_table_z / 2) body_table_shape.SetColor(chrono.ChColor(0.4, 0.4, 0.5)) body_table.GetAssets().push_back(body_table_shape) body_table_texture = chrono.ChTexture() # body_table_texture.SetTextureFilename(chrono.GetChronoDataPath() + 'concrete.jpg') body_table.GetAssets().push_back(body_table_texture) my_system.Add(body_table) # Makes the table shake link_shaker = chrono.ChLinkLockLock() # link_shaker.SetMotion_X() link_shaker.Initialize(body_table, body_floor, chrono.CSYSNORM) my_system.Add(link_shaker) # ..create the function for imposed y vertical motion, etc. mfunY = chrono.ChFunction_Sine(0, settings.TABLE_FREQ_Y, settings.TABLE_AMP_Y) # phase, frequency, amplitude # ..create the function for imposed z horizontal motion, etc. mfunZ = chrono.ChFunction_Sine(0, settings.TABLE_FREQ_Z, settings.TABLE_AMP_Z) # phase, frequency, amplitude # ..create the function for imposed x horizontal motion, etc. mfunX = chrono.ChFunction_Sine(2, 0, 0) # phase, frequency, amplitude print("Sim env_level " + str(difficulty_level)) if difficulty_level == settings.SHAKE_IN_X_AXIS_LEVEL: mfunX = chrono.ChFunction_Sine(2, settings.TABLE_FREQ_X, settings.TABLE_AMP_X) # phase, frequency, amplitude elif difficulty_level >= settings.SHAKE_IN_X_AND_Z_AXIS_LEVEL: increment = 0.25 * difficulty_level mfunX = chrono.ChFunction_Sine(2, settings.TABLE_FREQ_X + increment, settings.TABLE_AMP_X) # phase, frequency, amplitude mfunZ = chrono.ChFunction_Sine(0, settings.TABLE_FREQ_Z + increment, settings.TABLE_AMP_Z) # phase, frequency, amplitude link_shaker.SetMotion_Y(mfunY) link_shaker.SetMotion_Z(mfunZ) link_shaker.SetMotion_X(mfunX) # --------------------------------------------------------------------- # # Create an Irrlicht application to visualize the system window_name = "Tower Trial: " + str(trial_num) + " Gen: " + str(gen_num) if trial_num == -1: window_name = "Initializing Population..." app = chronoirr.ChIrrApp(my_system, window_name, chronoirr.dimension2du(settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)) app.AddTypicalSky() app.AddTypicalLogo(chrono.GetChronoDataPath() + 'logo_pychrono_alpha.png') app.AddTypicalCamera(chronoirr.vector3df(settings.CAMERA_X, settings.CAMERA_Y, settings.CAMERA_Z)) app.AddLightWithShadow(chronoirr.vector3df(2, 4, 2), # point chronoirr.vector3df(0, 0, 0), # aimpoint 9, # radius (power) 1, 9, # near, far 30) # Committing visualization app.AssetBindAll() app.AssetUpdateAll(); app.AddShadowAll(); # --------------------------------------------------------------------- # # Run the simulation. This is where all of the constraints are set # app.SetTimestep(settings.SPEED) app.SetTryRealtime(True) app.GetDevice().run() fitness = 0 brick1_init = block_bodies[0].GetPos().y brick2_init = block_bodies[1].GetPos().y brick3_init = block_bodies[2].GetPos().y brick4_init = block_bodies[3].GetPos().y # Highest while True: brick1_curr_height = block_bodies[0].GetPos().y brick2_curr_height = block_bodies[1].GetPos().y brick3_curr_height = block_bodies[2].GetPos().y brick4_curr_height = block_bodies[3].GetPos().y # Highest # Break conditions if my_system.GetChTime() > settings.SIMULATION_RUNTIME: break if my_system.GetChTime() > settings.SIMULATION_RUNTIME / 2: mfunX = chrono.ChFunction_Sine(2, 0, 0) mfunZ = chrono.ChFunction_Sine(2, 0, 0) link_shaker.SetMotion_Z(mfunZ) link_shaker.SetMotion_X(mfunX) # If the blocks fall out of line if brick1_init - brick1_curr_height > settings.CANCEL_SIM_THRESHOLD or \ brick2_init - brick2_curr_height > settings.CANCEL_SIM_THRESHOLD or \ brick3_init - brick3_curr_height > settings.CANCEL_SIM_THRESHOLD or \ brick4_init - brick4_curr_height > settings.CANCEL_SIM_THRESHOLD: break # Record fitness every 1/1000 of the runtime if 0.01 > my_system.GetChTime() % ((1 / 1000) * settings.SIMULATION_RUNTIME) > 0: if settings.FITNESS_FUNCTION == settings.Fitness.SumLengths: # Sum of size_y fitness += block_shapes[0].GetBoxGeometry().GetLengths().y + \ block_shapes[1].GetBoxGeometry().GetLengths().y + \ block_shapes[2].GetBoxGeometry().GetLengths().y + \ block_shapes[3].GetBoxGeometry().GetLengths().y elif settings.FITNESS_FUNCTION == settings.Fitness.MaxPosition: # Max of y positions fitness += max(block_bodies[0].GetPos().y, block_bodies[1].GetPos().y, block_bodies[2].GetPos().y, block_bodies[3].GetPos().y) elif settings.FITNESS_FUNCTION == settings.Fitness.MaxPositionSumLengths: # Max * sum of sizes fitness += max(block_bodies[0].GetPos().y, block_bodies[1].GetPos().y, block_bodies[2].GetPos().y, block_bodies[3].GetPos().y) * \ block_shapes[0].GetBoxGeometry().GetLengths().y + \ block_shapes[1].GetBoxGeometry().GetLengths().y + \ block_shapes[2].GetBoxGeometry().GetLengths().y + \ block_shapes[3].GetBoxGeometry().GetLengths().y app.BeginScene() app.DrawAll() for substep in range(0, 5): app.DoStep() app.EndScene() app.GetDevice().closeDevice() print("Fitness: " + str(fitness) + " Gen: " + str(gen_num)) return [fitness, traits]