Jump to content

[1.3] kOS Scriptable Autopilot System v1.1.3.0


erendrake

Recommended Posts

I have an issue with steering in kOS version 1.0 that I haven't been able to fix.  I'm afraid to upgrade kOS to the latest version because I'm using kOS on an install of Real Solar System and Realism Overhaul that is still using KSP 1.1.3, and I don't think the mods I'm using are all update for KSP version 1.2.

Anyway, as part of my Ares mission, I've been writing a kOS script for handling the launch.  I've been able to write the staging and throtting commands just fine, but when it comes to steering, my rocket seems to act like a drunk man.

My main launch scripts can be found here:

Right now, I'm trying to test how to tell my rocket to roll 90 degrees clockwise.  I've been using this command:

//Execute 90-degree roll.
SET roll to 180 - 90.
LOCK STEERING to Up + R(0,0,roll).

It's equivalent to LOCK STEERING to Up + R(0,0,90).  When the command is executed, though, my rocket oversteers by up to twice the commanded roll, so for instance, the rocket rolls from 180 to 0 and back.  I looked up the kOS documentation and got to work trying to solve the issue.

First I tried adjusting the ROLLTS and observed no change in behavior.  I tried adjusting ROLLTORQUEFACTOR and observed no change in behavior.  Then I figured that I would have to tune the Roll PID controller itself.

I wrote a script for doing so, hoping I was measuring the correct value for tuning:

//Saturn VB PID Tuning
//DECLARE PARAMETER Kd.

RUNPATH("AresLaunchDisplay.ks").

//SET Inboard to SHIP:PARTSTAGGED("F1AInboard")[0].
SET Outboard to SHIP:PARTSTAGGED("F1AOutboard1")[0].
SET SRB to SHIP:PARTSTAGGED("SRB1")[0].

//Possibility for roll oversteer - kOS underestimates torque available.

//STEERINGMANAGER:RESETPIDS().
//SET STEERINGMANAGER:ROLLPID:KP to 1. //Wrong parameters?
//SET STEERINGMANAGER:ROLLPID:KI to 0.
//SET STEERINGMANAGER:ROLLPID:KD to Kd.
SET STEERINGMANAGER:ROLLTORQUEADJUST to -300000. //This should correct kOS's torque underestimation

CLEARSCREEN.

SAS ON.
LOCK THROTTLE to 1.0.

STAGE. //F-1A ignition

UNTIL (Outboard:THRUST/Outboard:MAXTHRUST) > 0.88 {
  IF(Outboard:MAXTHRUST > 0) {  //Prevent NAN
    LaunchDisplay(0,2,Outboard:THRUST/Outboard:MAXTHRUST,0).
  }
}

STAGE.  //SRB ignition and liftoff
CLEARSCREEN.

LOG "Roll PID Tuning" TO Roll_Log.txt.
LOG "Kd: " + STEERINGMANAGER:ROLLPID:KD TO Roll_Log.txt.
LOG "t,Roll Deviation (Kd = " + STEERINGMANAGER:ROLLPID:KD +")" TO Roll_Log.txt.

//Execute 90-degree roll.
SET roll to 180 - 90.
LOCK STEERING to Up + R(0,0,roll). //rotation not affected by PID settings because not cooked?

//Print deviation from desired roll vs time.
UNTIL MISSIONTIME > 90 {
  SET r to (SHIP:BEARING) - (-roll + 180).
  LOG MISSIONTIME + "," + r TO Roll_Log.txt.
  WAIT 0.001. //Should this wait go away?  Is it causing cooked steering to malfunction? - NO
}

AresLaunchDisplay.ks

//Display program for Ares Launch program.

SET State to list("Ignition Sequence Start", "Liftoff", "Max Q", "Throttle Up", "SRB Sep", "Center Engine Shutdown", "Staging", "Stage Two Ignition", "Skirt Separation", "LES Jettison", "SECO").
SET Level to list("60", "85", "100").

function LaunchDisplay{

  parameter statevariable.
  parameter throttlelevel.
  parameter liquidthrust.
  parameter SRBthrust is 0.
  
  CLEARVECDRAWS().
  //Set Velocity to VECDRAW(V(0,0,0),SHIP:VELOCITY:SURFACE + R(0,-3,0),Blue,"v",5.0,TRUE,0.3).
  
  //Set Prograde to VECDRAW(V(0,0,0),50*SHIP:SRFPROGRADE:VECTOR,Green,"p",5.0,TRUE,0.3).
  PRINT State[statevariable] at (0,0).
  PRINT "Throttle Setting: " + Level[throttlelevel] + "%" at (0,1).
  
  IF statevariable <= 5 {
    PRINT "F-1A Thrust: " + ROUND(liquidthrust * 100,1) + "%." at (0,2).
  } ELSE {
    PRINT "J-2S Thrust: " + ROUND(liquidthrust * 100,1) + "%." at (0,2).
  }
  
  IF statevariable < 4 AND statevariable > 0 {
    PRINT "UA1564 Thrust: " + ROUND(SRBthrust * 100,1) + "%." at (0,3).
  }
}

