pythonnnnnnnnnnnnnn

This commit is contained in:
cs-powell
2025-02-10 16:48:34 -05:00
parent e15c534c07
commit a1aaf7704d
5 changed files with 1418 additions and 2 deletions

View File

@@ -0,0 +1,145 @@
from time import sleep
import xpc
from model import AircraftLandingModel
def ex():
print("X-Plane Connect example script")
print("Setting up simulation")
with xpc.XPlaneConnect() as client:
# Verify connection
try:
# If X-Plane does not respond to the request, a timeout error
# will be raised.
client.getDREF("sim/test/test_float")
except:
print("Error establishing connection to X-Plane.")
print("Exiting...")
return
test = AircraftLandingModel(client)
# # Set position of the player aircraft
# print("Setting position")
# # Lat Lon Alt Pitch Roll Yaw Gear
# posi = [37.524, -122.06899, 2500, 0, 0, 0, 1]
# client.sendPOSI(posi)
# # Set position of a non-player aircraft
# print("Setting NPC position")
# # Lat Lon Alt Pitch Roll Yaw Gear
# posi = [37.52465, -122.06899, 2500, 0, 20, 0, 1]
# client.sendPOSI(posi, 1)
# # Set angle of attack, velocity, and orientation using the DATA command
# print("Setting orientation")
# data = [\
# [18, 0, -998, 0, -998, -998, -998, -998, -998],\
# [ 3, 130, 130, 130, 130, -998, -998, -998, -998],\
# [16, 0, 0, 0, -998, -998, -998, -998, -998]\
# ]
# client.sendDATA(data)
# Set control surfaces and throttle of the player aircraft using sendCTRL
print("Setting controls")
ctrl = [0.0, 0.0, 0.0, 0.0]
client.sendCTRL(ctrl)
# Pitch, Roll, Rudder, Throttle
# Pause the sim
client.pauseSim(False)
count = 0
innercount = 0
#ONE SECOND INCREMENTS
# while(count < 1000000 ):
# client.pauseSim(False)
# sleep(1.0)
# print("Pausing" + str(count))
# client.pauseSim(True)
# sleep(1.0)
# count+=1
#0.1 SECOND INCREMENTS
# while(count < 1000000 ):
# client.pauseSim(False)
# sleep(0.1)
# print("Pausing" + str(count))
# client.pauseSim(True)
# sleep(0.1)
# count+=1
#0.001 SECOND INCREMENTS
# while(count < 1000000 ):
# client.pauseSim(False)
# sleep(0.001)
# print("Pausing" + str(count))
# client.pauseSim(True)
# sleep(0.001)
# count+=1
#0.00001 SECOND INCREMENTS
# while(count < 1000000 ):
# client.pauseSim(False)
# sleep(0.00001)
# print("Pausing" + str(count))
# client.pauseSim(True)
# sleep(0.00001)
# count+=1
# sim/operation/override/override_timestep
#Doing stuff In between Test SECOND INCREMENTS
while(count < 1000000 ):
#50 Millisecond Timesteps
sleep(0.05)
client.pauseSim(False) #Unpause
sleep(0.05) # Run 50 Milliseconds
client.pauseSim(True) # Pause Simulator
#Run Model (Send commands to simulator within this process)
####Insert Model Here, some assembly required#######
test.update_aircraft_state()
test.update_controls_simultaneously()
#Please work
#Repeat
print("Advanced 50 Milliseconds: Step #" + str(count))
count+=1
# print("Pausing" + str(count))
# innercount = 0
# client.pauseSim(True)
# sleep(0.05) #Simulate 50 milliseconds
# sleep(0.01) #Simulate 50 milliseconds
# # while(innercount < 100000):
# # # print("Doing Stuff" + str(innercount)) # Simulates the model running and computing for 50 Milliseconds maybe?
# # innercount+=1
# # else:
# client.pauseSim(False)
# print("Exit Pause" + str(count))
# sleep(0.5)
# count+=1
# Toggle pause state to resume
print("Resuming")
client.pauseSim(False)
# Let the sim run for a bit.
sleep(4)
print("End of Python client example")
input("Press any key to exit...")
if __name__ == "__main__":
ex()

142
Python3/src/model.py Normal file
View File

