Jump to content

Cantab Learns Python with KSP and kRPC.


cantab

Recommended Posts

Time to fly rockets with kRPC and Python. I know very little Python and am hoping this will be a fun way of learning the basics. Like how when I was a kid at school and we'd write programs to make the turtle drive around, only with rockets.

In future I will make this opening post prettier and more detailed and so on. I just want to get the thread started now

My rules:

All flight of unmanned vehicles, and most flight of manned vehicles, to be conducted using kRPC. Manual control inputs to be kept to a minimum.

To focus on the Python coding, all rockets to be 'off the shelf' - the game's stock craft, craft from KerbalX or this forum, etc. Light non-structural modifications, for example changing science equipment, is allowed.

Rossum Program

The Rossum Program will be my first steps.

Link to comment
Share on other sites

Rossum 1

Rocket: Jumping Flea (Stock)

For this I simply typed in commands to python interactively. There is nothing fancy in the slightest, but it demonstrates the system works.

thomas@spelvia:~$ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import krpc
>>> conn = krpc.connect(name='Connection 1')>>> vessel = conn.space_center.active_vessel
>>> vessel.control.sas = true
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined

Whoops! Now I learn Python is case-sensitive.

>>> vessel.control.sas = True
>>> vessel.control.activate_next_stage()
[]

And we have liftoff! Without ever touching the spacebar in Kerbal itself. Now I waited until the rocket reached apoapsis, then

>>> vessel.control.activate_next_stage()
[]
>>> vessel.control.sas = False
>>> 

Activate the next stage, which is the parachute, and turn SAS back off so it doesn't fight the aerodynamics. After a safe landing, recovered the vessel manually.

So of course this was really really basic. I can improve this by triggering the next stage automatically at a suitable moment, and also look at running the science experiments.

Link to comment
Share on other sites

Rossum 2

Rocket: Jumping Flea

Rossum 2 running science

The mission is much the same as before, flying straight up using SAS then opening parachutes when we reach our highest point, but this time it will be fully automated from launch to landing. We'll also run the science experiments. I'm playing with all parts unlocked but I still like collecting science, it's a way to measure my progress in exploring the system.

As far as the python code goes, we make use of a couple of loops. Python makes it very easy to loop over all the elements of a list.

The documentation provided with kRPC is excellent, it's made the code easy to write even as a real novice.

To the extent possible under law, I waive all copyright and related or neighboring rights to the Python code in this post. This work is published from the United Kingdom. https://creativecommons.org/publicdomain/zero/1.0/

# Get the basics set up and the vessel ready for launch
import time
import krpc
conn = krpc.connect(name='Rossum 2')
vessel = conn.space_center.active_vessel
vessel.control.sas = True
vessel.control.throttle = 1

# launch!
vessel.control.activate_next_stage()

# wait until we reach our highest point and begin descending
# this is an inefficient way to do this, using a stream would be better
while vessel.flight(vessel.orbit.body.reference_frame).vertical_speed > 0:
 time.sleep(1)

# turn SAS off and open the chutes
vessel.control.sas = False
vessel.control.activate_next_stage()

# run science experiment on each part with one
for part in vessel.parts.with_module('ModuleScienceExperiment'):
 part.experiment.run()

 

Link to comment
Share on other sites

This is a fantastic thread!  I've been thinking about doing something like this with videos - showing the basics of using KRPC and python.   I'm so glad you're posting these reports!  Keep it up!  I'll point other KRPC beginners to this as a resource.

 

Link to comment
Share on other sites

  • 2 weeks later...

Ahem, I've been a bit of a slowpoke.

Rossum 3

Rocket: Modified "Science Jr". Extra science, chutes, batteries, and windproof antenna added. Boosters removed and upper stage short-fuelled.

Our rocket for suborbital flights

This time we'll be making a series of suborbital flights in a multistage rocket and conducting science experiments automatically during the flight. The code demonstrates the use of a function to perform a series of actions. It also shows the use of kRPC's built-in autopilot feature. And there are a bunch of print() functions to put diagnostic information on the command line. The flight path is crude, it's controlled by manually changing the hardcoded numbers in the script between flights, and the way science is handled is not ideal. But it works. Up to nearly 250 science in the save now.