The lines for the PID parameters and declare statement are commented out here only temporarily, and I uncomment them when I need them.  I also didn't have the ROLLTORQUEADJUST line in the code when trying to tweak the PID parameters.

So I went on to set KI and KD to zero and vary KP.  No value of KP changed the behavior of the roll oscillations:

k6Z4fvT.png

Kp was set at 2000, 1, 0.001, and 100.

I then fixed Kp to 1 and varied Kd.  Also didn't see any real change in behavior except at bit of an amplitude variation at the end.

1owEcUz.png

Next I thought that maybe my engines are gimballing too much and tried to reduce the gimbal ranges.  Again, no change in behavior. (no graph available right now).  Finally, I thought that maybe kOS was underestimating the amount of available torque my craft had, so I set ROLLTORQUEADJUST to 300,000 kNm, which is what MechJeb said I was producing in the z-direction.  No change in behavior.  I subtracted 300,000kNm and also experienced no change in behavior.  After that, I ran out of ideas.

I did a test with MechJeb's SmartASS and it was able to perform the 90-degree roll with almost no overshoot, so I know that it's possible for some sort of script to make the craft roll properly.  I'm not sure what, and I'm not even sure I'm tuning the right parameters or using the right commands to steer the craft or tuning the proper PID controller.

If anyone has any ideas what I'm doing wrong, let me know, because I don't have an idea what might be going on.  I'm not really familiar with PID controllers, and this is my first time using kOS to steer a rocket, and my first time trying to tune a PID controller.

Link to comment
Share on other sites

Actually, I may have solved my own problem.  On a fluke, I set Kd to 90 and finally got a different steering behavior.  I guess my PID parameters were just too low for my rocket.

At worst, I'll just make my own PID loop.  I was in the process of doing that if a high Kd setting didn't work for kOS's built-in Roll PID controller.

EDIT: Turns out having SAS on is causing the undesired steering behavior.  I noticed SAS was off, turned it on, and the severe oscillations returned.  Therefore, I can only conclude the SAS was causing issues with kOS steering.

This is something I overlooked, but I'm glad I found it.  I assumed that SAS wouldn't have an effect during cooked steering because of what the kOS documentation said, but maybe it still does cause some unwanted effects in v1.0.

Edited by Nittany Tiger
Link to comment
Share on other sites

11 hours ago, Nittany Tiger said:

This is something I overlooked, but I'm glad I found it.  I assumed that SAS wouldn't have an effect during cooked steering because of what the kOS documentation said, but maybe it still does cause some unwanted effects in v1.0.

Having SAS stability assist turned on when kOS has a LOCK STEERING on is still bad.  Does the documentation claim otherwise somewhere?  If so that needs to be changed.