@@ -0,0 +1,142 @@
import pyactr
# from XPlaneConnect import *
import xpc
# Initialize XPlaneConnect client
class AircraftLandingModel(pyactr.ACTRModel):
def __init__(self,client):
super().__init__()
# Initialize the declarative memory (DM)
# self.decmem.add(
# [
# ("airspeed", 100), # Current airspeed (e.g., 100 knots)
# ("roll", 0), # Current roll (0 for wings level)
# ("heading", 0), # Current heading
# ("descent_rate", 500), # Current descent rate in fpm
# ("target_airspeed", 80), # Target airspeed during descent
# ("target_roll", 0), # Target roll (wings level)
# ("target_heading", 90), # Target heading (runway heading)
# ("target_descent_rate", 500) # Target descent rate (fpm)
# ]
# )
self.client = client
self.airspeed = 100
self.roll = 0
self.heading = 0
self.descent_rate = 500
self.target_airspeed = 80
self.target_roll = 0
self.target_heading = 0
self.target_descent_rate = 500
# Declare the state for previous values
self.previous_airspeed = None
self.previous_roll = None
self.previous_heading = None
self.previous_descent_rate = None
# Initialize the integral errors for each parameter
self.integral_airspeed = 0
self.integral_roll = 0
self.integral_heading = 0
self.integral_descent_rate = 0
# Integral gains (tune these values for performance)
self.Kp = 0.1 # Proportional gain
self.Ki = 0.01 # Integral gain
def proportionalIntegralControl(self, current, target, integral_error):
"""
Proportional-Integral control rule implementation for multiple parameters.
"""
# Calculate the error (current - target)
error = target - current
# Update the integral of the error
integral_error += error
# Calculate the control value using the PI formula
control_value = (self.Kp * error) + (self.Ki * integral_error)
return control_value, integral_error # Return control value and updated integral error
def update_controls_simultaneously(self):
"""
Update all controls at the same time by calculating control values for each parameter.
"""
# Compute control values for all parameters (yoke pull, yoke steer, rudder, throttle)
yoke_pull, self.integral_airspeed = self.proportionalIntegralControl(self.airspeed, self.target_airspeed, self.integral_airspeed)
yoke_steer, self.integral_roll = self.proportionalIntegralControl(self.roll, self.target_roll, self.integral_roll)
rudder, self.integral_heading = self.proportionalIntegralControl(self.heading, self.target_heading, self.integral_heading)
throttle, self.integral_descent_rate = self.proportionalIntegralControl(self.descent_rate, self.target_descent_rate, self.integral_descent_rate)
# Send all controls simultaneously to X-Plane
self.send_controls_to_xplane(yoke_pull, yoke_steer, rudder, throttle)
def send_controls_to_xplane(self, yoke_pull, yoke_steer, rudder, throttle):
"""
Sends all control inputs to X-Plane using XPlaneConnect
"""
# Send yoke pull, yoke steer, rudder, and throttle simultaneously
self.client.sendControls([yoke_pull, yoke_steer, 0, rudder, throttle]) # Control inputs: [yoke_pull, yoke_steer, roll/pitch, rudder, throttle]
# Update the model's DM based on X-Plane data
def update_aircraft_state(self):
# Retrieve current data from X-Plane
airspeed = self.client.getDREF("sim/cockpit2/gauges/indicators/airspeed_kts_pilot")
roll = self.client.getDREF("sim/cockpit2/gauges/indicators/roll_AHARS_deg_pilot")
heading = self.client.getDREF("sim/cockpit2/gauges/indicators/heading_AHARS_deg_mag_pilot")
descent_rate = self.client.getDREF("sim/flightmodel/position/vh_ind_fpm")
# Update the model's declarative memory
# model.declarative_memory["airspeed"] = airspeed
# model.declarative_memory["roll"] = roll
# model.declarative_memory["heading"] = heading
# model.declarative_memory["descent_rate"] = descent_rate
self.airspeed = airspeed
self.roll = roll
self.heading = heading
self.descent_rate = descent_rate
# def rules(self):
# """
# Define the rules for descent control using proportional-integral control for all controls at once.
# """
# return [
# # Rule to adjust all controls simultaneously based on PI control for each parameter
# pyactr.Production(
# condition=pyactr.Condition("airspeed", "airspeed") &
# pyactr.Condition("roll", "roll") &
# pyactr.Condition("heading", "heading") &
# pyactr.Condition("descent_rate", "descent_rate") &
# pyactr.Condition("target_airspeed", "target_airspeed") &
# pyactr.Condition("target_roll", "target_roll") &
# pyactr.Condition("target_heading", "target_heading") &
# pyactr.Condition("target_descent_rate", "target_descent_rate"),
# action=self.update_controls_simultaneously(),
# ),
# ]
# # Function to get the current dataref value for a given parameter
# def getDref(parameter_name):
# # Depending on the parameter name, you would query X-Plane datarefs
# if parameter_name == "Airspeed":
# # Get airspeed dataref
# return client.getData([DATAREF_AIRSPEED])
# elif parameter_name == "Roll":
# # Get roll angle dataref
# return client.getData([DATAREF_ROLL])
# elif parameter_name == "Hdg":
# # Get heading dataref
# return client.getData([DATAREF_HEADING])
# elif parameter_name == "DescentRate":
# # Get descent rate dataref
# return client.getData([DATAREF_DESCENT_RATE])

174
Python3/src/pyactrDemo.py Normal file
View File

