Project Chrono

Joyjin·2024년 6월 3일

공식 홈페이지

uname -m -x86_64 확인
공식 사이트에서 콘다 다운로드
"Python 3.11
64-Bit (x86) Installer (997.2M)"
cd Downloads
bash Anaconda3-2024.02-1-Linux-x86_64.sh

bashrc 추가
source ~/anaconda3/etc/profile.d/conda.sh

conda create -n myenv python=3.9
conda activate myenv

pychrono-9.0.0-py39_4853.tar.bz2
선택
(release: 최신 / main: 안전성)

데모파일 위치
cd anaconda3/envs/chrono/lib/python3.9/site-packages/pychrono

  • 실행
    Anaconda Prompt

    conda activate chrono

    DEMO file repository로 이동
    cd C:\Users\user\anaconda3\pkgs\pychrono-8.0.0-py39_3631\Lib\site-packages\pychrono\demos

Python codes

Tracked vehicle inputs & outputs


# Main driver function for the HMMWV full model.
#
# The vehicle reference frame has Z up, X towards the front of the vehicle, and
# Y pointing to the left.
#
# =============================================================================

import pychrono as chrono
import pychrono.vehicle as veh
import pychrono.irrlicht as irr
import os
import math as m

# M113
# print("\n")
# print(dir(veh.M113))

def get_driver_inputs(time):
    # Example dynamic inputs based on time
    throttle = 1.0
    steering = 0.5 * m.sin(time*2)
    braking = 0.0

    return throttle, steering, braking

# Quaternion to Roll, Pitch, Yaw
def euler_from_quaternion(w, x, y, z):
    t0 = +2.0 * (w * x + y * z)
    t1 = +1.0 - 2.0 * (x * x + y * y)
    roll = m.atan2(t0, t1)*180/m.pi 

    t2 = +2.0 * (w * y - z * x)
    t2 = +1.0 if t2 > +1.0 else t2
    t2 = -1.0 if t2 < -1.0 else t2
    pitch = m.asin(t2)*180/m.pi

    t3 = +2.0 * (w * z + x * y)
    t4 = +1.0 - 2.0 * (y * y + z * z)
    yaw = m.atan2(t3, t4)*180/m.pi

    return roll, pitch, yaw # in degrees