I don't fully understand why part.experiment.data returns a list. That was the tricky bit of the API to understand for me, doesn't an experiment only have one piece of data? Or are there some that contain multiple?

To the extent possible under law, I waive all copyright and related or neighboring rights to the Python code in this post. This work is published from the United Kingdom. https://creativecommons.org/publicdomain/zero/1.0/

import time
import krpc

# First we check the science we have and decide if it wants transmitting or dumping
# THEN we run experiments
# This might seem backwards but there's a simple reason - part.experiment.run() returns instantly
# but the experiment actually takes time to run
# and I don't wish to do a guesswork sleep command

def doscience(vessel):
  for part in vessel.parts.with_module('ModuleScienceExperiment'):
   # it throws an exception if the experiment already has data
   for data in part.experiment.data:
    print("Handling", part.title)
    if data.transmit_value > 0.1:
     print("Transmitting", part.title, "for", data.transmit_value)
     part.experiment.transmit()
    elif data.science_value < 0.1:
     print("Dumping", part.title, "for", data.science_value)
     part.experiment.dump()
   if part.experiment.has_data == False and part.experiment.inoperable == False:
    print("Running", part.title)
    part.experiment.run()

#basic setup stuff
conn = krpc.connect(name='Rossum 3')
vessel = conn.space_center.active_vessel
vessel.control.sas = True
vessel.control.throttle = 1

prevbiome = vessel.biome
prevsituation = vessel.situation

#can't hurt to see what there is on the pad :)
doscience(vessel)

# launch!
vessel.control.activate_next_stage()

# go straight up for a bit
while vessel.flight().mean_altitude < 2500:
 time.sleep(1)

# set autopilot to pitch over
vessel.control.sas = False
vessel.auto_pilot.target_pitch_and_heading(60, 270)
vessel.auto_pilot.engage()

# 'main loop'
# first fly the rocket! Just stage when thrust is zero.
# that only works for simple serial staged rockets
# Then do the science if the biome or situation have changed

while True:
 if vessel.thrust == 0 and vessel.control.current_stage != 0:
  vessel.control.activate_next_stage()
 if vessel.biome != prevbiome or vessel.situation != prevsituation:
  print(vessel.biome, vessel.situation)
  doscience(vessel)
  prevbiome = vessel.biome
  prevsituation = vessel.situation
 time.sleep(1)

Next time will be a big milestone - I'll be writing my first script to launch to orbit.

Link to comment
Share on other sites

I think I will have to try something similar to this.  I've been meaning to learn Python but I can't motivate myself to start because I can't think of any fun project to do.  Automating rocket launches in ksp will be just the ticket. Fantastic thread, looking forward to more!

Link to comment
Share on other sites

  • 4 weeks later...

Nice! Also, sort of off topic, but how do you get the weird code windows you can scroll in? I've been on the forum for 1.5 years now and I never found out how to do that.

Also, this could turn out to be very interesting! I've followed this.

I wonder how much code would be needed for a Mun mission...

Link to comment
Share on other sites

The code tags!   On the markup/formatting bar click the <> button and that will pop up a window to type your code into, and you can even tell it what language to get it to color it correctly if it actually is code!

 

And a fully automated mun mission wouldn't be trivial, but it's certainly doable.  I think almost everything you need to accomplish it is in my version of the library repository - https://github.com/artwhaley/krpc-library/tree/master/Art_Whaleys_KRPC_Demos

There's a launch script that's self explanatory,

Then in the rendezvous.py file you'll find methods for a hohmann transfer - they'll have to be recoded because I think they intercept a vessel only, but swapping the target_vessel for target_body ought to be just about the extent of it.    This would work fine for giving you a rough Transmunar Injection Burn.

Then you'd enter munar SOI and have to write a bit of code to burn radial + or - to adjust periapsis.

Then you'd circularize at periapsis (similar to how it's done in the launch script at apoapsis)

Then there's an automated landing script in the folder that handles reasonably efficient landings on vacuum bodies!

 

If I ever finish the code for the KRPC mechjeb service, it's WAY easier.   When I had that hacked together without reflection, it was about 20 lines of code to launch and transfer and land on the mun... because you were just feeding parameters to mechjeb an then activating the autopilots.

Link to comment
Share on other sites

  • 6 months later...
This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...