(Stability assist has logic in it to stop messing with the controls when the HUMAN does something with the controls, and not take over again until the human stops touching the controls.  But it only does this for the human.  It doesn't do the same thing when an autopilot is moving the controls.  So both kOS and SAS are trying to move the controls at the same time.)

 

Link to comment
Share on other sites

https://ksp-kos.github.io/KOS/commands/flight.html

Quote

SAS OVERRIDES kOS

With the current implementation of flight control, you may now leave SAS turned on in "STABILITYASSIST" mode, and it will not override kOS‘s attempts to steer the ship. However, it will fight and/or override kOS‘s attempts to steer when using any other mode. In order for kOS to be able to turn the ship in other modes, you need to set SAS OFF or SET SASMODE TO "STABILITYASSIST". You should take care in your scripts to manage the use of SAS and SASMODE appropriately. It is common for people writing kOS scripts to explicitly start them with a use of the SAS OFF and/or SET SASMODE TO "STABILITYASSIST" commands just in case you forgot to turn it off before running the script. You could also store the current state in a temporary variable, and re-set it at the conclusion of your script.

  I made a mistake in reading that you could have SAS on and have it not do anything.  I was using SAS to help keep my ship pointed up to dampen any oscillations, but having it full on instead caused SAS and kOS to fight each other and produce those huge oscillations.  The belief that I could have SAS on meant that I overlooked it as a problem until I reconsidered it today.

  I actually thought kOS's PID controllers were wonky, and was on the verge on writing my own.  As fun as that could have been, I'm glad I found out the true cause of my issues, albeit it was a silly mistake.

  I should try SAS set to Stability Assist before I start coding the pitch maneuver since I want my ship to roll and then pitch after reaching 50 m/s, and it needs to be stable for a second or two during its ascent before the pitch and roll program are engaged.

EDIT: Turns out default SAS setting was Stability Assist, so I dunno what was going on.  I'm just going to leave SAS off in my code.  I could try to figure out the problem later, or possibly it's a feature post 1.0, but I can replace SAS ON with LOCK STEERING to Up and get the same result I want hopefully without any steering silliness.

Edited by Nittany Tiger
Link to comment
Share on other sites

5 hours ago, Nittany Tiger said:

Turns out default SAS setting was Stability Assist, so I dunno what was going on.  I'm just going to leave SAS off in my code.  I could try to figure out the problem later, or possibly it's a feature post 1.0, but I can replace SAS ON with LOCK STEERING to Up and get the same result I want hopefully without any steering silliness.

That’s more or less what I do, and it works fine, except this is what I have:

lock steering to lookdirup(heading(azimuth,90):vector, ship:facing:topvector).

I think I snarfed that from someone else’s script when I was starting out, so there are probably better ways to do it.  I’m also wondering, now that I look at it again, if this would lead to disaster if I built a ship where the command module was upside down or sideways at launch…

Link to comment
Share on other sites

Found a problem with this Cooked control.

While all the indicators say the cooked control system is working, the gimbals (RD704s) are not moving (SAS ON or OFF) = no control ?

I've gone though checking the gimbals etc..  Anyone else have a similar problem ?

Edited by ColKlonk2
Link to comment
Share on other sites

On 2/24/2017 at 9:54 AM, meyerweb said:

That’s more or less what I do, and it works fine, except this is what I have:


lock steering to lookdirup(heading(azimuth,90):vector, ship:facing:topvector).

I think I snarfed that from someone else’s script when I was starting out, so there are probably better ways to do it.  I’m also wondering, now that I look at it again, if this would lead to disaster if I built a ship where the command module was upside down or sideways at launch…

Since I launch vertically, and stock SAS holds vertical just fine, I decided to just lock steering to "kill," since that's the same as turning SAS on and setting it to stability assist mode.  Maybe the statement about SAS is for post 1.0 versions of kOS.Plus, using cooked steering all the way seems to work so far for my rocket guidance.  I start with LOCK STEERING to "kill" until my surface velocity exceeds 50 m/s (it's all vertical velocity because it's a vertical launch), and then I command the pitch and roll by using LOCK STEERING to HEADING(90,87).  From experimentation, that seems to do what I want where the rocket pitches slightly for a gravity turn and rolls to a eastward heading.  I'll try to lock it to prograde after the pitchover when the velocity and facing vectors are closely aligned and hopefully that will give me a good gravity turn.

Quote

Found a problem with this Cooked control.

While all the indicators say the cooked control system is working, the gimbals (RD704s) are not moving (SAS ON or OFF) = no control ?

I've gone though checking the gimbals etc..  Anyone else have a similar problem ?

Is your rocket following cooked steering commands?  Is it turning or holding still like you ask even though you're not getting a visible gimbal response?

Edited by Nittany Tiger
Link to comment
Share on other sites

You can see the control action indicators moving in the bottom left hand corner.

With a close up view of the engines, the (engines) gimbals are not moving.

The rocket doesn't correct for heading nor pitch under Steering lock, and drifts about the vertical.. straight up.

 

 

 

Edited by ColKlonk2
Link to comment
Share on other sites

I know I once experienced a bug where if I didn't activate engines through staging, they would not gimbal.  This wasn't a kOS problem, but a problem I experienced trying to activate engines through AGX.  This might just be a stock bug.

How are you activating your engines?

Link to comment
Share on other sites

	// in 2 seperate functions - global variables//
	//===========================================//
	List Parts in EngList.
	For Prt in EngList
	{
		If prt:TAG = "Stg1_Eng1"
		{
			Set Eng1 to prt.
		}
		If prt:TAG = "Stg1_Eng2"
		{
			Set Eng2 to prt.
		}
		If prt:TAG = "Stg1_Eng3"
		{
			Set Eng3 to prt.
		}
		If prt:TAG = "Stg2_Eng1"
		{
			Set Eng4 to prt.
		}
	}
//===========================================//
		If ThisTime = 4
		{
			Print "Activated   " at (22,12).
			Eng1:activate.
			Set Eng1:Gimbal:LOCK to FALSE.
			Set Eng1:Gimbal:LIMIT to 100.
			Eng2:activate.
			Set Eng2:Gimbal:LOCK to FALSE.
			Set Eng2:Gimbal:LIMIT to 100.
			Eng3:activate.
			Set Eng3:Gimbal:LOCK to FALSE.
			Set Eng3:Gimbal:LIMIT to 100.
			Lock THROTTLE to 1.0.
		}
		Wait 1.
//===========================================//

Not sure but AGX doesn't seem have and engine activate triggers this time around ??

So I've put this into a parts list.

Edited by ColKlonk2
Link to comment
Share on other sites

Yeah, I think you're hitting the same bug I am where if you don't activate engines through staging but through action groups, then the engines don't gimbal.  I don't know if it's an AGX bug or a stock bug, but it's not a kOS bug.  The only way I know how to fix it is to activate your engines through staging.  I also don't know if this is a bug in RSS/RO installs or stock ones.  I think I just need to check myself where the bug is.

In summary, your issue is that since you're trying to turn your engines on via AGX action groups (or stock action groups), the engine gimbals don't turn on.  Currently, the only solution to that is to activate your engines through staging.

Link to comment
Share on other sites

can somebody explain me why

                                           set antenna to ship:partstagged("antenna").

                                           print antenna:modules.

gets error "suffix MODULES not found on object list of 1 items..."

Link to comment
Share on other sites

39 minutes ago, Nittany Tiger said:

@GeKa do you have any parts whose name tags are set to "antenna"?  SHIP:PARTSTAGGED() doesn't look for part with "antenna" in the name, but it looks for parts with their name tags set to "antenna."

yes, i know, the first line doesn't get error, and if after first line i type "print antenna" it shows me the id and tag of it, the error appears when i try to find out the modules of the part.

Link to comment
Share on other sites

3 hours ago, GeKa said:

error "suffix MODULES not found on object list of 1 items..."

try:
set antenna to ship:partstagged("antenna")[0].

partstagged returns a list (of parts). You want the modules of the first element in that list.

Edited by pellinor
Link to comment
Share on other sites

3 hours ago, ColKlonk2 said:

@Nittany Tiger: It seems to be a combination of staging and engine activation.


Stage.
Wait 1.
Lock THROTTLE to 1.0.
Eng4:activate.

 

That's good.  I tested engine activation with stock action groups, and the gimbal bug didn't pop up.  It must be something with AGX.

Link to comment
Share on other sites

On 02/22/2017 at 10:00 PM, podbaydoor said:

I'm trying to call the trajectory prediction functions (`positionat` and `velocityat`) on a landed vessel to do some precision landings. I was hoping this would be a clean way to account the changing absolute position of the landed vessel as the parent body rotates. However I just get NaN vectors back. Am I doing something wrong or does `positionat` not work on unloaded or landed vessels?

If trajectory prediction won't work here, does anyone have code for computing the position of a landed vessel in the future, accounting for rotation speed, elevation, latitude, etc?

I wouldn't expect POSITIONAT to work for anything landed. Landed vessels have an orbital velocity based on the body's rotation, but their trajectory does not follow the Keplerian orbit that corresponds to this velocity (e.g. a 175m/s orbital velocity at Kerbin's equator corresponds roughly to a 0m by -598500m orbit, but the vessel can't fall through the planet towards periapsis). For the same reasons, VELOCITYAT is likely not to predict their future velocity.

At least body rotation is predictable. Can you rotate the landed craft's current position vector (converted to be from the body's centre to the craft) around the body's axis of rotation by the angle the body will rotate over the time that will elapse? That could then be converted back to be relative to the active vessel. I've not done any accurate landings yet, so I don't really have anything useful to share, I'm afraid.