@@ -0,0 +1,174 @@
from time import sleep
import xpc
import pyactr as actr #Importing ACT-R python edition
def ex():
## ACT-R Setup
playing_memory = actr.ACTRModel()
actr.chunktype("pitch", "up, throttle")
initial_chunk = actr.makechunk(typename="pitch", up="20")
## Define new chunk type(s)
#
# Control Updates
# Rudder = #### (0.5)
# Elevator = #### (0)
# Aileron = ####
# Throttle = #####
# Rules to define How much to change based on current parameters
# Within a given rule, multiple values can be updated (which values depend on
# acceptable ranges/current envrionment state/current goal state(pre-touchdown (cares about altitude) vs.
# after touchdown braking (doesn't care about altitude)))
actr.chunktype("Control Update", "rudder, elevator, aileron, throttle")
##Use goal states to frame acceptable ranges for parameters (descent vs touchdown vs level flight etc etc.)
## Divide landing task into subproblems
## Level Flight
# Initial Descent
# .......
# and/or tracking landing signal (ILS, RNAV, etc.) [Quantitative measure]
## Environment Conditions: Calm...very calm
##First Focus: Begin Simulation with the tedious button pressing all complete -- [go the route of Dead Reckoning]
# (i.e. focus on command and control not beuracracy)
# Define acceptable range of parameters for each stage
# Stabilized descent (Maintaining a given descent rate in FPM -- Maintaining Speed, loosing altitude)
# --> Rudder
# --> Aileron
# --> Elevator
# --> Throttle
# -->> Altitude (Throtte)
# -->> Airspeed (Pitch = Elevator)
# -->> Pitch (Elevator)
# -->>>>>>>>>> Transition Point
# Initial Parameter Above a certain altitude (50ish feet)
# Search for established equations & control schema/relationships for the controls and/or environmental stimuli
# Round out/ Flare & Crosswind Corections(i.e. don't land sideways) [Arresting the descent, maintaing wings level,
# Letting the speed bleed off while maintaing altitude]
# -->
# Touchdown
# -->
# Rollout & Braking & Centerline tracking
# -->
goal = playing_memory.set_goal("goal")
goal.add(initial_chunk)
print(goal)
playing_memory.productionstring(name="startpitch", string="""
=goal>
isa pitch
up 20
throttle None
?manual>
state free
==>
=goal>
isa pitch
throttle 100""") #this rule will be modified later
playing_memory.productionstring(name="modifyPitch", string="""
=goal>
isa pitch
up 20
throttle 100
==>
+manual>
isa _manual
#
cmd press_key
key 1
#
=goal>
isa pitch
throttle None""") #this rule works correctly
simulation_game = playing_memory.simulation()
simulation_game.run()
# print(goal)
# final_chunk = goal.pop()
# print(final_chunk)
# print("X-Plane Connect example script")
# print("Setting up simulation")
# with xpc.XPlaneConnect() as client:
# # Verify connection
# try:
# # If X-Plane does not respond to the request, a timeout error
# # will be raised.
# client.getDREF("sim/test/test_float")
# except:
# print("Error establishing connection to X-Plane.")
# print("Exiting...")
# return
# # Set position of the player aircraft
# print("Setting position")
# # Lat Lon Alt Pitch Roll Yaw Gear
# posi = [37.524, -122.06899, 2500, 0, 0, 0, 1]
# client.sendPOSI(posi)
# # Set position of a non-player aircraft
# print("Setting NPC position")
# # Lat Lon Alt Pitch Roll Yaw Gear
# posi = [37.52465, -122.06899, 2500, 0, 20, 0, 1]
# client.sendPOSI(posi, 1)
# # Set angle of attack, velocity, and orientation using the DATA command
# print("Setting orientation")
# data = [\
# [18, 0, -998, 0, -998, -998, -998, -998, -998],\
# [ 3, 130, 130, 130, 130, -998, -998, -998, -998],\
# [16, 0, 0, 0, -998, -998, -998, -998, -998]\
# ]
# client.sendDATA(data)
# # Set control surfaces and throttle of the player aircraft using sendCTRL
# print("Setting controls")
# ctrl = [0.0, 0.0, 0.0, 0.8]
# client.sendCTRL(ctrl)
# # Pause the sim
# print("Pausing")
# client.pauseSim(True)
# sleep(2)
# # Toggle pause state to resume
# print("Resuming")
# client.pauseSim(False)
# # Stow landing gear using a dataref
# print("Stowing gear")
# gear_dref = "sim/cockpit/switches/gear_handle_status"
# client.sendDREF(gear_dref, 0)
# # Let the sim run for a bit.
# sleep(4)
# # Make sure gear was stowed successfully
# gear_status = client.getDREF(gear_dref)
# if gear_status[0] == 0:
# print("Gear stowed")
# else:
# print("Error stowing gear")
print("End of Python client example")
input("Press any key to exit...")
if __name__ == "__main__":
ex()