def main():
    #print("Copyright (c) 2017 projectchrono.org\nChrono version: ", CHRONO_VERSION , "\n\n")

    #  Create the M113 vehicle
    # ------------------------

    m113 = veh.M113()
    m113.SetContactMethod(chrono.ChContactMethod_SMC)
    m113.SetTrackShoeType(veh.TrackShoeType_SINGLE_PIN)
    m113.SetDrivelineType(veh.DrivelineTypeTV_BDS)
    m113.SetEngineType(veh.EngineModelType_SHAFTS)
    m113.SetTransmissionType(veh.TransmissionModelType_SHAFTS)
    m113.SetBrakeType(veh.BrakeType_SIMPLE)

    m113.SetInitPosition(chrono.ChCoordsysD(initLoc, initRot))
    m113.Initialize()

    m113.SetChassisVisualizationType(veh.VisualizationType_PRIMITIVES)
    m113.SetSprocketVisualizationType(veh.VisualizationType_MESH);
    m113.SetIdlerVisualizationType(veh.VisualizationType_MESH);
    m113.SetIdlerWheelVisualizationType(veh.VisualizationType_MESH);
    m113.SetSuspensionVisualizationType(veh.VisualizationType_MESH);
    m113.SetRoadWheelVisualizationType(veh.VisualizationType_MESH);
    m113.SetTrackShoeVisualizationType(veh.VisualizationType_MESH);

    # Create the terrain
    # ------------------

    terrain = veh.RigidTerrain(m113.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.CSYSNORM, 
                             terrainLength, terrainWidth)
    patch.SetTexture(veh.GetDataFile("terrain/textures/tile4.jpg"), 200, 200)
    patch.SetColor(chrono.ChColor(0.5, 0.8, 0.5))
    terrain.Initialize()

    # Create the vehicle Irrlicht interface
    # -------------------------------------

    vis = veh.ChTrackedVehicleVisualSystemIrrlicht()
    vis.SetWindowTitle('M113')
    vis.SetWindowSize(1500, 800)
    vis.SetChaseCamera(trackPoint, 6.0, 0.5)
    vis.Initialize()
    vis.AddLogo(chrono.GetChronoDataFile('logo_pychrono_alpha.png'))
    vis.AddLightDirectional()
    vis.AddSkyBox()
    vis.AttachVehicle(m113.GetVehicle())

    # Create the driver system
    # ------------------------

    driver = veh.ChDriver(m113.GetVehicle())
    driver.Initialize()

    # Inter-module communication data
    shoe_forces_left = veh.TerrainForces(m113.GetVehicle().GetNumTrackShoes(veh.LEFT))
    shoe_forces_right = veh.TerrainForces(m113.GetVehicle().GetNumTrackShoes(veh.RIGHT))

    # Simulation loop
    # -------------------------------------------------------------------------------------------

    m113.GetVehicle().EnableRealtime(True)

    # Number of simulation steps between miscellaneous events
    debug_steps = m.ceil(debug_step_size / step_size)

    # Initialize simulation frame counter and simulation time
    step_number = 0

    while vis.Run():
        time = m113.GetSystem().GetChTime()
        
        vis.BeginScene()
        vis.Render()
        vis.EndScene()

        # Get driver inputs
        throttle, steering, braking = get_driver_inputs(time)
        driver.SetThrottle(throttle)
        driver.SetSteering(steering)
        driver.SetBraking(braking)
        driver_inputs = driver.GetInputs()

        # Update modules (process inputs from other modules)
        driver.Synchronize(time)
        terrain.Synchronize(time)
        m113.Synchronize(time, driver_inputs, shoe_forces_left, shoe_forces_right)
        vis.Synchronize(time, driver_inputs)

        # Advance simulation for one timestep for all modules
        driver.Advance(step_size)
        terrain.Advance(step_size)
        m113.Advance(step_size)
        vis.Advance(step_size)

        # Increment frame number
        step_number += 1

        # Outputs ***
        if (debug_output and step_number % debug_steps == 0) :
            print("\n\n============ System Information ============\n")
            print( "Time = ", time, "s\n")
            #my_hmmwv.DebugLog(OUT_SPRINGS | OUT_SHOCKS | OUT_CONSTRAINTS)

            ###################################### ChChassis.{} ####################################
            # print(dir(my_hmmwv.GetChassis()))
            # =============================================================================================
            # 'ExportComponentList', 'GetBody', 'GetCOMFrame', 'GetCOMSpeed', 'GetDriverPos',
            # 'GetInertia', 'GetLocalDriverCoordsys', 'GetLocalPosRearConnector', 'GetMarkers', 
            # 'GetMass', 'GetName', 'GetPointAcceleration', 'GetPointLocation', 'GetPointVelocity',
            # 'GetPos', 'GetRot', 'GetSpeed', 'GetSystem', 'GetTemplateName', 'GetTransform', 
            # 'HasBushings', 'Initialize', 'InitializeInertiaProperties', 'IsFixed', 'IsInitialized', 
            # 'Output', 'OutputEnabled', 'RemoveJoint', 'RemoveVisualizationAssets', 
            # 'SetAerodynamicDrag', 'SetCollide', 'SetFixed', 'SetName', 'SetOutput', 
            # 'SetVisualizationType', 'Synchronize', 'TransformInertiaMatrix', 'UpdateInertiaProperties', 
            # '__class_', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', 
            # '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
            # '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
            # '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__swig_destroy__', 
            # '__weakref_', 'this', 'thisown']
            # =============================================================================================
    

            ##################################### ChMarkers.{} ########################################
            # print(dir(marker))
            # ==============================================================================================
            # ['Amatrix', 'ArchiveIn', 'ArchiveOut', 'Compute_Adt', 'Compute_Adtdt', 'ConcatenatePostTransformation', 'ConcatenatePreTransformation',
            # 'Dir_Ref2World', 'Dir_World2Ref', 'Equals', 'GetA', 'GetA_dt', 'GetA_dtdt', 'GetAbsCoord', 'GetAbsCoord_dt', 'GetAbsCoord_dtdt', 'GetAbsFrame', 
            # 'GetAbsWacc', 'GetAbsWvel', 'GetBody', 'GetChTime', 'GetCoord', 'GetCoord_dt', 'GetCoord_dtdt', 'GetIdentifier', 'GetInverse', 'GetMotionType',
            # 'GetMotion_X', 'GetMotion_Y', 'GetMotion_Z', 'GetMotion_ang', 'GetMotion_axis', 'GetName', 'GetNameString', 'GetPos', 'GetPos_dt', 'GetPos_dtdt', 
            # 'GetRest_Coord', 'GetRot', 'GetRotAngle', 'GetRotAxis', 'GetRot_dt', 'GetRot_dtdt', 'GetWacc_loc', 'GetWacc_par', 'GetWvel_loc', 'GetWvel_par', 
            # 'Impose_Abs_Coord', 'Impose_Rel_Coord', 'Invert', 'MFlagGet', 'MFlagSetOFF', 'MFlagSetON', 'MFlagsSetAllOFF', 'MFlagsSetAllON', 
            # 'M_MOTION_EXTERNAL', 'M_MOTION_FUNCTIONS', 'M_MOTION_KEYFRAMED', 'Move', 'Normalize', 'PointAccelerationLocalToParent', 
            # 'PointAccelerationParentToLocal', 'PointSpeedLocalToParent', 'PointSpeedParentToLocal', 'Point_Ref2World', 'Point_World2Ref', 'SetAbsCoord', 
            # 'SetAbsCoord_dt', 'SetAbsCoord_dtdt', 'SetBody', 'SetChTime', 'SetCoord', 'SetCoord_dt', 'SetCoord_dtdt', 'SetIdentifier', 'SetIdentity', 'SetMotionType',
            # 'SetMotion_X', 'SetMotion_Y', 'SetMotion_Z', 'SetMotion_ang', 'SetMotion_axis', 'SetName', 'SetNameString', 'SetPos', 'SetPos_dt', 'SetPos_dtdt', 'SetRot', 
            # 'SetRot_dt', 'SetRot_dtdt', 'SetWacc_loc', 'SetWacc_par', 'SetWvel_loc', 'SetWvel_par', 'TransformDirectionLocalToParent', 
            # 'TransformDirectionParentToLocal', 'TransformLocalToParent', 'TransformParentToLocal', 'TransformPointLocalToParent', 'TransformPointParentToLocal', 
            # 'Update', 'UpdateState', 'UpdateTime', 'UpdatedExternalTime', '__class__', '__delattr__', '__dict__', '__dir__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', 
            # '__getattribute__', '__gt__', '__hash__', '__imod__', '__imul__', '__init__', '__init_subclass__', '__irshift__', '__le__', '__lt__', '__module__', '__mul__', '__ne__', '__new__',
            # '__reduce__', '__reduce_ex__', '__repr__', '__rshift__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__swig_destroy__', '__truediv__', '__weakref__', 'coord', 
            # 'coord_dt', 'coord_dtdt', 'this', 'thisown']
            # ==============================================================================================

            chassis = m113.GetChassis()    

            # [0]: Chassis driver position / [1]: Chassis COM
            marker = chassis.GetMarkers()[1]
            marker_name = marker.GetName()

            marker_location = marker.GetAbsCoord().pos
            marker_velocity = chassis.GetPointVelocity(marker_location)

            chassis_rotation = chassis.GetRot()
            roll, pitch, yaw = euler_from_quaternion(chassis_rotation.e0, chassis_rotation.e1, chassis_rotation.e2, chassis_rotation.e3)
            rotate = marker.GetAbsWvel()*180/m.pi
            
            print( "Inputs")
            print("  [ Driver Cmd ] throttle:",throttle," braking:",braking, " steering:",steering, "\n")

            print( "Outputs")
            print( "  [",marker_name,"Loc ] x:" , marker_location.x, " y:", marker_location.y, " z:",marker_location.z)
            print( "  [",marker_name,"Vel ] vx:", marker_velocity.x," vy:",marker_velocity.y," vz:",marker_velocity.z)

            # print("  [ Chassis Quaternion Rot ] q0:", chassis_rotation.e0," q1:", chassis_rotation.e1," q2:",chassis_rotation.e2," q3: ",chassis_rotation.e3)
            print("  [ Chassis Rot Ang ] rx:",roll," ry:",pitch," rz:",yaw," (degree)")
            print("  [ Chassis Rot Vel ] wx:",rotate.x," wy:",rotate.y," wz:",rotate.z," (degree/s)")

            

    return 0

# -------------------------------------------------------------------------------------------------
# Setting Data path
# data_path = chrono.GetChronoDataFile('')
# print("PyChrono data path:", data_path)
veh.SetDataPath(chrono.GetChronoDataPath() + 'vehicle/')

# Initial vehicle location and orientation
initLoc = chrono.ChVectorD(0, 0, 0.7)
initRot = chrono.ChQuaternionD(1, 0, 0, 0)

# Contact method
contact_method = chrono.ChContactMethod_SMC

# Rigid terrain
terrainHeight = 0;      # terrain height (FLAT terrain only)
terrainLength = 100.0;  # size in X direction
terrainWidth = 100.0;   # size in Y direction

# Point on chassis tracked by the camera
trackPoint = chrono.ChVectorD(0.0, 0.0, 0.0)

# Simulation step sizes
step_size = 5e-4;

# Time interval between two render frames (화면에 보이는 step size)
render_step_size = 1.0 / 60;  # FPS = 60

# Debug logging
debug_output = True
debug_step_size = 1.0 / 60  # FPS = 1

main()
profile
System_Dynamics_Lab

0개의 댓글