Link to comment
Share on other sites

13 hours ago, pellinor said:

try:
set antenna to ship:partstagged("antenna")[0].

partstagged returns a list (of parts). You want the modules of the first element in that list.

thank you a lot, that works. But i don't understand, year earlier i did it without this [0] and it works and also it shows whether the module is string or not.

Edited by GeKa
new information
Link to comment
Share on other sites

9 hours ago, GeKa said:

thank you a lot, that works. But i don't understand, year earlier i did it without this [0] and it works and also it shows whether the module is string or not.

Are you sure this used to work?  I think it only worked on a pre-release not public version nobody should have seen.

The reason for the [0] is that there can be more than one part with the same name.  PartsTagged returns a list of hits.  That also allows it to return a list of zero things as a way to communicate that there were no such parts.

 

Link to comment
Share on other sites

Hey guys, I have a problem with my second ever script.  It is intended to launch a rocket, circularize in LKO, perform scientific experiments and recover the capsule. I dont know why, but all of a sudden kOS seems to restart when my ship reaches about 75km. The Terminal Window just "reboots", showing the exact same data it does when starting up on the launchpad. Does anybody have a clue why this happens? Or did someone have a similar problem? 

Thanks so much for your help!

Finn

//Test01 REMASTERED 
//Goal: Launch a Capsule into Orbit, perform experiments and return home safely.

//Set the ship to a known configuration
SAS off.
RCS on.
lights on.
lock throttle to 0. //Throttle is a decimal from 0.0 to 1.0
gear off.
set fuel to 0.

clearscreen.

set targetApoapsis to 80000. //Target apoapsis in meters
set targetPeriapsis to 80000. //Target periapsis in meters

set runmode to 2. //Safety in case we start mid-flight
if ALT:RADAR < 100 { //Guess if we are waiting for take off
    set runmode to 1.
    }

print "Initating launch sequence.".
wait 1.
print "T-3 to Engine Ignition.".
wait 1.
print "T-2".
wait 1.
print "T-1".
wait 1.
print "Lift off!".

until runmode = 0 { //Run until we end the program

    if runmode = 1 { //Ship is on the launchpad
        lock steering to UP.  //Point the rocket straight up
        set TVAL to 1.        //Throttle up to 100%
        stage.                //Same thing as pressing Space-bar
        set runmode to 2.     //Go to the next runmode
    }

    else if runmode = 2 { // Fly UP to 10,000m
        lock steering to heading (90,90). //Straight up.
        set TVAL to 1.
        if SHIP:ALTITUDE > 10000 { 
            //Once altitude is higher than 10km, go to Gravity Turn mode
            set runmode to 3.
        }
    }

    else if runmode = 3 { //Gravity turn
        set targetPitch to max( 5, 90 * (1 - ALT:RADAR / 50000)).  //Pitch over gradually until levelling out to 5 degrees at 50km
        lock steering to heading ( 90, targetPitch). //Heading 90' (East), then target pitch
        set TVAL to 1.
		if SHIP:APOAPSIS > targetApoapsis {
            set runmode to 4.
        }
    }
    
    else if runmode = 4 { //Coast to Ap
        lock steering to heading ( 90, 3). //Stay pointing 3 degrees above horizon
        set TVAL to 0. //Engines off.
       	set runmode to 5.
    }

    else if runmode = 5 { //Burn to raise Periapsis
        if (ETA:APOAPSIS < 15) or (VERTICALSPEED < 0) { //If we're less then 15 seconds from Ap or loosing altitude
            set TVAL to 1.
        }
        if (SHIP:PERIAPSIS > targetPeriapsis) or (SHIP:PERIAPSIS > targetApoapsis * 0.95) {
            //If the periapsis is high enough or getting close to the apoapsis
            set TVAL to 0.
            set runmode to 6.
        }
    }

    else if runmode = 6 { //Final touches
        set TVAL to 0. //Shutdown engine.
        panels on.     //Deploy solar panels
        lights on.
        unlock steering.
        print "Stable Orbit around Kerbin reached.".
        wait 6.
        print "Beginning scientific Experiments.".
        wait 1.
        toggle ag1.
        wait 6.
        print "All data collected!".
        toggle ag2.
        set runmode to 7.
    }

    else if runmode = 7 { //Wait for the ship to reach Apoapsis
       if ETA:APOAPSIS < 10{
    		set WARP to 0.
       		wait 2.
       		lock steering to retrograde.
       		wait 3.
       		until SHIP:PERIAPSIS < 28000{
       				lock throttle to 1.
       		}
       	}
       	lock throttle to 0.
       	set runmode to 8.
    }

    else if runmode = 8{
       		if ALT:RADAR < 80000 {
       			stage.
       			set runmode to 9.
       		}
    }

    else if runmode = 9{
    	if ALT:RADAR < 4500 {
    		stage.
    		unlock steering.
    		set runmode to 10.
    	}
    }

    else if runmode = 10{
    	if ALT:RADAR < 2500 {
    		stage.
    		set runmode to 0.
    	}
    }

    //Housekeeping
    if stage:Liquidfuel < 1 and fuel < 2 { //Stage if the stage is out of fuel
        lock throttle to 0.
        wait 2.
        stage.
        set fuel to fuel+1.
        wait 3.
        lock throttle to TVAL.
    }

    set finalTVAL to TVAL.
    lock throttle to finalTVAL. //Write our planned throttle to the physical throttle
    
}

 

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...