From 7c8de229c41b5ba3bd92a17a529a8bb0a69a70c4 Mon Sep 17 00:00:00 2001 From: Carson Johnson Date: Sat, 1 Nov 2025 23:19:02 -0400 Subject: [PATCH] Fix Python format string issues and add telemetry improvements - Escaped curly braces in audit.txt prompt template to prevent KeyError - Escaped curly braces in flight_template.txt to prevent format string errors - Enhanced JSON parsing in json_utils.py with better error handling - Added telemetry_collector.py with graceful FAR property handling - Added kosmos.py with soft reset mode and exception debugging - Added MechJeb and kRPC documentation prompts - Updated flight.py to use new flight template These changes fix multiple runtime errors that were preventing missions from executing. --- kosmos/agents/flight.py | 493 ++- kosmos/kosmos.py | 457 +++ kosmos/prompts/audit.txt | 160 + kosmos/prompts/flight_template.txt | 98 +- kosmos/prompts/krpc_readmellm.txt | 4178 ++++++++++++++++++++++++++ kosmos/prompts/mechjeb_readmellm.txt | 3349 +++++++++++++++++++++ kosmos/utils/json_utils.py | 271 ++ kosmos/utils/telemetry_collector.py | 626 ++++ 8 files changed, 9567 insertions(+), 65 deletions(-) create mode 100644 kosmos/kosmos.py create mode 100644 kosmos/prompts/audit.txt create mode 100644 kosmos/prompts/krpc_readmellm.txt create mode 100644 kosmos/prompts/mechjeb_readmellm.txt create mode 100644 kosmos/utils/telemetry_collector.py diff --git a/kosmos/agents/flight.py b/kosmos/agents/flight.py index ff5052c..b625c3a 100644 --- a/kosmos/agents/flight.py +++ b/kosmos/agents/flight.py @@ -1,21 +1,22 @@ import ast +import os import re import time +import json import kosmos.utils as U -from langchain_openai import ChatOpenAI -from langchain.prompts import SystemMessagePromptTemplate -from langchain.prompts import AIMessage, HumanMessage, SystemMessage +from langchain_anthropic import ChatAnthropic +from langchain_core.prompts import SystemMessagePromptTemplate +from langchain_core.messages import AIMessage, HumanMessage, SystemMessage from kosmos.prompts import load_prompt -from kosmos.control_primitives_context import load_control_primitives_context class FlightAgent: def __init__( self, - model_name="gpt-4o", + model_name="claude-haiku-4-5-20251001", temperature=0, - request_timeout=120, + request_timeout=300, checkpoint_dir="checkpoint", chat_log=True, execution_error=True, @@ -24,38 +25,112 @@ def __init__( self.chat_log = chat_log self.execution_error = execution_error U.f_mkdir(f"{checkpoint_dir}/action") - self.llm = ChatOpenAI( - model_name=model_name, + self.llm = ChatAnthropic( + model=model_name, temperature=temperature, - request_timeout=request_timeout, + timeout=request_timeout, + api_key=os.getenv("ANTHROPIC"), ) + print(f"🔍 DEBUG: FlightAgent initialized with model={model_name}, temp={temperature}, timeout={request_timeout}") - def construct_system_message(self, skills=[]): - system_template = load_prompt("action_template") - base_skills = [ - # load control primitives - ] - programs = "\n\n".join(load_control_primitives_context(base_skills) + skills) - response_format = load_prompt("action_response_format") + def get_vessel_telemetry(self, env=None): + """Render vessel observation using actual KSP telemetry""" + if env and hasattr(env, 'get_vessel_telemetry'): + try: + telemetry = env.get_vessel_telemetry() + return { + "vessel_name": telemetry.get("vessel_name", "Unknown"), + "situation": telemetry.get("vessel_situation", "Unknown"), + "altitude": telemetry.get("altitude", 0), + "mission_status": "Active" + } + except Exception as e: + print(f"Warning: Could not get vessel telemetry: {e}") + + # Fallback to basic observation + return { + "vessel_name": "Retriever A1", + "situation": "In Flight", + "altitude": 0, + "mission_status": "Active" + } + + def construct_system_message(self, maneuvers=[]): + print(f"🔍 DEBUG: FlightAgent constructing system message with {len(maneuvers)} maneuvers") + system_template = load_prompt("new_flight_template") + # Load MechJeb documentation + mechjeb_docs = load_prompt("mechjeb_readmellm") + # Load kRPC documentation + krpc_docs = load_prompt("krpc_readmellm") + # TODO: Add control primitives later - for now using maneuvers only + programs = "\n\n".join(maneuvers) + response_format = load_prompt("flight_response_format") system_message_prompt = SystemMessagePromptTemplate.from_template( system_template ) system_message = system_message_prompt.format( - programs=programs, response_format=response_format + mechjeb_docs=mechjeb_docs, krpc_docs=krpc_docs, programs=programs, response_format=response_format ) assert isinstance(system_message, SystemMessage) + print(f"🔍 DEBUG: FlightAgent system message constructed, length={len(system_message.content)} chars") return system_message def construct_human_message(self, *, events, code="", task="", context="", audit=""): + print(f"🔍 DEBUG: FlightAgent constructing human message - task='{task[:50]}...', context='{context[:50]}...', audit='{audit[:50]}...'") chat_messages = [] error_messages = [] - assert events[-1][0] == "observe", "Last event must be observe" - for i, (event_type, event) in enumerate(events): - # Process events here - placeholder for now - pass + + # Handle both observe and error events + last_event = events[-1] + if isinstance(last_event, tuple) and len(last_event) > 1: + event_type, event = last_event + else: + event_type, event = "observe", last_event + + if event_type == "error": + print(f"🔍 DEBUG: FlightAgent detected error event: {event.get('execution_error', 'Unknown error')}") + + # Extract error events and chat messages from events + for evt_tuple in events: + try: + if isinstance(evt_tuple, tuple) and len(evt_tuple) > 1: + evt_type, evt_data = evt_tuple + else: + evt_type, evt_data = "observe", evt_tuple + + if evt_type == "error" and isinstance(evt_data, dict): + error_msg = evt_data.get('execution_error', 'Unknown error') + error_type = evt_data.get('exception_type', 'Exception') + error_messages.append(f"{error_type}: {error_msg}") + elif evt_type == "onChat" and isinstance(evt_data, dict) and "onChat" in evt_data: + chat_messages.append(evt_data["onChat"]) + except (TypeError, AttributeError, KeyError) as e: + print(f"🔍 DEBUG: Error processing event: {e}") + continue observation = "" + # PRIORITY: Show errors and audit critique prominently at the top + if error_messages: + observation += "=" * 80 + "\n" + observation += "🚨 EXECUTION ERRORS - ACTION REQUIRED 🚨\n" + observation += "=" * 80 + "\n\n" + for i, error_msg in enumerate(error_messages, 1): + observation += f"ERROR {i}: {error_msg}\n\n" + observation += "=" * 80 + "\n\n" + + # Show audit critique prominently right after errors (or at top if no errors) + if audit: + observation += "=" * 80 + "\n" + observation += "📋 AUDIT AGENT CRITIQUE & GUIDANCE 📋\n" + observation += "=" * 80 + "\n\n" + observation += f"{audit}\n\n" + observation += "=" * 80 + "\n\n" + elif error_messages: + # If there were errors but no audit yet, note that + observation += "⚠️ Note: Audit Agent is analyzing the errors above. Please wait for critique.\n\n" + observation += "=" * 80 + "\n\n" + if code: observation += f"Code from the last round:\n{code}\n\n" else: @@ -63,10 +138,10 @@ def construct_human_message(self, *, events, code="", task="", context="", audit if self.execution_error: if error_messages: - error = "\n".join(error_messages) - observation += f"Execution error:\n{error}\n\n" + # Errors already shown above, just add a note + observation += f"Execution status: ERRORS occurred (see above)\n\n" else: - observation += f"Execution error: No error\n\n" + observation += f"Execution status: No execution errors\n\n" if self.chat_log: if chat_messages: @@ -75,7 +150,192 @@ def construct_human_message(self, *, events, code="", task="", context="", audit else: observation += f"Chat log: None\n\n" - # FIXME: add all the game telemetry to the observation + # Add game telemetry to the observation + # Try to get telemetry from the last observe event, or from error event if it contains telemetry + telemetry = None + telemetry_event = None + + # Look for the last observe event + for event_tuple in reversed(events): + if isinstance(event_tuple, tuple) and len(event_tuple) > 1: + evt_type, evt_data = event_tuple + else: + evt_type, evt_data = "observe", event_tuple + + if evt_type == "observe" and isinstance(evt_data, dict): + telemetry = evt_data + telemetry_event = event_tuple + break + elif evt_type == "error" and isinstance(evt_data, dict) and 'vessel_status' in evt_data: + # Error events may contain telemetry data + telemetry = evt_data + telemetry_event = event_tuple + break + + if telemetry: + comprehensive = telemetry.get('comprehensive_telemetry', {}) + + observation += f"Vessel Telemetry:\n" + observation += f" Vessel: {telemetry.get('vessel_name', 'Unknown')} ({telemetry.get('vessel_type', 'Unknown')})\n" + observation += f" Situation: {telemetry.get('vessel_situation', 'Unknown')}\n" + observation += f" Mission Time: {telemetry.get('mission_time', 0):.1f}s\n" + observation += f" Current Body: {telemetry.get('current_body', 'Unknown')}\n" + + # Position and velocity (use comprehensive data if available) + if 'position' in telemetry: + pos = telemetry['position'] + observation += f" Position: ({pos.get('x', 0):.1f}, {pos.get('y', 0):.1f}, {pos.get('z', 0):.1f})\n" + + if 'velocity' in telemetry: + vel = telemetry['velocity'] + observation += f" Velocity: ({vel.get('x', 0):.1f}, {vel.get('y', 0):.1f}, {vel.get('z', 0):.1f})\n" + + # Altitude and speed (use comprehensive data if available) + altitude = telemetry.get('altitude', 0) + if comprehensive.get('altitude_location', {}).get('mean_altitude'): + altitude = comprehensive['altitude_location']['mean_altitude'] + observation += f" Altitude: {altitude:.1f}m" + if comprehensive.get('altitude_location', {}).get('surface_altitude') is not None: + observation += f" (Surface: {comprehensive['altitude_location']['surface_altitude']:.1f}m)" + observation += "\n" + + speed = telemetry.get('speed', 0) + if comprehensive.get('position_velocity', {}).get('speed'): + speed = comprehensive['position_velocity']['speed'] + observation += f" Speed: {speed:.1f}m/s" + if comprehensive.get('position_velocity', {}).get('vertical_speed') is not None: + observation += f" (Vertical: {comprehensive['position_velocity']['vertical_speed']:.1f}m/s)" + if comprehensive.get('position_velocity', {}).get('horizontal_speed') is not None: + observation += f" (Horizontal: {comprehensive['position_velocity']['horizontal_speed']:.1f}m/s)" + observation += "\n" + + # G-Force (from comprehensive telemetry) + g_force = telemetry.get('g_force', 0) + if comprehensive.get('flight_dynamics', {}).get('g_force') is not None: + g_force = comprehensive['flight_dynamics']['g_force'] + observation += f" G-Force: {g_force:.2f}g\n" + + # Orbit parameters + if 'orbit_parameters' in telemetry: + orbit = telemetry['orbit_parameters'] + observation += f" Orbit: Apoapsis {orbit.get('apoapsis_altitude', 0):.0f}m, Periapsis {orbit.get('periapsis_altitude', 0):.0f}m\n" + observation += f" Inclination: {orbit.get('inclination', 0):.1f}°, Eccentricity: {orbit.get('eccentricity', 0):.3f}\n" + # Use comprehensive orbital data if available + if comprehensive.get('orbital'): + orb_data = comprehensive['orbital'] + if orb_data.get('period'): + observation += f" Period: {orb_data['period']:.0f}s" + if orb_data.get('time_to_apoapsis') is not None: + observation += f", Time to Apoapsis: {orb_data['time_to_apoapsis']:.0f}s" + observation += "\n" + + # Resources (fuel, etc.) - use comprehensive data + if 'resources' in telemetry: + resources = telemetry['resources'] + # Also check comprehensive resources + comp_resources = comprehensive.get('resources', {}) + all_resources = {**resources} + for name, data in comp_resources.items(): + if name not in all_resources: + all_resources[name] = {'amount': data.get('amount', 0), 'max': data.get('max', 0)} + + fuel_resources = {k: v for k, v in all_resources.items() + if 'fuel' in k.lower() or 'oxidizer' in k.lower() or 'electric' in k.lower()} + if fuel_resources: + observation += f" Resources:\n" + for name, data in fuel_resources.items(): + amount = data.get('amount', 0) if isinstance(data, dict) else 0 + max_amount = data.get('max', 0) if isinstance(data, dict) else 0 + percentage = (amount / max_amount * 100) if max_amount > 0 else 0 + observation += f" {name}: {amount:.1f}/{max_amount:.1f} ({percentage:.1f}%)\n" + + # Vessel status - use comprehensive data + if 'vessel_status' in telemetry: + status = telemetry['vessel_status'] + basic_vessel = comprehensive.get('basic_vessel', {}) + performance = comprehensive.get('performance', {}) + + mass = status.get('mass', basic_vessel.get('mass', 0)) + observation += f" Mass: {mass:.1f}t" + if basic_vessel.get('dry_mass'): + observation += f" (Dry: {basic_vessel['dry_mass']:.1f}t)" + observation += "\n" + + thrust = status.get('thrust', performance.get('thrust', 0)) + max_thrust = status.get('max_thrust', performance.get('max_thrust', 0)) + observation += f" Thrust: {thrust:.1f}N (Available: {max_thrust:.1f}N)\n" + + if performance.get('specific_impulse'): + observation += f" ISP: {performance['specific_impulse']:.1f}s\n" + + if 'control_state' in status: + control = status['control_state'] + # Use comprehensive control data if available + comp_control = comprehensive.get('control', {}) + observation += f" Control: Throttle {comp_control.get('throttle', control.get('throttle', 0)):.2f}" + observation += f", SAS {comp_control.get('sas', control.get('sas', False))}" + observation += f", RCS {comp_control.get('rcs', control.get('rcs', False))}\n" + + if comp_control.get('gear') is not None: + observation += f" Gear: {comp_control['gear']}" + if comp_control.get('lights') is not None: + observation += f", Lights: {comp_control['lights']}" + if comp_control.get('brakes') is not None: + observation += f", Brakes: {comp_control['brakes']}" + observation += "\n" + + # Orientation data from comprehensive telemetry + orientation = comprehensive.get('orientation', {}) + if orientation: + observation += f" Orientation: Heading {orientation.get('heading', 0):.1f}°, " + observation += f"Pitch {orientation.get('pitch', 0):.1f}°, " + observation += f"Roll {orientation.get('roll', 0):.1f}°\n" + + # Autopilot status from comprehensive telemetry + autopilot = comprehensive.get('autopilot', {}) + if autopilot.get('engaged'): + observation += f" Autopilot: Engaged, Error: {autopilot.get('error', 0):.2f}°\n" + if autopilot.get('target_pitch') is not None: + observation += f" Target Pitch: {autopilot['target_pitch']:.1f}°, " + if autopilot.get('target_heading') is not None: + observation += f"Target Heading: {autopilot['target_heading']:.1f}°\n" + + # MechJeb status + if 'mechjeb_status' in telemetry: + mj = telemetry['mechjeb_status'] + if mj.get('api_ready'): + observation += f" MechJeb: API Ready, Status: {mj.get('ascent_status', 'Unknown')}\n" + + # MechJeb comprehensive data + mechjeb = comprehensive.get('mechjeb', {}) + if mechjeb.get('available') and mechjeb.get('api_ready'): + if mechjeb.get('ascent_autopilot', {}).get('enabled'): + ascent = mechjeb['ascent_autopilot'] + observation += f" MechJeb Ascent: {ascent.get('status', 'Unknown')}, " + observation += f"Target Alt: {ascent.get('desired_orbit_altitude', 0):.0f}m\n" + + # Staging info + if 'part_status' in telemetry: + parts = telemetry['part_status'] + observation += f" Parts: {parts.get('part_count', 0)} total, Stage {parts.get('current_stage', 0)}" + if parts.get('stage_count'): + observation += f" ({parts['stage_count']} parts)" + observation += "\n" + + # Nearby vessels + if 'nearby_vessels' in telemetry and telemetry['nearby_vessels']: + observation += f" Nearby Vessels:\n" + for vessel in telemetry['nearby_vessels'][:3]: # Show top 3 + observation += f" {vessel.get('name', 'Unknown')}: {vessel.get('distance', 0):.0f}m ({vessel.get('situation', 'Unknown')})\n" + + # Execution time + if 'execution_time' in telemetry: + observation += f" Execution Time: {telemetry.get('execution_time', 0):.3f}s\n" + + observation += "\n" + else: + # No telemetry available (shouldn't happen normally, but handle gracefully) + observation += "Vessel Telemetry: No telemetry data available\n\n" observation += f"Task: {task}\n\n" @@ -83,26 +343,51 @@ def construct_human_message(self, *, events, code="", task="", context="", audit observation += f"Context: {context}\n\n" else: observation += f"Context: None\n\n" + + # Add reminder about errors/critique if present (already shown above, but include summary) + if error_messages or audit: + observation += "=" * 80 + "\n" + observation += "📌 REMINDER: Review the errors and critique above, then fix your code accordingly.\n" + observation += "=" * 80 + "\n\n" - if audit: - observation += f"Audit: {audit}\n\n" - else: - observation += f"Critique: None\n\n" - + print(f"🔍 DEBUG: FlightAgent human message constructed, length={len(observation)} chars") return HumanMessage(content=observation) + def call_llm(self, messages): + print(f"🔍 DEBUG: FlightAgent calling LLM with {len(messages)} messages") + print(f"🔍 DEBUG: FlightAgent system message preview: {messages[0].content[:200]}...") + print(f"🔍 DEBUG: FlightAgent human message preview: {messages[1].content[:200]}...") + + try: + response = self.llm.invoke(messages) + print(f"🔍 DEBUG: FlightAgent LLM response received, length={len(response.content)} chars") + print(f"🔍 DEBUG: FlightAgent LLM response preview: {response.content[:300]}...") + return response + except Exception as e: + print(f"🔍 ERROR: FlightAgent LLM call failed: {e}") + raise + def process_ai_message(self, message): + print(f"🔍 DEBUG: FlightAgent processing AI message, length={len(message.content)} chars") assert isinstance(message, AIMessage) retry = 3 error = None while retry > 0: try: + print(f"🔍 DEBUG: FlightAgent parsing attempt {4-retry}, extracting code from message") code_pattern = re.compile(r"```(?:python|py)(.*?)```", re.DOTALL) code = "\n".join(code_pattern.findall(message.content)) + print(f"🔍 DEBUG: FlightAgent extracted code length: {len(code)} chars") + if code: + print(f"🔍 DEBUG: FlightAgent code preview: {code[:200]}...") + else: + print("🔍 WARNING: FlightAgent no code found in message") + parsed = ast.parse(code) functions = [] assert len(parsed.body) > 0, "No functions found" + print(f"🔍 DEBUG: FlightAgent found {len(parsed.body)} AST nodes") for node in parsed.body: if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): @@ -117,29 +402,57 @@ def process_ai_message(self, message): # Get function source code (simplified - in practice you might want to use ast.unparse) functions.append({ - "name": node.id.name, + "name": node.name, "type": node_type, "body": ast.unparse(node), "params": params, }) - # Find the last async function + # Find the last function (prefer regular functions over async) main_function = None for function in reversed(functions): - if function["type"] == "AsyncFunctionDef": + if function["type"] == "FunctionDef": main_function = function break + # If no regular function found, look for async function + if main_function is None: + for function in reversed(functions): + if function["type"] == "AsyncFunctionDef": + main_function = function + break + + print(f"🔍 DEBUG: FlightAgent found {len(functions)} functions, main_function: {main_function['name'] if main_function else 'None'}") + assert ( main_function is not None - ), "No async function found. Your main function must be async." - assert ( - len(main_function["params"]) == 1 - and main_function["params"][0] == "bot" - ), f"Main function {main_function['name']} must take a single argument named 'bot'" + ), "No function found. Your code must contain at least one function." + # Functions can have any parameters - they'll use the execution context directly program_code = "\n\n".join(function["body"] for function in functions) - exec_code = f"await {main_function['name']}(bot)" + # Call the function with the correct parameters based on what it expects + if len(main_function['params']) == 1: + if main_function['params'][0] == 'mech_jeb': + exec_code = f"{main_function['name']}(mech_jeb)" + else: + exec_code = f"{main_function['name']}(conn)" + elif len(main_function['params']) == 2: + if 'mech_jeb' in main_function['params']: + if main_function['params'] == ['conn', 'mech_jeb']: + exec_code = f"{main_function['name']}(conn, mech_jeb)" + elif main_function['params'] == ['mech_jeb', 'vessel']: + exec_code = f"{main_function['name']}(mech_jeb, vessel)" + else: + exec_code = f"{main_function['name']}(conn, vessel)" + else: + exec_code = f"{main_function['name']}(conn, vessel)" + elif len(main_function['params']) == 3: + exec_code = f"{main_function['name']}(conn, vessel, mech_jeb)" + else: + # Default to conn, vessel for backward compatibility + exec_code = f"{main_function['name']}(conn, vessel)" + + print(f"🔍 DEBUG: FlightAgent successfully parsed code - program_name: {main_function['name']}, exec_code: {exec_code}") return { "program_code": program_code, @@ -149,9 +462,111 @@ def process_ai_message(self, message): except Exception as e: retry -= 1 error = e + print(f"🔍 ERROR: FlightAgent parsing failed (attempt {4-retry}): {e}") time.sleep(1) + print(f"🔍 ERROR: FlightAgent failed to parse after all retries: {error}") return f"Error parsing action response (before program execution): {error}" + def update_vessel_memory(self, vessel_status): + print(f"🔍 DEBUG: FlightAgent updating vessel memory with status keys: {list(vessel_status.keys()) if vessel_status else 'None'}") + # This method is called from kosmos.py but not implemented yet + # Placeholder for future vessel memory functionality + pass + + def render_vessel_observation(self, events=None): + """Render vessel observation from telemetry events.""" + print("🔍 DEBUG: FlightAgent rendering vessel observation") + + if not events: + return "No telemetry available" + + try: + # Get the latest telemetry event + last_event = events[-1] + if isinstance(last_event, tuple) and len(last_event) > 1: + event_type, event = last_event + else: + event_type, event = "observe", last_event + + # Check if event is None or not a dict + if event is None: + return "No telemetry data available" + + if not isinstance(event, dict): + return f"Invalid telemetry data type: {type(event).__name__}" + + if event_type != "observe": + return f"Event type: {event_type} (not observing)" + + # Extract comprehensive telemetry if available (safely) + comprehensive = event.get("comprehensive_telemetry") if isinstance(event, dict) else {} + if comprehensive is None: + comprehensive = {} + except (IndexError, TypeError, AttributeError) as e: + print(f"🔍 DEBUG: Error extracting telemetry from events: {e}") + return f"Error extracting telemetry: {type(e).__name__}" + + # Build a summary of key vessel state + observation_parts = [] + + # Basic vessel info + vessel_name = event.get("vessel_name", "Unknown") + situation = event.get("vessel_situation", "Unknown") + observation_parts.append(f"Vessel: {vessel_name} ({situation})") + + # Position and motion (with null checks) + if 'position' in event and isinstance(event.get('position'), dict): + pos = event['position'] + observation_parts.append(f"Position: ({pos.get('x', 0):.1f}, {pos.get('y', 0):.1f}, {pos.get('z', 0):.1f})") + + if 'velocity' in event and isinstance(event.get('velocity'), dict): + vel = event['velocity'] + observation_parts.append(f"Velocity: ({vel.get('x', 0):.1f}, {vel.get('y', 0):.1f}, {vel.get('z', 0):.1f})") + + observation_parts.append(f"Altitude: {event.get('altitude', 0):.1f}m, Speed: {event.get('speed', 0):.1f}m/s") + + # Orbital state (with null checks) + orbit_params = event.get('orbit_parameters') + if orbit_params and isinstance(orbit_params, dict): + observation_parts.append(f"Orbit: Ap {orbit_params.get('apoapsis_altitude', 0):.0f}m, Pe {orbit_params.get('periapsis_altitude', 0):.0f}m") + + # Control state (with null checks) + vessel_status = event.get('vessel_status') + if vessel_status and isinstance(vessel_status, dict): + control_state = vessel_status.get('control_state') + if control_state and isinstance(control_state, dict): + observation_parts.append(f"Control: Throttle {control_state.get('throttle', 0):.2f}, SAS {control_state.get('sas', False)}, RCS {control_state.get('rcs', False)}") + + # MechJeb status if available (with null checks) + mechjeb_status = event.get('mechjeb_status') + if mechjeb_status and isinstance(mechjeb_status, dict): + if mechjeb_status.get('api_ready', False): + observation_parts.append(f"MechJeb: API Ready, Status: {mechjeb_status.get('ascent_status', 'Unknown')}") + + # Resources summary (with null checks) + resources = event.get('resources') + if resources and isinstance(resources, dict): + fuel_info = [] + for name in ['LiquidFuel', 'Oxidizer', 'ElectricCharge']: + if name in resources: + resource_data = resources[name] + if isinstance(resource_data, dict): + amt = resource_data.get('amount', 0) + max_amt = resource_data.get('max', 0) + if max_amt > 0: + pct = (amt / max_amt) * 100 + fuel_info.append(f"{name}: {pct:.1f}%") + if fuel_info: + observation_parts.append(f"Resources: {', '.join(fuel_info)}") + + return "\n".join(observation_parts) + + def summarize_telemetry_log(self, telemetry): + print(f"🔍 DEBUG: FlightAgent summarizing telemetry log with {len(telemetry)} events") + # This method is called from kosmos.py but not implemented yet + # Placeholder for future telemetry summarization + return "Telemetry summary placeholder" + def summarize_chatlog(self, events): chatlog = set() for event_type, event in events: diff --git a/kosmos/kosmos.py b/kosmos/kosmos.py new file mode 100644 index 0000000..e9009d6 --- /dev/null +++ b/kosmos/kosmos.py @@ -0,0 +1,457 @@ +import copy +import json +import os +from pickle import FALSE +import time +from typing import Dict + +import kosmos.utils as U +from kosmos.utils.debug_utils import create_debug_logger +from .env import KSPEnv + +from .agents import FlightAgent, AuditAgent, MissionControlAgent, ManeuverAgent + +class Kosmos: + def __init__( + self, + krpc_address: str = "127.0.0.1", + krpc_rpc_port: int = 50000, + krpc_stream_port: int = 50001, + openai_api_key: str = None, + anthropic_api_key: str = None, + env_wait_time: float = 1.0, + env_request_timeout: float = 120, + max_iterations: int = 160, + reset_vessel_if_failed: bool = False, + initial_mission: str = None, + flight_agent_model_name: str = "claude-haiku-4-5-20251001", + flight_agent_temperature: float = 0, + flight_agent_task_max_retries: int = 4, + flight_agent_show_telemetry_log: bool = True, + flight_agent_show_execution_error: bool = True, + mission_control_agent_model_name: str = "gpt-4o", + mission_control_agent_temperature: float = 0, + mission_control_agent_qa_model_name: str = "gpt-3.5-turbo", + mission_control_agent_qa_temperature: float = 0, + mission_control_agent_warm_up: Dict[str, int] = None, + mission_control_agent_core_resources: str = r"LiquidFule|Oxidizer|MonoPropellant|EletricCharge|SolidFuel", + mission_control_agent_mode: str = "auto", + audit_agent_model_name: str = "gpt-4o", + audit_agent_temperature: float = 0, + audit_agent_mode: str = "auto", + maneuver_agent_model_name: str = "gpt-3.5-turbo", + maneuver_agent_temperature: float = 0, + maneuver_agent_retrieval_top_k: int = 5, + openai_api_request_timeout: int = 300, + checkpoint_dir: str = "checkpoint", + maneuver_library_dir: str = None, + resume: bool = False, + ): + # Initialize the environment + print("🔍 DEBUG: Initializing KSPEnv...") + self.env = KSPEnv( + krpc_address=krpc_address, + krpc_rpc_port=krpc_rpc_port, + krpc_stream_port=krpc_stream_port, + ) + print("🔍 DEBUG: KSPEnv initialized") + self.env_wait_time = env_wait_time + self.reset_vessel_if_failed = reset_vessel_if_failed + self.max_iterations = max_iterations + + self.initial_mission = initial_mission + + if openai_api_key: + os.environ["OPENAI"] = openai_api_key + else: + print("⚠️ WARNING: No OpenAI API key provided. Set OPENAI_API_KEY environment variable.") + + if anthropic_api_key: + os.environ["ANTHROPIC"] = anthropic_api_key + else: + print("⚠️ WARNING: No Anthropic API key provided. Set ANTHROPIC_API_KEY environment variable.") + + print("🔍 DEBUG: Initializing FlightAgent...") + self.flight_agent = FlightAgent( + model_name=flight_agent_model_name, + temperature=flight_agent_temperature, + request_timeout=openai_api_request_timeout, + checkpoint_dir=checkpoint_dir, + chat_log=flight_agent_show_telemetry_log, + execution_error=flight_agent_show_execution_error, + ) + print("🔍 DEBUG: FlightAgent initialized") + self.flight_agent_task_max_retries = flight_agent_task_max_retries + + print("🔍 DEBUG: Initializing MissionControlAgent...") + self.mission_control_agent = MissionControlAgent( + model_name=mission_control_agent_model_name, + temperature=mission_control_agent_temperature, + qa_model_name=mission_control_agent_qa_model_name, + qa_temperature=mission_control_agent_qa_temperature, + request_timout=openai_api_request_timeout, + ckpt_dir=checkpoint_dir, + resume=resume, + mode=mission_control_agent_mode, + warm_up=mission_control_agent_warm_up, + core_resources=mission_control_agent_core_resources, + ) + print("🔍 DEBUG: MissionControlAgent initialized") + + print("🔍 DEBUG: Initializing AuditAgent...") + self.audit_agent = AuditAgent( + model_name=audit_agent_model_name, + temperature=audit_agent_temperature, + request_timeout=openai_api_request_timeout, + mode=audit_agent_mode, + ) + print("🔍 DEBUG: AuditAgent initialized") + + print("🔍 DEBUG: Initializing ManeuverAgent...") + self.maneuver_agent = ManeuverAgent( + model_name=maneuver_agent_model_name, + temperature=maneuver_agent_temperature, + top_k_vals=maneuver_agent_retrieval_top_k, + timeout_period=openai_api_request_timeout, + checkpoint_dir=checkpoint_dir, + resume=1 if resume or maneuver_library_dir else 0, + ) + print("🔍 DEBUG: ManeuverAgent initialized") + + self.recorder = U.EventRecorder(checkpoint_dir=checkpoint_dir) + self.resume = resume + + # Initialize debug logger + self.debug_logger = create_debug_logger("Kosmos") + + # init variables for mission rollout + self.flight_agent_rollout_num_iterations = -1 + self.context = "" + self.messages = None + self.conversations = [] + self.last_events = None + + def reset(self, mission, context="", reset_env=True): + self.flight_agent_rollout_num_iterations = 0 + self.mission = mission + self.context = context + if reset_env: + self.env.reset( + options={ + "mode": "soft", + "wait_time": self.env_wait_time, + } + ) + + # Set time warp and game settings + telemetry = self.env.step( + "conn.space_center.rails_warp_factor = 0\n" + + "conn.space_center.physics_warp_factor = 0\n" + + "print('Time warp disabled, ready for operations')" + ) + + maneuvers = self.maneuver_agent.getManeuvers(query=self.context) + print( + f"Render Flight Agent system message with {len(maneuvers)} skills" + ) + system_message = self.flight_agent.construct_system_message(maneuvers=maneuvers) + human_message = self.flight_agent.construct_human_message( + events=telemetry, code="", task=self.mission, context=context, audit="" + ) + self.messages = [system_message, human_message] + assert len(self.messages) == 2 + self.conversations = [] + return self.messages + + def close(self): + self.env.close() + + def step(self): + self.debug_logger.debug(f"Step method called, iteration: {self.flight_agent_rollout_num_iterations}") + if self.flight_agent_rollout_num_iterations < 0: + raise ValueError("Agent must be reset before stepping") + + self.debug_logger.debug("Calling FlightAgent LLM") + # Add delay to prevent rate limiting + time.sleep(2) + ai_message = self.flight_agent.call_llm(self.messages) + self.debug_logger.debug(f"Flight Agent response received, length: {len(ai_message.content)}") + + self.conversations.append( + (self.messages[0].content, self.messages[1].content, ai_message.content) + ) + parsed_result = self.flight_agent.process_ai_message(message=ai_message) + success = False + if isinstance(parsed_result, dict): + self.debug_logger.debug("Code parsed successfully, executing in environment") + code = parsed_result["program_code"] + "\n" + parsed_result["exec_code"] + + print(f"🔍 DEBUG: Kosmos executing code:") + print(f"🔍 DEBUG: Program code:\n{parsed_result['program_code']}") + print(f"🔍 DEBUG: Exec code: {parsed_result['exec_code']}") + print(f"🔍 DEBUG: Full code to execute:\n{code}") + + telemetry = self.env.step( + code, + programs=self.maneuver_agent.programs, + ) + self.recorder.record(telemetry, self.mission) + self.flight_agent.update_vessel_memory(telemetry[-1][1]["vessel_status"]) + + self.debug_logger.debug(f"Calling Audit Agent for mission: {self.mission}") + # Add delay to prevent rate limiting + time.sleep(1) + success, audit = self.audit_agent.check_mission_success( + events=telemetry, + task=self.mission, + context=self.context, + vessel_observation=self.flight_agent.render_vessel_observation(events=telemetry), + max_retries=5, + ) + self.debug_logger.info(f"Audit Agent Result: Success={success}, Critique='{audit[:100]}...'") + + if self.reset_vessel_if_failed and not success: + vessel_state = [] + for event_type, event in telemetry: + if event_type == "onSave" and "vessel_modified" in event: + vessel_state.append(event["vessel_state"]) + if vessel_state: + new_telemetry = self.env.step( + f"revert_vessel_state(conn, vessel, {U.json_dumps(vessel_state[-1])})", + programs=self.maneuver_agent.programs, + ) + telemetry[-1][1]["vessel_status"] = new_telemetry[-1][1]["vessel_status"] + telemetry[-1][1]["orbit_parameters"] = new_telemetry[-1][1]["orbit_parameters"] + + new_maneuvers = self.maneuver_agent.getManeuvers( + query=self.context + + "\n\n" + + self.flight_agent.summarize_telemetry_log(telemetry) + ) + system_message = self.flight_agent.construct_system_message(maneuvers=new_maneuvers) + human_message = self.flight_agent.construct_human_message( + events=telemetry, + code=parsed_result["program_code"], + task=self.mission, + context=self.context, + audit=audit, + ) + self.last_events = copy.deepcopy(telemetry) + self.messages = [system_message, human_message] + else: + assert isinstance(parsed_result, str) + self.recorder.record([], self.mission) + print(f"{parsed_result} Trying again!") + assert len(self.messages) == 2 + self.flight_agent_rollout_num_iterations += 1 + done = ( + self.flight_agent_rollout_num_iterations >= self.flight_agent_task_max_retries + or success + ) + info = { + "mission": self.mission, + "success": success, + "conversations": self.conversations, + } + if success: + assert ( + "program_code" in parsed_result and "program_name" in parsed_result + ), "program and program_name must be returned when success" + info["program_code"] = parsed_result["program_code"] + info["program_name"] = parsed_result["program_name"] + else: + print( + f"Flight Agent human message\n{self.messages[-1].content}" + ) + return self.messages, 0, done, info + + def rollout(self, *, mission, context, reset_env=FALSE): + print(f"🔍 DEBUG: Rollout started for mission: {mission[:50]}...") + self.reset(mission=mission, context=context, reset_env=reset_env) + print(f"🔍 DEBUG: Reset completed, starting step loop...") + step_count = 0 + while True: + step_count += 1 + print(f"🔍 DEBUG: Rollout step {step_count}") + messages, reward, done, info = self.step() + print(f"🔍 DEBUG: Step {step_count} completed, done: {done}") + if done: + print(f"🔍 DEBUG: Rollout finished after {step_count} steps") + break + return messages, reward, done, info + + def learn(self, reset_env=True, initial_mission=None): + print("🔍 DEBUG: Kosmos.learn() called") + # Use the provided initial_mission if given, otherwise use the one from constructor + if initial_mission is not None: + self.initial_mission = initial_mission + print(f"🔍 DEBUG: Using provided initial_mission: {initial_mission[:100]}...") + elif self.initial_mission: + print(f"🔍 DEBUG: Using constructor initial_mission: {self.initial_mission[:100]}...") + else: + print("🔍 DEBUG: No initial_mission provided") + + # Always use soft reset to avoid disrupting active vessel + # Soft mode continues with whatever vessel is currently active in KSP + print(f"🔍 DEBUG: Performing soft reset (keeping current vessel state)") + self.env.reset( + options={ + "mode": "soft", + "wait_time": self.env_wait_time, + } + ) + self.resume = True + self.last_events = self.env.step("") + + print("🔍 DEBUG: Starting main mission loop...") + while True: + print(f"🔍 DEBUG: Loop iteration {self.recorder.iteration}, max: {self.max_iterations}") + if self.recorder.iteration > self.max_iterations: + print("Mission iteration limit reached") + break + + print(f"\033[35m🎯 Calling Mission Control Agent (Progress: {self.mission_control_agent.progress})\033[0m") + mission, context = self.mission_control_agent.propose_next_mission( + telemetry=self.last_events, + vessel_observation=self.flight_agent.get_vessel_telemetry(env=self.env), + max_retries=5, + initial_mission=self.initial_mission, + ) + print(f"\033[35m🎯 Mission Control Agent Result: Mission='{mission}', Context='{context[:100]}...'\033[0m") + print( + f"Starting mission {mission} for at most {self.flight_agent_task_max_retries} times" + ) + try: + print(f"🔍 DEBUG: Calling rollout for mission: {mission[:50]}...") + messages, reward, done, info = self.rollout( + mission=mission, + context=context, + reset_env=reset_env, + ) + print(f"🔍 DEBUG: Rollout completed, success: {info.get('success', 'unknown')}") + except Exception as e: + # Enhanced error debugging + print(f"\033[31m{'='*70}") + print(f"🔍 EXCEPTION CAUGHT IN LEARN()") + print(f"Exception type: {type(e).__name__}") + print(f"Exception module: {type(e).__module__}") + print(f"Exception str: {str(e)}") + print(f"Exception repr: {repr(e)}") + if hasattr(e, 'args'): + print(f"Exception args: {e.args}") + print(f"{'='*70}\033[0m") + + import traceback + print("\033[31mFull traceback:\033[0m") + traceback.print_exc() + + time.sleep(3) # wait for kRPC connection to stabilize + info = { + "mission": mission, + "success": False, + } + # Safely access telemetry data + last_telemetry_data = {} + if self.last_events and len(self.last_events) > 0: + try: + last_event = self.last_events[-1] + # Handle different event structures + if isinstance(last_event, tuple) and len(last_event) > 1: + event_data = last_event[1] + last_telemetry_data = event_data if isinstance(event_data, dict) else {} + elif isinstance(last_event, dict): + last_telemetry_data = last_event + except (IndexError, TypeError, AttributeError) as te: + print(f"🔍 DEBUG: Error extracting telemetry from last_events: {te}") + last_telemetry_data = {} + + # Ensure all values are dicts, not None + vessel_status = last_telemetry_data.get("vessel_status") if isinstance(last_telemetry_data, dict) else {} + resources = last_telemetry_data.get("resources") if isinstance(last_telemetry_data, dict) else {} + position = last_telemetry_data.get("position") if isinstance(last_telemetry_data, dict) else {} + + # Convert None to empty dict + if not isinstance(vessel_status, dict): + vessel_status = {} + if not isinstance(resources, dict): + resources = {} + if not isinstance(position, dict): + position = {} + + self.last_events = self.env.reset( + options={ + "mode": "soft", + "wait_time": self.env_wait_time, + "vessel_status": vessel_status, + "resources": resources, + "position": position, + } + ) + print("Your last mission rollout terminated due to error:") + print(f"{e}") + + if info["success"]: + # Convert the info dict to the format expected by add_new_maneuver + maneuver_data = { + "code_function_name": info["program_name"], + "code_function_body": info["program_code"] + } + self.maneuver_agent.add_new_maneuver(maneuver_data) + + print(f"\033[33m📊 Updating Mission Control Progress: Success={info['success']}\033[0m") + self.mission_control_agent.update_exploration_progress(info) + print(f"\033[33m📊 Mission Control Progress After Update: {self.mission_control_agent.progress}\033[0m") + print( + f"Completed missions: {', '.join(self.mission_control_agent.completed_missions)}" + ) + print( + f"Failed missions: {', '.join(self.mission_control_agent.failed_missions)}" + ) + return { + "completed_missions": self.mission_control_agent.completed_missions, + "failed_missions": self.mission_control_agent.failed_missions, + "maneuvers": self.maneuver_agent.availablemaneuvers, + } + + def decompose_mission(self, mission): + if not self.last_events: + self.last_events = self.env.reset( + options={ + "mode": "hard", + "wait_time": self.env_wait_time, + } + ) + return self.mission_control_agent.decompose_mission(mission, self.last_events) + + def inference(self, mission=None, sub_missions=[], reset_mode="hard", reset_env=True): + if not mission and not sub_missions: + raise ValueError("Either mission or sub_missions must be provided") + if not sub_missions: + sub_missions = self.decompose_mission(mission) + self.env.reset( + options={ + "mode": reset_mode, + "wait_time": self.env_wait_time, + } + ) + self.mission_control_agent.completed_missions = [] + self.mission_control_agent.failed_missions = [] + self.last_events = self.env.step("") + while self.mission_control_agent.progress < len(sub_missions): + next_mission = sub_missions[self.mission_control_agent.progress] + context = self.mission_control_agent.get_mission_context(next_mission) + print( + f"Starting mission {next_mission} for at most {self.flight_agent_task_max_retries} times" + ) + messages, reward, done, info = self.rollout( + mission=next_mission, + context=context, + reset_env=reset_env, + ) + self.mission_control_agent.update_exploration_progress(info) + print( + f"Completed missions: {', '.join(self.mission_control_agent.completed_missions)}" + ) + print( + f"Failed missions: {', '.join(self.mission_control_agent.failed_missions)}" + ) \ No newline at end of file diff --git a/kosmos/prompts/audit.txt b/kosmos/prompts/audit.txt new file mode 100644 index 0000000..619a558 --- /dev/null +++ b/kosmos/prompts/audit.txt @@ -0,0 +1,160 @@ +You are an assistant that assesses my progress in Kerbal Space Program and provides useful guidance for spaceflight missions. + +You are required to evaluate if I have met the mission requirements. Exceeding the mission requirements is also considered a success while failing to meet them requires you to provide critique to help me improve my spaceflight skills. + +## KRPC MechJeb API Documentation + +{mechjeb_docs} + +I will give you the following information: + +Current body: The celestial body I'm currently near after mission execution. +Mission time: The elapsed mission time in seconds. +Vessel situation: My current vessel situation (landed, orbiting, flying, etc.). +Altitude: My current altitude above sea level or surface. +Orbital parameters: My current orbital characteristics (apoapsis, periapsis, inclination, etc.). +Fuel remaining: My current fuel levels (LiquidFuel, Oxidizer, MonoPropellant). +Battery charge: My current electrical charge level. +Position: My current 3D coordinates. +Velocity: My current velocity vector and speed. +Resources: My vessel's current resource levels and capacities. +Parts: Information about my vessel's parts and staging. +Nearby vessels: Other spacecraft in the vicinity. +Mission: The objective I need to accomplish. +Context: The context and requirements of the mission. + +You should only respond in VALID JSON format as described below: +{{ + "reasoning": "your reasoning here", + "success": true, + "critique": "your critique here" +}} +Ensure the response can be parsed by Python json.loads. Requirements: +- No trailing commas +- Use double quotes, not single quotes +- Boolean values should be true or false (lowercase, not True/False) +- Return ONLY the JSON object, no additional text before or after +- If critique is empty, use empty string "" not null + +Here are some examples: +INPUT: +Current body: Kerbin +Altitude: 85340m +Orbital parameters: {{"apoapsis_altitude": 85340, "periapsis_altitude": 82150, "inclination": 0.2}} + +Mission: Launch to 80km orbit + +RESPONSE: +{{ + "reasoning": "You need to achieve a stable orbit at 80km altitude. Your current orbit has apoapsis at 85km and periapsis at 82km, which exceeds the minimum 80km requirement.", + "success": true, + "critique": "" +}} + +INPUT: +Current body: Kerbin +Altitude: 45000m +Vessel situation: flying +Fuel remaining: {{"LiquidFuel": 180, "Oxidizer": 220}} + +Mission: Launch to 80km orbit + +RESPONSE: +{{ + "reasoning": "You are currently at 45km altitude and still flying, which means you haven't achieved orbit yet. A stable orbit requires reaching at least 80km altitude.", + "success": false, + "critique": "Continue your ascent and perform orbital insertion burn to achieve a stable orbit above 80km altitude. You have sufficient fuel remaining." +}} + +INPUT: +Current body: Mun +Vessel situation: landed +Altitude: 0m + +Mission: Land on the Mun + +RESPONSE: +{{ + "reasoning": "You are currently landed on the Mun's surface, which means you successfully completed the landing mission.", + "success": true, + "critique": "" +}} + +INPUT: +Current body: Kerbin +Orbital parameters: {{"apoapsis_altitude": 250000, "periapsis_altitude": 85000}} +Mission time: 1850.3 + +Mission: Transfer to Mun orbit + +Context: Perform Hohmann transfer to reach Mun's sphere of influence + +RESPONSE: +{{ + "reasoning": "For a Mun transfer, you need to be in Mun's sphere of influence, not Kerbin's. Your high apoapsis suggests you performed a transfer burn, but you're still orbiting Kerbin.", + "success": false, + "critique": "Wait for your spacecraft to reach the Mun's sphere of influence. If the transfer window was missed, perform course correction burns to intercept the Mun." +}} + +INPUT: +Fuel remaining: {{"LiquidFuel": 0, "Oxidizer": 0}} +Vessel situation: landed +Current body: Kerbin + +Mission: Perform emergency landing + +Context: Land safely with minimal fuel + +RESPONSE: +{{ + "reasoning": "You have successfully landed on Kerbin with no fuel remaining, which indicates a successful emergency landing procedure.", + "success": true, + "critique": "" +}} + +INPUT: +Resources: {{"ElectricCharge": {{"amount": 250, "max": 300}}}} +Parts: {{"solar_panels_deployed": true}} + +Mission: Deploy solar panels and recharge + +Context: Recharge batteries using solar power + +RESPONSE: +{{ + "reasoning": "Your solar panels are deployed and you have 250/300 electric charge, which shows successful recharging. The mission is complete.", + "success": true, + "critique": "" +}} + +INPUT: +Current body: Duna +Orbital parameters: {{"apoapsis_altitude": 150000, "periapsis_altitude": 50000}} +Nearby vessels: [{{"name": "Duna Station", "distance": 2500}}] + +Mission: Rendezvous with Duna Station + +Context: Get within 2km of the target vessel + +RESPONSE: +{{ + "reasoning": "You are within 2.5km of Duna Station, which meets the rendezvous requirement of getting within 2km of the target.", + "success": true, + "critique": "" +}} + +INPUT: +Current body: Kerbin +Orbital parameters: {{"inclination": 45.2}} +Fuel remaining: {{"LiquidFuel": 50, "Oxidizer": 60}} + +Mission: Achieve equatorial orbit + +Context: Orbit Kerbin with 0-degree inclination + +RESPONSE: +{{ + "reasoning": "Your current orbital inclination is 45.2 degrees, which is far from the required equatorial orbit (0 degrees). You have some fuel remaining for plane change maneuvers.", + "success": false, + "critique": "Perform plane change maneuvers at the ascending or descending node to reduce your orbital inclination to near 0 degrees. This will require significant delta-v, so plan your burns carefully." +}} \ No newline at end of file diff --git a/kosmos/prompts/flight_template.txt b/kosmos/prompts/flight_template.txt index f13f136..65f1477 100644 --- a/kosmos/prompts/flight_template.txt +++ b/kosmos/prompts/flight_template.txt @@ -1,10 +1,11 @@ -You are a helpful assistant that writes kRPC and MechJeb python code to complete any Kerbel Space Program task specified by me. - -Here are some useful programs written with the kRPC and MechJeb APIs. - +Updated Flight Agent Prompt +You are a helpful assistant that writes MechJeb python code to complete any Kerbal Space Program task specified by me. +KRPC MechJeb API Documentation +{mechjeb_docs} +KRPC API Documentation +{krpc_docs} +Here are some useful programs written with the MechJeb API. {programs} - - At each round of conversation, I will give you Code from the last round: ... Execution error: ... @@ -25,28 +26,73 @@ Resources: ... Task: ... Context: ... Critique: ... - You should then respond to me with -Explain (if applicable): Are there any steps missing in your plan? Why does the code not complete the task? What does the chat log and execution error imply? -Plan: How to complete the task step by step. You should pay attention to to Resources and Part status since they tell what you have available. The task completeness check is also based on your final orbital state and mission objective. +Explain (if applicable): Are there any steps missing in your plan? Why does the code not complete the task? What does the chat log and execution error imply? Pay special attention to any Critique provided - it contains specific guidance on how to fix errors from the previous attempt. +Plan: How to complete the task step by step. You should pay attention to to Resources and Part status since they tell what you have available. The task completeness check is also based on your final orbital state and mission objective. If there was a Critique, incorporate the suggested fixes into your plan. Code: - 1) Write a function taking the connection and vessel as arguments. - 2) Reuse the above useful programs as much as possible. - - Use `launch_to_orbit(conn, vessel, target_altitude, target_inclination)` for launches. Do not use raw staging and throttle control. - - Use `execute_maneuver_node(conn, vessl, mode)` for burns. Do not use manual throttle control during burns. - - Use `automated_landing(conn, vessel, target_lat, target_lon)` for landings. Do not use manual landing procedures. - - Use `transfer_to_body(conn, vessel, target_body)` for interplanetary transfers. Do not calculate transfer windows manually. - - Use `rendezvous_with_target(conn, vessel, target)` for docking operations. Do not use manual approach procedures. - 3) Your function will be reused for building more complex missions. Therefore, you should make it generic and reusable. You should not make strong assumptions about the vessel configuration (as it may be changed between missions), and therefore you should always check whether you have the required parts and resources before using them. If not, you should return appropriate error messages. - 4) Functions in the "Code from the last round" section will not be saved or executed. Do not reuse functions listed there. - 5) Anything defined outside a function will be ignored, define all your variables inside your functions. - 6) Use `print()` statements to show intermediate progress and telemetry data. - 7) Use `wait_for_soi_change(conn, vessel, target_body)` when waiting for sphere of influence changes during transfers. You should monitor vessel status during long burns or coast phases. - 8) Always check `conn.space_center.active_vessel` to ensure you're controlling the correct vessel. Vessel references can change during scene transitions. - 9) Do not write infinite loops without proper exit conditions based on mission objectives or failure states. - 10) Do not use `conn.add_stream()` without properly removing streams when done. Always clean up resources. - 11) Handle MechJeb availability with mj.available()` checks before using autopilots. Wait for MechJeb to initialize if needed. - 12) Name your function in a meaningful way that describes the mission phase or objective. +1) Write a function taking the connection and vessel as arguments. Example: def launch_mission(conn, vessel): +Example code structure: +python def launch_mission(conn, vessel): + if not conn.mech_jeb.api_ready: + print("MechJeb not available") + return False + ascent_ap = conn.mech_jeb.ascent_autopilot + # ... rest of code + return True # Return success/failure +2) CRITICAL: Always return True on success, False on failure. This allows error handling and recovery. + +3) CRITICAL: Use `conn.mech_jeb` to access MechJeb services directly from the connection. + +4) Use ONLY MechJeb autopilots and modules to implement functionality. Do NOT use raw kRPC calls. + +5) If the above useful programs are available, reuse them. Otherwise, implement using MechJeb. + +6) Your function will be reused for building more complex missions. Therefore, you should make it generic and reusable. You should not make strong assumptions about the vessel configuration (as it may be changed between missions), and therefore you should always check whether you have the required parts and resources before using them. If not, you should return appropriate error messages. + +7) Functions in the "Code from the last round" section will not be saved or executed. Do not reuse functions listed there. + +8) Anything defined outside a function will be ignored, define all your variables inside your functions. + +9) Use `print()` statements to show intermediate progress and telemetry data. + +10) Always check MechJeb availability with `conn.mech_jeb.api_ready` before using any MechJeb modules. Use `conn.mech_jeb` to access all MechJeb services. + +11) Wait for MechJeb autopilots to complete their tasks using appropriate monitoring loops. + +12) Do not write infinite loops without proper exit conditions based on mission objectives or failure states. + +13) CRITICAL FOR LAUNCHES: Always start the rocket before enabling MechJeb autopilot. + +14) FUEL OPTIMIZATION: Configure MechJeb for efficient ascent. + +15) Use MechJeb's built-in monitoring and control systems rather than manual kRPC streams. + +16) Always check `conn.space_center.active_vessel` to ensure you're controlling the correct vessel. Vessel references can change during scene transitions. + +17) ALWAYS check vessel readiness before using autopilots: verify vessel has engines, fuel, and is in the correct situation. + +18) CRITICAL FOR LAUNCHES: Always enable autostaging and set up staging controller for automatic launch. + +19) CRITICAL: Monitor mission status and detect failures. + +20) MANDATORY: Your code MUST include these monitoring features: + - Track maximum altitude reached during ascent + - Check for altitude loss (falling back to ground) + - Monitor fuel levels with `vessel.resources.amount('LiquidFuel')` + - Check vessel situation for crashes + - Print detailed status updates including altitude and fuel levels + +21) CRITICAL: Use the telemetry data provided in the prompt to make decisions. The telemetry includes: + - Resources: Check fuel amounts and percentages before launching + - Vessel Status: Check mass, thrust, and control state + - Part Status: Check if vessel has the required parts + - Orbit Parameters: Use current orbital state for planning + +22) Base your code decisions on the actual telemetry values, not assumptions. + +23) Name your function in a meaningful way that describes the mission phase or objective. + +24) Prefer MechJeb's high-level autopilots over manual control implementations. You should only respond in the format as described below: RESPONSE FORMAT: diff --git a/kosmos/prompts/krpc_readmellm.txt b/kosmos/prompts/krpc_readmellm.txt new file mode 100644 index 0000000..2d071da --- /dev/null +++ b/kosmos/prompts/krpc_readmellm.txt @@ -0,0 +1,4178 @@ +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +SpaceCenter +=========== + + +.. module:: SpaceCenter + +Provides functionality to interact with Kerbal Space Program. This includes controlling +the active vessel, managing its resources, planning maneuver nodes and auto-piloting. + + +.. attribute:: science + + The current amount of science. + + :Attribute: Read-only, cannot be set + :rtype: float + + + + + +.. attribute:: funds + + The current amount of funds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + + + +.. attribute:: reputation + + The current amount of reputation. + + :Attribute: Read-only, cannot be set + :rtype: float + + + + + +.. attribute:: active_vessel + + The currently active vessel. + + :Attribute: Can be read or written + :rtype: :class:`Vessel` + + + + + +.. attribute:: vessels + + A list of all the vessels in the game. + + :Attribute: Read-only, cannot be set + :rtype: list(:class:`Vessel`) + + + + + +.. attribute:: launch_sites + + A list of available launch sites. + + :Attribute: Read-only, cannot be set + :rtype: list(:class:`LaunchSite`) + + + + + +.. attribute:: bodies + + A dictionary of all celestial bodies (planets, moons, etc.) in the game, + keyed by the name of the body. + + :Attribute: Read-only, cannot be set + :rtype: dict(str, :class:`CelestialBody`) + + + + + +.. attribute:: target_body + + The currently targeted celestial body. + + :Attribute: Can be read or written + :rtype: :class:`CelestialBody` + :Game Scenes: Flight + + + + + +.. attribute:: target_vessel + + The currently targeted vessel. + + :Attribute: Can be read or written + :rtype: :class:`Vessel` + :Game Scenes: Flight + + + + + +.. attribute:: target_docking_port + + The currently targeted docking port. + + :Attribute: Can be read or written + :rtype: :class:`DockingPort` + :Game Scenes: Flight + + + + + +.. staticmethod:: clear_target() + + Clears the current target. + + :Game Scenes: Flight + + + + + +.. staticmethod:: launchable_vessels(craft_directory) + + Returns a list of vessels from the given *craft_directory* + that can be launched. + + :param str craft_directory: Name of the directory in the current saves "Ships" directory. For example ``"VAB"`` or ``"SPH"``. + :rtype: list(str) + + + + + +.. staticmethod:: launch_vessel(craft_directory, name, launch_site, [recover = True], [crew = None], [flag_url = '']) + + Launch a vessel. + + :param str craft_directory: Name of the directory in the current saves "Ships" directory, that contains the craft file. For example ``"VAB"`` or ``"SPH"``. + :param str name: Name of the vessel to launch. This is the name of the ".craft" file in the save directory, without the ".craft" file extension. + :param str launch_site: Name of the launch site. For example ``"LaunchPad"`` or ``"Runway"``. + :param bool recover: If true and there is a vessel on the launch site, recover it before launching. + :param list crew: If not ``None``, a list of names of Kerbals to place in the craft. Otherwise the crew will use default assignments. + :param str flag_url: If not ``None``, the asset URL of the mission flag to use for the launch. + + + .. note:: + + Throws an exception if any of the games pre-flight checks fail. + + + + +.. staticmethod:: launch_vessel_from_vab(name, [recover = True]) + + Launch a new vessel from the VAB onto the launchpad. + + :param str name: Name of the vessel to launch. + :param bool recover: If true and there is a vessel on the launch pad, recover it before launching. + + + .. note:: + + This is equivalent to calling :meth:`launch_vessel` with the craft directory + set to "VAB" and the launch site set to "LaunchPad". + Throws an exception if any of the games pre-flight checks fail. + + + + +.. staticmethod:: launch_vessel_from_sph(name, [recover = True]) + + Launch a new vessel from the SPH onto the runway. + + :param str name: Name of the vessel to launch. + :param bool recover: If true and there is a vessel on the runway, recover it before launching. + + + .. note:: + + This is equivalent to calling :meth:`launch_vessel` with the craft directory + set to "SPH" and the launch site set to "Runway". + Throws an exception if any of the games pre-flight checks fail. + + + + +.. staticmethod:: save(name) + + Save the game with a given name. + This will create a save file called ``name.sfs`` in the folder of the + current save game. + + :param str name: Name of the save. + + + + + +.. staticmethod:: load(name) + + Load the game with the given name. + This will create a load a save file called ``name.sfs`` from the folder of the + current save game. + + :param str name: Name of the save. + + + + + +.. staticmethod:: quicksave() + + Save a quicksave. + + + + .. note:: + + This is the same as calling :meth:`save` with the name "quicksave". + + + + +.. staticmethod:: quickload() + + Load a quicksave. + + + + .. note:: + + This is the same as calling :meth:`load` with the name "quicksave". + + + + +.. staticmethod:: can_revert_to_launch() + + Whether the current flight can be reverted to launch. + + :rtype: bool + + + + + +.. staticmethod:: revert_to_launch() + + Revert the current flight to launch. + + + + + + +.. staticmethod:: transfer_crew(crew_member, target_part) + + Transfers a crew member to a different part. + + :param CrewMember crew_member: The crew member to transfer. + :param Part target_part: The part to move them to. + :Game Scenes: Flight + + + + + +.. attribute:: ui_visible + + Whether the UI is visible. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + + + +.. attribute:: navball + + Whether the navball is visible. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + + + +.. attribute:: ut + + The current universal time in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + + + +.. attribute:: g + + The value of the `gravitational constant `_ G in :math:`N(m/kg)^2`. + + :Attribute: Read-only, cannot be set + :rtype: float + + + + + +.. attribute:: warp_rate + + The current warp rate. This is the rate at which time is passing for + either on-rails or physical time warp. For example, a value of 10 means + time is passing 10x faster than normal. Returns 1 if time warp is not + active. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + + + +.. attribute:: warp_factor + + The current warp factor. This is the index of the rate at which time + is passing for either regular "on-rails" or physical time warp. Returns 0 + if time warp is not active. When in on-rails time warp, this is equal to + :attr:`rails_warp_factor`, and in physics time warp, this is equal to + :attr:`physics_warp_factor`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + + + +.. attribute:: rails_warp_factor + + The time warp rate, using regular "on-rails" time warp. A value between + 0 and 7 inclusive. 0 means no time warp. Returns 0 if physical time warp + is active. + + If requested time warp factor cannot be set, it will be set to the next + lowest possible value. For example, if the vessel is too close to a + planet. See `the KSP wiki `_ for details. + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + + + + +.. attribute:: physics_warp_factor + + The physical time warp rate. A value between 0 and 3 inclusive. 0 means + no time warp. Returns 0 if regular "on-rails" time warp is active. + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + + + + +.. staticmethod:: can_rails_warp_at([factor = 1]) + + Returns ``True`` if regular "on-rails" time warp can be used, at the specified warp + *factor*. The maximum time warp rate is limited by various things, + including how close the active vessel is to a planet. See + `the KSP wiki `_ + for details. + + :param int factor: The warp factor to check. + :rtype: bool + :Game Scenes: Flight + + + + + +.. attribute:: maximum_rails_warp_factor + + The current maximum regular "on-rails" warp factor that can be set. + A value between 0 and 7 inclusive. See + `the KSP wiki `_ + for details. + + :Attribute: Read-only, cannot be set + :rtype: int + :Game Scenes: Flight + + + + + +.. staticmethod:: warp_to(ut, [max_rails_rate = 100000.0], [max_physics_rate = 2.0]) + + Uses time acceleration to warp forward to a time in the future, specified + by universal time *ut*. This call blocks until the desired + time is reached. Uses regular "on-rails" or physical time warp as appropriate. + For example, physical time warp is used when the active vessel is traveling + through an atmosphere. When using regular "on-rails" time warp, the warp + rate is limited by *max_rails_rate*, and when using physical + time warp, the warp rate is limited by *max_physics_rate*. + + :param float ut: The universal time to warp to, in seconds. + :param float max_rails_rate: The maximum warp rate in regular "on-rails" time warp. + :param float max_physics_rate: The maximum warp rate in physical time warp. + :returns: When the time warp is complete. + :Game Scenes: Flight + + + + + +.. staticmethod:: transform_position(position, from, to) + + Converts a position from one reference frame to another. + + :param tuple position: Position, as a vector, in reference frame *from*. + :param ReferenceFrame from: The reference frame that the position is in. + :param ReferenceFrame to: The reference frame to covert the position to. + :returns: The corresponding position, as a vector, in reference frame *to*. + :rtype: tuple(float, float, float) + + + + + +.. staticmethod:: transform_direction(direction, from, to) + + Converts a direction from one reference frame to another. + + :param tuple direction: Direction, as a vector, in reference frame *from*. + :param ReferenceFrame from: The reference frame that the direction is in. + :param ReferenceFrame to: The reference frame to covert the direction to. + :returns: The corresponding direction, as a vector, in reference frame *to*. + :rtype: tuple(float, float, float) + + + + + +.. staticmethod:: transform_rotation(rotation, from, to) + + Converts a rotation from one reference frame to another. + + :param tuple rotation: Rotation, as a quaternion of the form :math:`(x, y, z, w)`, in reference frame *from*. + :param ReferenceFrame from: The reference frame that the rotation is in. + :param ReferenceFrame to: The reference frame to covert the rotation to. + :returns: The corresponding rotation, as a quaternion of the form :math:`(x, y, z, w)`, in reference frame *to*. + :rtype: tuple(float, float, float, float) + + + + + +.. staticmethod:: transform_velocity(position, velocity, from, to) + + Converts a velocity (acting at the specified position) from one reference frame + to another. The position is required to take the relative angular velocity of the + reference frames into account. + + :param tuple position: Position, as a vector, in reference frame *from*. + :param tuple velocity: Velocity, as a vector that points in the direction of travel and whose magnitude is the speed in meters per second, in reference frame *from*. + :param ReferenceFrame from: The reference frame that the position and velocity are in. + :param ReferenceFrame to: The reference frame to covert the velocity to. + :returns: The corresponding velocity, as a vector, in reference frame *to*. + :rtype: tuple(float, float, float) + + + + + +.. staticmethod:: raycast_distance(position, direction, reference_frame) + + Cast a ray from a given position in a given direction, and return the distance to the hit point. + If no hit occurs, returns infinity. + + :param tuple position: Position, as a vector, of the origin of the ray. + :param tuple direction: Direction of the ray, as a unit vector. + :param ReferenceFrame reference_frame: The reference frame that the position and direction are in. + :returns: The distance to the hit, in meters, or infinity if there was no hit. + :rtype: float + + + + + +.. staticmethod:: raycast_part(position, direction, reference_frame) + + Cast a ray from a given position in a given direction, and return the part that it hits. + If no hit occurs, returns ``None``. + + :param tuple position: Position, as a vector, of the origin of the ray. + :param tuple direction: Direction of the ray, as a unit vector. + :param ReferenceFrame reference_frame: The reference frame that the position and direction are in. + :returns: The part that was hit or ``None`` if there was no hit. + :rtype: :class:`Part` + :Game Scenes: Flight + + + + + +.. attribute:: far_available + + Whether `Ferram Aerospace Research `_ is installed. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + + + +.. staticmethod:: create_kerbal(name, job, male) + + Creates a Kerbal. + + :param str name: + :param str job: + :param bool male: + + + + + +.. staticmethod:: get_kerbal(name) + + Find a Kerbal by name. + + :param str name: + :rtype: :class:`CrewMember` + + + + + +.. staticmethod:: load_space_center() + + Switch to the space center view. + + + + + + +.. attribute:: map_filter + + The visible objects in map mode. + + :Attribute: Can be read or written + :rtype: :class:`MapFilterType` + + + + + +.. staticmethod:: screenshot(file_path, [scale = 1]) + + Saves a screenshot. + + :param str file_path: The path of the file to save. + :param int scale: Resolution scaling factor + :Game Scenes: Flight + + + + + +.. attribute:: game_mode + + The current mode the game is in. + + :Attribute: Read-only, cannot be set + :rtype: :class:`GameMode` + + + + + +.. attribute:: warp_mode + + The current time warp mode. Returns :attr:`WarpMode.none` if time + warp is not active, :attr:`WarpMode.rails` if regular "on-rails" time warp + is active, or :attr:`WarpMode.physics` if physical time warp is active. + + :Attribute: Read-only, cannot be set + :rtype: :class:`WarpMode` + :Game Scenes: Flight + + + + + +.. attribute:: camera + + An object that can be used to control the camera. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Camera` + :Game Scenes: Flight + + + + + +.. attribute:: waypoint_manager + + The waypoint manager. + + :Attribute: Read-only, cannot be set + :rtype: :class:`WaypointManager` + :Game Scenes: Flight + + + + + +.. attribute:: contract_manager + + The contract manager. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ContractManager` + + + + + +.. attribute:: alarm_manager + + The alarm manager. + + :Attribute: Read-only, cannot be set + :rtype: :class:`AlarmManager` + + + + + + +.. class:: GameMode + + The game mode. + Returned by :class:`GameMode` + + + .. data:: sandbox + + Sandbox mode. + + + .. data:: career + + Career mode. + + + .. data:: science + + Science career mode. + + + .. data:: science_sandbox + + Science sandbox mode. + + + .. data:: mission + + Mission mode. + + + .. data:: mission_builder + + Mission builder mode. + + + .. data:: scenario + + Scenario mode. + + + .. data:: scenario_non_resumable + + Scenario mode that cannot be resumed. + + + +.. class:: WarpMode + + The time warp mode. + Returned by :class:`WarpMode` + + + .. data:: rails + + Time warp is active, and in regular "on-rails" mode. + + + .. data:: physics + + Time warp is active, and in physical time warp mode. + + + .. data:: none + + Time warp is not active. + + + +.. class:: MapFilterType + + The set of things that are visible in map mode. + These may be combined with bitwise logic. + + + .. data:: all + + Everything. + + + .. data:: none + + Nothing. + + + .. data:: debris + + Debris. + + + .. data:: unknown + + Unknown. + + + .. data:: space_objects + + SpaceObjects. + + + .. data:: probes + + Probes. + + + .. data:: rovers + + Rovers. + + + .. data:: landers + + Landers. + + + .. data:: ships + + Ships. + + + .. data:: stations + + Stations. + + + .. data:: bases + + Bases. + + + .. data:: ev_as + + EVAs. + + + .. data:: flags + + Flags. + + + .. data:: plane + + Planes. + + + .. data:: relay + + Relays. + + + .. data:: site + + Launch Sites. + + + .. data:: deployed_science_controller + + Deployed Science Controllers. + + + +.. class:: LaunchSite + + A place where craft can be launched from. + More of these can be added with mods like Kerbal Konstructs. + + .. attribute:: name + + The name of the launch site. + + :Attribute: Read-only, cannot be set + :rtype: str + + + .. attribute:: body + + The celestial body the launch site is on. + + :Attribute: Read-only, cannot be set + :rtype: :class:`CelestialBody` + + + .. attribute:: editor_facility + + Which editor is normally used for this launch site. + + :Attribute: Read-only, cannot be set + :rtype: :class:`EditorFacility` + + + + +.. class:: EditorFacility + + Editor facility. + See :attr:`LaunchSite.editor_facility`. + + + .. data:: vab + + Vehicle Assembly Building. + + + .. data:: sph + + Space Plane Hanger. + + + .. data:: none + + None. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +Vessel +====== + + +.. class:: Vessel + + These objects are used to interact with vessels in KSP. This includes getting + orbital and flight data, manipulating control inputs and managing resources. + Created using :attr:`active_vessel` or :attr:`vessels`. + + .. attribute:: name + + The name of the vessel. + + :Attribute: Can be read or written + :rtype: str + + + .. attribute:: type + + The type of the vessel. + + :Attribute: Can be read or written + :rtype: :class:`VesselType` + + + .. attribute:: situation + + The situation the vessel is in. + + :Attribute: Read-only, cannot be set + :rtype: :class:`VesselSituation` + + + .. attribute:: recoverable + + Whether the vessel is recoverable. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + .. method:: recover() + + Recover the vessel. + + + + .. attribute:: met + + The mission elapsed time in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: biome + + The name of the biome the vessel is currently in. + + :Attribute: Read-only, cannot be set + :rtype: str + + + .. method:: flight([reference_frame = None]) + + Returns a :class:`Flight` object that can be used to get flight + telemetry for the vessel, in the specified reference frame. + + :param ReferenceFrame reference_frame: Reference frame. Defaults to the vessel's surface reference frame (:attr:`Vessel.surface_reference_frame`). + :rtype: :class:`Flight` + :Game Scenes: Flight + + + .. note:: When this is called with no arguments, the vessel's surface reference + frame is used. This reference frame moves with the vessel, therefore + velocities and speeds returned by the flight object will be zero. See + the :rst:ref:`reference frames tutorial ` + for examples of getting :rst:ref:`the orbital and surface speeds of a + vessel `. + + .. attribute:: orbit + + The current orbit of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Orbit` + + + .. attribute:: control + + Returns a :class:`Control` object that can be used to manipulate + the vessel's control inputs. For example, its pitch/yaw/roll controls, + RCS and thrust. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Control` + :Game Scenes: Flight + + .. attribute:: comms + + Returns a :class:`Comms` object that can be used to interact + with CommNet for this vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Comms` + :Game Scenes: Flight + + .. attribute:: auto_pilot + + An :class:`AutoPilot` object, that can be used to perform + simple auto-piloting of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`AutoPilot` + :Game Scenes: Flight + + .. attribute:: crew_capacity + + The number of crew that can occupy the vessel. + + :Attribute: Read-only, cannot be set + :rtype: int + + + .. attribute:: crew_count + + The number of crew that are occupying the vessel. + + :Attribute: Read-only, cannot be set + :rtype: int + + + .. attribute:: crew + + The crew in the vessel. + + :Attribute: Read-only, cannot be set + :rtype: list(:class:`CrewMember`) + + + .. attribute:: resources + + A :class:`Resources` object, that can used to get information + about resources stored in the vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Resources` + :Game Scenes: Flight + + .. method:: resources_in_decouple_stage(stage, [cumulative = True]) + + Returns a :class:`Resources` object, that can used to get + information about resources stored in a given *stage*. + + :param int stage: Get resources for parts that are decoupled in this stage. + :param bool cumulative: When ``False``, returns the resources for parts decoupled in just the given stage. When ``True`` returns the resources decoupled in the given stage and all subsequent stages combined. + :rtype: :class:`Resources` + :Game Scenes: Flight + + + .. note:: For details on stage numbering, see the + discussion on :rst:ref:`python-api-parts-staging`. + + .. attribute:: parts + + A :class:`Parts` object, that can used to interact with the parts that make up this vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Parts` + :Game Scenes: Flight + + .. attribute:: mass + + The total mass of the vessel, including resources, in kg. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: dry_mass + + The total mass of the vessel, excluding resources, in kg. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: thrust + + The total thrust currently being produced by the vessel's engines, in + Newtons. This is computed by summing :attr:`Engine.thrust` for + every engine in the vessel. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: available_thrust + + Gets the total available thrust that can be produced by the vessel's + active engines, in Newtons. This is computed by summing + :attr:`Engine.available_thrust` for every active engine in the vessel. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. method:: available_thrust_at(pressure) + + Gets the total available thrust that can be produced by the vessel's + active engines, in Newtons. This is computed by summing + :meth:`Engine.available_thrust_at` for every active engine in the vessel. + Takes the given pressure into account. + + :param float pressure: Atmospheric pressure in atmospheres + :rtype: float + :Game Scenes: Flight + + .. attribute:: max_thrust + + The total maximum thrust that can be produced by the vessel's active + engines, in Newtons. This is computed by summing + :attr:`Engine.max_thrust` for every active engine. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. method:: max_thrust_at(pressure) + + The total maximum thrust that can be produced by the vessel's active + engines, in Newtons. This is computed by summing + :meth:`Engine.max_thrust_at` for every active engine. + Takes the given pressure into account. + + :param float pressure: Atmospheric pressure in atmospheres + :rtype: float + :Game Scenes: Flight + + .. attribute:: max_vacuum_thrust + + The total maximum thrust that can be produced by the vessel's active + engines when the vessel is in a vacuum, in Newtons. This is computed by + summing :attr:`Engine.max_vacuum_thrust` for every active engine. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: specific_impulse + + The combined specific impulse of all active engines, in seconds. This is computed using the formula + `described here `_. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. method:: specific_impulse_at(pressure) + + The combined specific impulse of all active engines, in seconds. This is computed using the formula + `described here `_. + Takes the given pressure into account. + + :param float pressure: Atmospheric pressure in atmospheres + :rtype: float + :Game Scenes: Flight + + .. attribute:: vacuum_specific_impulse + + The combined vacuum specific impulse of all active engines, in seconds. This is computed using the formula + `described here `_. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: kerbin_sea_level_specific_impulse + + The combined specific impulse of all active engines at sea level on Kerbin, in seconds. + This is computed using the formula + `described here `_. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: moment_of_inertia + + The moment of inertia of the vessel around its center of mass in :math:`kg.m^2`. + The inertia values in the returned 3-tuple are around the + pitch, roll and yaw directions respectively. + This corresponds to the vessels reference frame (:class:`ReferenceFrame`). + + :Attribute: Read-only, cannot be set + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: inertia_tensor + + The inertia tensor of the vessel around its center of mass, + in the vessels reference frame (:class:`ReferenceFrame`). + Returns the 3x3 matrix as a list of elements, in row-major order. + + :Attribute: Read-only, cannot be set + :rtype: list(float) + + + .. attribute:: available_torque + + The maximum torque that the vessel generates. Includes contributions from + reaction wheels, RCS, gimballed engines and aerodynamic control surfaces. + Returns the torques in :math:`N.m` around each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the pitch, roll and yaw axes of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: available_reaction_wheel_torque + + The maximum torque that the currently active and powered reaction wheels can generate. + Returns the torques in :math:`N.m` around each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the pitch, roll and yaw axes of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: available_rcs_torque + + The maximum torque that the currently active RCS thrusters can generate. + Returns the torques in :math:`N.m` around each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the pitch, roll and yaw axes of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: available_rcs_force + + The maximum force that the currently active RCS thrusters can generate. + Returns the forces in :math:`N` along each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the right, forward and bottom directions of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: available_engine_torque + + The maximum torque that the currently active and gimballed engines can generate. + Returns the torques in :math:`N.m` around each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the pitch, roll and yaw axes of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: available_control_surface_torque + + The maximum torque that the aerodynamic control surfaces can generate. + Returns the torques in :math:`N.m` around each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the pitch, roll and yaw axes of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: available_other_torque + + The maximum torque that parts (excluding reaction wheels, gimballed engines, + RCS and control surfaces) can generate. + Returns the torques in :math:`N.m` around each of the coordinate axes of the + vessels reference frame (:class:`ReferenceFrame`). + These axes are equivalent to the pitch, roll and yaw axes of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. attribute:: reference_frame + + The reference frame that is fixed relative to the vessel, + and orientated with the vessel. + + * The origin is at the center of mass of the vessel. + * The axes rotate with the vessel. + * The x-axis points out to the right of the vessel. + * The y-axis points in the forward direction of the vessel. + * The z-axis points out of the bottom off the vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + :Game Scenes: Flight + + + .. figure:: /images/reference-frames/vessel-aircraft.png + :align: center + + Vessel reference frame origin and axes for the Aeris 3A aircraft + + .. figure:: /images/reference-frames/vessel-rocket.png + :align: center + + Vessel reference frame origin and axes for the Kerbal-X rocket + + .. attribute:: orbital_reference_frame + + The reference frame that is fixed relative to the vessel, + and orientated with the vessels orbital prograde/normal/radial directions. + + * The origin is at the center of mass of the vessel. + * The axes rotate with the orbital prograde/normal/radial directions. + * The x-axis points in the orbital anti-radial direction. + * The y-axis points in the orbital prograde direction. + * The z-axis points in the orbital normal direction. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + :Game Scenes: Flight + + + .. note:: + + Be careful not to confuse this with 'orbit' mode on the navball. + + .. figure:: /images/reference-frames/vessel-orbital.png + :align: center + + Vessel orbital reference frame origin and axes + + .. attribute:: surface_reference_frame + + The reference frame that is fixed relative to the vessel, + and orientated with the surface of the body being orbited. + + * The origin is at the center of mass of the vessel. + * The axes rotate with the north and up directions on the surface of the body. + * The x-axis points in the `zenith `_ + direction (upwards, normal to the body being orbited, from the center of the body towards the center of + mass of the vessel). + * The y-axis points northwards towards the + `astronomical horizon `_ (north, and tangential to the + surface of the body -- the direction in which a compass would point when on the surface). + * The z-axis points eastwards towards the + `astronomical horizon `_ (east, and tangential to the + surface of the body -- east on a compass when on the surface). + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + :Game Scenes: Flight + + + .. note:: + + Be careful not to confuse this with 'surface' mode on the navball. + + .. figure:: /images/reference-frames/vessel-surface.png + :align: center + + Vessel surface reference frame origin and axes + + .. attribute:: surface_velocity_reference_frame + + The reference frame that is fixed relative to the vessel, + and orientated with the velocity vector of the vessel relative + to the surface of the body being orbited. + + * The origin is at the center of mass of the vessel. + * The axes rotate with the vessel's velocity vector. + * The y-axis points in the direction of the vessel's velocity vector, + relative to the surface of the body being orbited. + * The z-axis is in the plane of the + `astronomical horizon `_. + * The x-axis is orthogonal to the other two axes. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + :Game Scenes: Flight + + + .. figure:: /images/reference-frames/vessel-surface-velocity.png + :align: center + + Vessel surface velocity reference frame origin and axes + + .. method:: position(reference_frame) + + The position of the center of mass of the vessel, in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned position vector is in. + :returns: The position as a vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: bounding_box(reference_frame) + + The axis-aligned bounding box of the vessel in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned position vectors are in. + :returns: The positions of the minimum and maximum vertices of the box, as position vectors. + :rtype: tuple(tuple(float, float, float), tuple(float, float, float)) + :Game Scenes: Flight + + .. method:: velocity(reference_frame) + + The velocity of the center of mass of the vessel, in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned velocity vector is in. + :returns: The velocity as a vector. The vector points in the direction of travel, and its magnitude is the speed of the body in meters per second. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: rotation(reference_frame) + + The rotation of the vessel, in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned rotation is in. + :returns: The rotation as a quaternion of the form :math:`(x, y, z, w)`. + :rtype: tuple(float, float, float, float) + :Game Scenes: Flight + + .. method:: direction(reference_frame) + + The direction in which the vessel is pointing, in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned direction is in. + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: angular_velocity(reference_frame) + + The angular velocity of the vessel, in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame the returned angular velocity is in. + :returns: The angular velocity as a vector. The magnitude of the vector is the rotational speed of the vessel, in radians per second. The direction of the vector indicates the axis of rotation, using the right-hand rule. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + + +.. class:: VesselType + + The type of a vessel. + See :attr:`Vessel.type`. + + + .. data:: base + + Base. + + + .. data:: debris + + Debris. + + + .. data:: lander + + Lander. + + + .. data:: plane + + Plane. + + + .. data:: probe + + Probe. + + + .. data:: relay + + Relay. + + + .. data:: rover + + Rover. + + + .. data:: ship + + Ship. + + + .. data:: station + + Station. + + + .. data:: space_object + + SpaceObject. + + + .. data:: unknown + + Unknown. + + + .. data:: eva + + EVA. + + + .. data:: flag + + Flag. + + + .. data:: deployed_science_controller + + DeployedScienceController. + + + .. data:: deployed_science_part + + DeploedSciencePart. + + + .. data:: dropped_part + + DroppedPart. + + + .. data:: deployed_ground_part + + DeployedGroundPart. + + + +.. class:: VesselSituation + + The situation a vessel is in. + See :attr:`Vessel.situation`. + + + .. data:: docked + + Vessel is docked to another. + + + .. data:: escaping + + Escaping. + + + .. data:: flying + + Vessel is flying through an atmosphere. + + + .. data:: landed + + Vessel is landed on the surface of a body. + + + .. data:: orbiting + + Vessel is orbiting a body. + + + .. data:: pre_launch + + Vessel is awaiting launch. + + + .. data:: splashed + + Vessel has splashed down in an ocean. + + + .. data:: sub_orbital + + Vessel is on a sub-orbital trajectory. + + + +.. class:: CrewMember + + Represents crew in a vessel. Can be obtained using :attr:`Vessel.crew`. + + .. attribute:: name + + The crew members name. + + :Attribute: Can be read or written + :rtype: str + + + .. attribute:: type + + The type of crew member. + + :Attribute: Read-only, cannot be set + :rtype: :class:`CrewMemberType` + + + .. attribute:: on_mission + + Whether the crew member is on a mission. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + .. attribute:: courage + + The crew members courage. + + :Attribute: Can be read or written + :rtype: float + + + .. attribute:: stupidity + + The crew members stupidity. + + :Attribute: Can be read or written + :rtype: float + + + .. attribute:: experience + + The crew members experience. + + :Attribute: Can be read or written + :rtype: float + + + .. attribute:: badass + + Whether the crew member is a badass. + + :Attribute: Can be read or written + :rtype: bool + + + .. attribute:: veteran + + Whether the crew member is a veteran. + + :Attribute: Can be read or written + :rtype: bool + + + .. attribute:: trait + + The crew member's job. + + :Attribute: Read-only, cannot be set + :rtype: str + + + .. attribute:: gender + + The crew member's gender. + + :Attribute: Read-only, cannot be set + :rtype: :class:`CrewMemberGender` + + + .. attribute:: roster_status + + The crew member's current roster status. + + :Attribute: Read-only, cannot be set + :rtype: :class:`RosterStatus` + + + .. attribute:: suit_type + + The crew member's suit type. + + :Attribute: Can be read or written + :rtype: :class:`SuitType` + + + .. attribute:: career_log_flights + + The flight IDs for each entry in the career flight log. + + :Attribute: Read-only, cannot be set + :rtype: list(int) + + + .. attribute:: career_log_types + + The type for each entry in the career flight log. + + :Attribute: Read-only, cannot be set + :rtype: list(str) + + + .. attribute:: career_log_targets + + The body name for each entry in the career flight log. + + :Attribute: Read-only, cannot be set + :rtype: list(str) + + + + +.. class:: CrewMemberType + + The type of a crew member. + See :attr:`CrewMember.type`. + + + .. data:: applicant + + An applicant for crew. + + + .. data:: crew + + Rocket crew. + + + .. data:: tourist + + A tourist. + + + .. data:: unowned + + An unowned crew member. + + + +.. class:: CrewMemberGender + + A crew member's gender. + See :attr:`CrewMember.gender`. + + + .. data:: male + + Male. + + + .. data:: female + + Female. + + + +.. class:: RosterStatus + + A crew member's roster status. + See :attr:`CrewMember.roster_status`. + + + .. data:: available + + Available. + + + .. data:: assigned + + Assigned. + + + .. data:: dead + + Dead. + + + .. data:: missing + + Missing. + + + +.. class:: SuitType + + A crew member's suit type. + See :attr:`CrewMember.suit_type`. + + + .. data:: default + + Default. + + + .. data:: vintage + + Vintage. + + + .. data:: future + + Future. + + + .. data:: slim + + Slim. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +CelestialBody +============= + + +.. class:: CelestialBody + + Represents a celestial body (such as a planet or moon). + See :attr:`bodies`. + + .. attribute:: name + + The name of the body. + + :Attribute: Read-only, cannot be set + :rtype: str + + + .. attribute:: satellites + + A list of celestial bodies that are in orbit around this celestial body. + + :Attribute: Read-only, cannot be set + :rtype: list(:class:`CelestialBody`) + + + .. attribute:: orbit + + The orbit of the body. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Orbit` + + + .. attribute:: mass + + The mass of the body, in kilograms. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: gravitational_parameter + + The `standard gravitational parameter `_ of the body in :math:`m^3s^{-2}`. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: surface_gravity + + The acceleration due to gravity at sea level (mean altitude) on the body, + in :math:`m/s^2`. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: rotational_period + + The sidereal rotational period of the body, in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: rotational_speed + + The rotational speed of the body, in radians per second. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: rotation_angle + + The current rotation angle of the body, in radians. + A value between 0 and :math:`2\pi` + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: initial_rotation + + The initial rotation angle of the body (at UT 0), in radians. + A value between 0 and :math:`2\pi` + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: equatorial_radius + + The equatorial radius of the body, in meters. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. method:: surface_height(latitude, longitude) + + The height of the surface relative to mean sea level, in meters, + at the given position. When over water this is equal to 0. + + :param float latitude: Latitude in degrees. + :param float longitude: Longitude in degrees. + :rtype: float + + + .. method:: bedrock_height(latitude, longitude) + + The height of the surface relative to mean sea level, in meters, + at the given position. When over water, this is the height + of the sea-bed and is therefore negative value. + + :param float latitude: Latitude in degrees. + :param float longitude: Longitude in degrees. + :rtype: float + + + .. method:: msl_position(latitude, longitude, reference_frame) + + The position at mean sea level at the given latitude and longitude, + in the given reference frame. + + :param float latitude: Latitude in degrees. + :param float longitude: Longitude in degrees. + :param ReferenceFrame reference_frame: Reference frame for the returned position vector. + :returns: Position as a vector. + :rtype: tuple(float, float, float) + + + .. method:: surface_position(latitude, longitude, reference_frame) + + The position of the surface at the given latitude and longitude, in the given + reference frame. When over water, this is the position of the surface of the water. + + :param float latitude: Latitude in degrees. + :param float longitude: Longitude in degrees. + :param ReferenceFrame reference_frame: Reference frame for the returned position vector. + :returns: Position as a vector. + :rtype: tuple(float, float, float) + + + .. method:: bedrock_position(latitude, longitude, reference_frame) + + The position of the surface at the given latitude and longitude, in the given + reference frame. When over water, this is the position at the bottom of the sea-bed. + + :param float latitude: Latitude in degrees. + :param float longitude: Longitude in degrees. + :param ReferenceFrame reference_frame: Reference frame for the returned position vector. + :returns: Position as a vector. + :rtype: tuple(float, float, float) + + + .. method:: position_at_altitude(latitude, longitude, altitude, reference_frame) + + The position at the given latitude, longitude and altitude, in the given reference frame. + + :param float latitude: Latitude in degrees. + :param float longitude: Longitude in degrees. + :param float altitude: Altitude in meters above sea level. + :param ReferenceFrame reference_frame: Reference frame for the returned position vector. + :returns: Position as a vector. + :rtype: tuple(float, float, float) + + + .. method:: altitude_at_position(position, reference_frame) + + The altitude, in meters, of the given position in the given reference frame. + + :param tuple position: Position as a vector. + :param ReferenceFrame reference_frame: Reference frame for the position vector. + :rtype: float + + + .. method:: latitude_at_position(position, reference_frame) + + The latitude of the given position, in the given reference frame. + + :param tuple position: Position as a vector. + :param ReferenceFrame reference_frame: Reference frame for the position vector. + :rtype: float + + + .. method:: longitude_at_position(position, reference_frame) + + The longitude of the given position, in the given reference frame. + + :param tuple position: Position as a vector. + :param ReferenceFrame reference_frame: Reference frame for the position vector. + :rtype: float + + + .. attribute:: sphere_of_influence + + The radius of the sphere of influence of the body, in meters. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: is_star + + Whether or not the body is a star. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + .. attribute:: has_solid_surface + + Whether or not the body has a solid surface. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + .. attribute:: has_atmosphere + + ``True`` if the body has an atmosphere. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + .. attribute:: atmosphere_depth + + The depth of the atmosphere, in meters. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. method:: atmospheric_density_at_position(position, reference_frame) + + The atmospheric density at the given position, in :math:`kg/m^3`, + in the given reference frame. + + :param tuple position: The position vector at which to measure the density. + :param ReferenceFrame reference_frame: Reference frame that the position vector is in. + :rtype: float + + + .. attribute:: has_atmospheric_oxygen + + ``True`` if there is oxygen in the atmosphere, required for air-breathing engines. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + .. method:: temperature_at(position, reference_frame) + + The temperature on the body at the given position, in the given reference frame. + + :param tuple position: Position as a vector. + :param ReferenceFrame reference_frame: The reference frame that the position is in. + :rtype: float + + + .. note:: + + This calculation is performed using the bodies current position, which means that + the value could be wrong if you want to know the temperature in the far future. + + .. method:: density_at(altitude) + + Gets the air density, in :math:`kg/m^3`, for the specified + altitude above sea level, in meters. + + :param float altitude: + :rtype: float + + + .. note:: + + This is an approximation, because actual calculations, taking sun exposure into account + to compute air temperature, require us to know the exact point on the body where the + density is to be computed (knowing the altitude is not enough). + However, the difference is small for high altitudes, so it makes very little difference + for trajectory prediction. + + .. method:: pressure_at(altitude) + + Gets the air pressure, in Pascals, for the specified + altitude above sea level, in meters. + + :param float altitude: + :rtype: float + + + .. attribute:: biomes + + The biomes present on this body. + + :Attribute: Read-only, cannot be set + :rtype: set(str) + + + .. method:: biome_at(latitude, longitude) + + The biome at the given latitude and longitude, in degrees. + + :param float latitude: + :param float longitude: + :rtype: str + + + .. attribute:: flying_high_altitude_threshold + + The altitude, in meters, above which a vessel is considered to be + flying "high" when doing science. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: space_high_altitude_threshold + + The altitude, in meters, above which a vessel is considered to be + in "high" space when doing science. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: reference_frame + + The reference frame that is fixed relative to the celestial body. + + * The origin is at the center of the body. + * The axes rotate with the body. + * The x-axis points from the center of the body + towards the intersection of the prime meridian and equator (the + position at 0° longitude, 0° latitude). + * The y-axis points from the center of the body + towards the north pole. + * The z-axis points from the center of the body + towards the equator at 90°E longitude. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + + + .. figure:: /images/reference-frames/celestial-body.png + :align: center + + Celestial body reference frame origin and axes. The equator is shown in + blue, and the prime meridian in red. + + .. attribute:: non_rotating_reference_frame + + The reference frame that is fixed relative to this celestial body, and + orientated in a fixed direction (it does not rotate with the body). + + * The origin is at the center of the body. + * The axes do not rotate. + * The x-axis points in an arbitrary direction through the + equator. + * The y-axis points from the center of the body towards + the north pole. + * The z-axis points in an arbitrary direction through the + equator. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + + + .. attribute:: orbital_reference_frame + + The reference frame that is fixed relative to this celestial body, but + orientated with the body's orbital prograde/normal/radial directions. + + * The origin is at the center of the body. + * The axes rotate with the orbital prograde/normal/radial + directions. + * The x-axis points in the orbital anti-radial direction. + * The y-axis points in the orbital prograde direction. + * The z-axis points in the orbital normal direction. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ReferenceFrame` + + + .. method:: position(reference_frame) + + The position of the center of the body, in the specified reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned position vector is in. + :returns: The position as a vector. + :rtype: tuple(float, float, float) + + + .. method:: velocity(reference_frame) + + The linear velocity of the body, in the specified reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned velocity vector is in. + :returns: The velocity as a vector. The vector points in the direction of travel, and its magnitude is the speed of the body in meters per second. + :rtype: tuple(float, float, float) + + + .. method:: rotation(reference_frame) + + The rotation of the body, in the specified reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned rotation is in. + :returns: The rotation as a quaternion of the form :math:`(x, y, z, w)`. + :rtype: tuple(float, float, float, float) + + + .. method:: direction(reference_frame) + + The direction in which the north pole of the celestial body is pointing, + in the specified reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned direction is in. + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + + + .. method:: angular_velocity(reference_frame) + + The angular velocity of the body in the specified reference frame. + + :param ReferenceFrame reference_frame: The reference frame the returned angular velocity is in. + :returns: The angular velocity as a vector. The magnitude of the vector is the rotational speed of the body, in radians per second. The direction of the vector indicates the axis of rotation, using the right-hand rule. + :rtype: tuple(float, float, float) + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +Flight +====== + + +.. class:: Flight + + Used to get flight telemetry for a vessel, by calling :meth:`Vessel.flight`. + All of the information returned by this class is given in the reference frame + passed to that method. + Obtained by calling :meth:`Vessel.flight`. + + .. note:: + + To get orbital information, such as the apoapsis or inclination, see :class:`Orbit`. + + .. attribute:: g_force + + The current G force acting on the vessel in :math:`g`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: mean_altitude + + The altitude above sea level, in meters. + Measured from the center of mass of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: surface_altitude + + The altitude above the surface of the body or sea level, whichever is closer, in meters. + Measured from the center of mass of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: bedrock_altitude + + The altitude above the surface of the body, in meters. When over water, this is the altitude above the sea floor. + Measured from the center of mass of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: elevation + + The elevation of the terrain under the vessel, in meters. This is the height of the terrain above sea level, + and is negative when the vessel is over the sea. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: latitude + + The `latitude `_ of the vessel for the body being orbited, in degrees. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: longitude + + The `longitude `_ of the vessel for the body being orbited, in degrees. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: velocity + + The velocity of the vessel, in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The velocity as a vector. The vector points in the direction of travel, and its magnitude is the speed of the vessel in meters per second. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: speed + + The speed of the vessel in meters per second, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: horizontal_speed + + The horizontal speed of the vessel in meters per second, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: vertical_speed + + The vertical speed of the vessel in meters per second, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: center_of_mass + + The position of the center of mass of the vessel, + in the reference frame :class:`ReferenceFrame` + + :Attribute: Read-only, cannot be set + :returns: The position as a vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: rotation + + The rotation of the vessel, in the reference frame :class:`ReferenceFrame` + + :Attribute: Read-only, cannot be set + :returns: The rotation as a quaternion of the form :math:`(x, y, z, w)`. + :rtype: tuple(float, float, float, float) + :Game Scenes: Flight + + .. attribute:: direction + + The direction that the vessel is pointing in, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: pitch + + The pitch of the vessel relative to the horizon, in degrees. + A value between -90° and +90°. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: heading + + The heading of the vessel (its angle relative to north), in degrees. + A value between 0° and 360°. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: roll + + The roll of the vessel relative to the horizon, in degrees. + A value between -180° and +180°. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: prograde + + The prograde direction of the vessels orbit, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: retrograde + + The retrograde direction of the vessels orbit, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: normal + + The direction normal to the vessels orbit, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: anti_normal + + The direction opposite to the normal of the vessels orbit, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: radial + + The radial direction of the vessels orbit, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: anti_radial + + The direction opposite to the radial direction of the vessels orbit, + in the reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: atmosphere_density + + The current density of the atmosphere around the vessel, in :math:`kg/m^3`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: dynamic_pressure + + The dynamic pressure acting on the vessel, in Pascals. This is a measure of the + strength of the aerodynamic forces. It is equal to + :math:`\frac{1}{2} . \mbox{air density} . \mbox{velocity}^2`. + It is commonly denoted :math:`Q`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: static_pressure + + The static atmospheric pressure acting on the vessel, in Pascals. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: static_pressure_at_msl + + The static atmospheric pressure at mean sea level, in Pascals. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: aerodynamic_force + + The total aerodynamic forces acting on the vessel, + in reference frame :class:`ReferenceFrame`. + + :Attribute: Read-only, cannot be set + :returns: A vector pointing in the direction that the force acts, with its magnitude equal to the strength of the force in Newtons. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: simulate_aerodynamic_force_at(body, position, velocity) + + Simulate and return the total aerodynamic forces acting on the vessel, + if it where to be traveling with the given velocity at the given position in the + atmosphere of the given celestial body. + + :param CelestialBody body: + :param tuple position: + :param tuple velocity: + :returns: A vector pointing in the direction that the force acts, with its magnitude equal to the strength of the force in Newtons. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: lift + + The `aerodynamic lift `_ + currently acting on the vessel. + + :Attribute: Read-only, cannot be set + :returns: A vector pointing in the direction that the force acts, with its magnitude equal to the strength of the force in Newtons. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: drag + + The `aerodynamic drag `_ currently acting on the vessel. + + :Attribute: Read-only, cannot be set + :returns: A vector pointing in the direction of the force, with its magnitude equal to the strength of the force in Newtons. + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: speed_of_sound + + The speed of sound, in the atmosphere around the vessel, in :math:`m/s`. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: mach + + The speed of the vessel, in multiples of the speed of sound. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: reynolds_number + + The vessels Reynolds number. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Requires `Ferram Aerospace Research `_. + + .. attribute:: true_air_speed + + The `true air speed `_ + of the vessel, in meters per second. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: equivalent_air_speed + + The `equivalent air speed `_ + of the vessel, in meters per second. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: terminal_velocity + + An estimate of the current terminal velocity of the vessel, in meters per second. + This is the speed at which the drag forces cancel out the force of gravity. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: angle_of_attack + + The pitch angle between the orientation of the vessel and its velocity vector, + in degrees. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: sideslip_angle + + The yaw angle between the orientation of the vessel and its velocity vector, in degrees. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: total_air_temperature + + The `total air temperature `_ + of the atmosphere around the vessel, in Kelvin. + This includes the :attr:`Flight.static_air_temperature` and the vessel's kinetic energy. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: static_air_temperature + + The `static (ambient) temperature `_ of the atmosphere around the vessel, in Kelvin. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: stall_fraction + + The current amount of stall, between 0 and 1. A value greater than 0.005 indicates + a minor stall and a value greater than 0.5 indicates a large-scale stall. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Requires `Ferram Aerospace Research `_. + + .. attribute:: drag_coefficient + + The coefficient of drag. This is the amount of drag produced by the vessel. + It depends on air speed, air density and wing area. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Requires `Ferram Aerospace Research `_. + + .. attribute:: lift_coefficient + + The coefficient of lift. This is the amount of lift produced by the vessel, and + depends on air speed, air density and wing area. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Requires `Ferram Aerospace Research `_. + + .. attribute:: ballistic_coefficient + + The `ballistic coefficient `_. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Requires `Ferram Aerospace Research `_. + + .. attribute:: thrust_specific_fuel_consumption + + The thrust specific fuel consumption for the jet engines on the vessel. This is a + measure of the efficiency of the engines, with a lower value indicating a more + efficient vessel. This value is the number of Newtons of fuel that are burned, + per hour, to produce one newton of thrust. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Requires `Ferram Aerospace Research `_. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +Orbit +===== + + +.. class:: Orbit + + Describes an orbit. For example, the orbit of a vessel, obtained by calling + :attr:`Vessel.orbit`, or a celestial body, obtained by calling + :attr:`CelestialBody.orbit`. + + .. attribute:: body + + The celestial body (e.g. planet or moon) around which the object is orbiting. + + :Attribute: Read-only, cannot be set + :rtype: :class:`CelestialBody` + + + .. attribute:: apoapsis + + Gets the apoapsis of the orbit, in meters, from the center of mass + of the body being orbited. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. note:: + + For the apoapsis altitude reported on the in-game map view, + use :attr:`Orbit.apoapsis_altitude`. + + .. attribute:: periapsis + + The periapsis of the orbit, in meters, from the center of mass + of the body being orbited. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. note:: + + For the periapsis altitude reported on the in-game map view, + use :attr:`Orbit.periapsis_altitude`. + + .. attribute:: apoapsis_altitude + + The apoapsis of the orbit, in meters, above the sea level of the body being orbited. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. note:: + + This is equal to :attr:`Orbit.apoapsis` minus the equatorial radius of the body. + + .. attribute:: periapsis_altitude + + The periapsis of the orbit, in meters, above the sea level of the body being orbited. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. note:: + + This is equal to :attr:`Orbit.periapsis` minus the equatorial radius of the body. + + .. attribute:: semi_major_axis + + The semi-major axis of the orbit, in meters. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: semi_minor_axis + + The semi-minor axis of the orbit, in meters. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: radius + + The current radius of the orbit, in meters. This is the distance between the center + of mass of the object in orbit, and the center of mass of the body around which it + is orbiting. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. note:: + + This value will change over time if the orbit is elliptical. + + .. method:: radius_at(ut) + + The orbital radius at the given time, in meters. + + :param float ut: The universal time to measure the radius at. + :rtype: float + + + .. method:: position_at(ut, reference_frame) + + The position at a given time, in the specified reference frame. + + :param float ut: The universal time to measure the position at. + :param ReferenceFrame reference_frame: The reference frame that the returned position vector is in. + :returns: The position as a vector. + :rtype: tuple(float, float, float) + + + .. attribute:: speed + + The current orbital speed of the object in meters per second. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. note:: + + This value will change over time if the orbit is elliptical. + + .. attribute:: period + + The orbital period, in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: time_to_apoapsis + + The time until the object reaches apoapsis, in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: time_to_periapsis + + The time until the object reaches periapsis, in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: eccentricity + + The `eccentricity `_ + of the orbit. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: inclination + + The `inclination `_ + of the orbit, + in radians. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: longitude_of_ascending_node + + The `longitude of the ascending node `_, in radians. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: argument_of_periapsis + + The `argument of periapsis `_, in radians. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: mean_anomaly_at_epoch + + The `mean anomaly at epoch `_. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: epoch + + The time since the epoch (the point at which the + `mean anomaly at epoch `_ + was measured, in seconds. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: mean_anomaly + + The `mean anomaly `_. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. method:: mean_anomaly_at_ut(ut) + + The mean anomaly at the given time. + + :param float ut: The universal time in seconds. + :rtype: float + + + .. attribute:: eccentric_anomaly + + The `eccentric anomaly `_. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. method:: eccentric_anomaly_at_ut(ut) + + The eccentric anomaly at the given universal time. + + :param float ut: The universal time, in seconds. + :rtype: float + + + .. attribute:: true_anomaly + + The `true anomaly `_. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. method:: true_anomaly_at_ut(ut) + + The true anomaly at the given time. + + :param float ut: The universal time in seconds. + :rtype: float + + + .. method:: true_anomaly_at_radius(radius) + + The true anomaly at the given orbital radius. + + :param float radius: The orbital radius in meters. + :rtype: float + + + .. method:: ut_at_true_anomaly(true_anomaly) + + The universal time, in seconds, corresponding to the given true anomaly. + + :param float true_anomaly: True anomaly. + :rtype: float + + + .. method:: radius_at_true_anomaly(true_anomaly) + + The orbital radius at the point in the orbit given by the true anomaly. + + :param float true_anomaly: The true anomaly. + :rtype: float + + + .. method:: true_anomaly_at_an(target) + + The true anomaly of the ascending node with the given target orbit. + + :param Orbit target: Target orbit. + :rtype: float + + + .. method:: true_anomaly_at_dn(target) + + The true anomaly of the descending node with the given target orbit. + + :param Orbit target: Target orbit. + :rtype: float + + + .. attribute:: orbital_speed + + The current orbital speed in meters per second. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. method:: orbital_speed_at(time) + + The orbital speed at the given time, in meters per second. + + :param float time: Time from now, in seconds. + :rtype: float + + + .. staticmethod:: reference_plane_normal(reference_frame) + + The direction that is normal to the orbits reference plane, + in the given reference frame. + The reference plane is the plane from which the orbits inclination is measured. + + :param ReferenceFrame reference_frame: The reference frame that the returned direction is in. + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + + + .. staticmethod:: reference_plane_direction(reference_frame) + + The direction from which the orbits longitude of ascending node is measured, + in the given reference frame. + + :param ReferenceFrame reference_frame: The reference frame that the returned direction is in. + :returns: The direction as a unit vector. + :rtype: tuple(float, float, float) + + + .. method:: relative_inclination(target) + + Relative inclination of this orbit and the target orbit, in radians. + + :param Orbit target: Target orbit. + :rtype: float + + + .. attribute:: time_to_soi_change + + The time until the object changes sphere of influence, in seconds. Returns ``NaN`` + if the object is not going to change sphere of influence. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: next_orbit + + If the object is going to change sphere of influence in the future, returns the new + orbit after the change. Otherwise returns ``None``. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Orbit` + + + .. method:: time_of_closest_approach(target) + + Estimates and returns the time at closest approach to a target orbit. + + :param Orbit target: Target orbit. + :returns: The universal time at closest approach, in seconds. + :rtype: float + + + .. method:: distance_at_closest_approach(target) + + Estimates and returns the distance at closest approach to a target orbit, in meters. + + :param Orbit target: Target orbit. + :rtype: float + + + .. method:: list_closest_approaches(target, orbits) + + Returns the times at closest approach and corresponding distances, to a target orbit. + + :param Orbit target: Target orbit. + :param int orbits: The number of future orbits to search. + :returns: A list of two lists. The first is a list of times at closest approach, as universal times in seconds. The second is a list of corresponding distances at closest approach, in meters. + :rtype: list(list(float)) + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +Control +======= + + +.. class:: Control + + Used to manipulate the controls of a vessel. This includes adjusting the + throttle, enabling/disabling systems such as SAS and RCS, or altering the + direction in which the vessel is pointing. + Obtained by calling :attr:`Vessel.control`. + + .. note:: + + Control inputs (such as pitch, yaw and roll) are zeroed when all clients + that have set one or more of these inputs are no longer connected. + + .. attribute:: source + + The source of the vessels control, for example by a kerbal or a probe core. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ControlSource` + :Game Scenes: Flight + + .. attribute:: state + + The control state of the vessel. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ControlState` + :Game Scenes: Flight + + .. attribute:: sas + + The state of SAS. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + .. note:: + + Equivalent to :attr:`AutoPilot.sas` + + .. attribute:: sas_mode + + The current :class:`SASMode`. + These modes are equivalent to the mode buttons to + the left of the navball that appear when SAS is enabled. + + :Attribute: Can be read or written + :rtype: :class:`SASMode` + :Game Scenes: Flight + + + .. note:: + + Equivalent to :attr:`AutoPilot.sas_mode` + + .. attribute:: speed_mode + + The current :class:`SpeedMode` of the navball. + This is the mode displayed next to the speed at the top of the navball. + + :Attribute: Can be read or written + :rtype: :class:`SpeedMode` + :Game Scenes: Flight + + .. attribute:: rcs + + The state of RCS. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: reaction_wheels + + Returns whether all reactive wheels on the vessel are active, + and sets the active state of all reaction wheels. + See :attr:`ReactionWheel.active`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: gear + + The state of the landing gear/legs. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: legs + + Returns whether all landing legs on the vessel are deployed, + and sets the deployment state of all landing legs. + Does not include wheels (for example landing gear). + See :attr:`Leg.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: wheels + + Returns whether all wheels on the vessel are deployed, + and sets the deployment state of all wheels. + Does not include landing legs. + See :attr:`Wheel.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: lights + + The state of the lights. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: brakes + + The state of the wheel brakes. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: antennas + + Returns whether all antennas on the vessel are deployed, + and sets the deployment state of all antennas. + See :attr:`Antenna.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: cargo_bays + + Returns whether any of the cargo bays on the vessel are open, + and sets the open state of all cargo bays. + See :attr:`CargoBay.open`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: intakes + + Returns whether all of the air intakes on the vessel are open, + and sets the open state of all air intakes. + See :attr:`Intake.open`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: parachutes + + Returns whether all parachutes on the vessel are deployed, + and sets the deployment state of all parachutes. + Cannot be set to ``False``. + See :attr:`Parachute.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: radiators + + Returns whether all radiators on the vessel are deployed, + and sets the deployment state of all radiators. + See :attr:`Radiator.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: resource_harvesters + + Returns whether all of the resource harvesters on the vessel are deployed, + and sets the deployment state of all resource harvesters. + See :attr:`ResourceHarvester.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: resource_harvesters_active + + Returns whether any of the resource harvesters on the vessel are active, + and sets the active state of all resource harvesters. + See :attr:`ResourceHarvester.active`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: solar_panels + + Returns whether all solar panels on the vessel are deployed, + and sets the deployment state of all solar panels. + See :attr:`SolarPanel.deployed`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: abort + + The state of the abort action group. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: throttle + + The state of the throttle. A value between 0 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: input_mode + + Sets the behavior of the pitch, yaw, roll and translation control inputs. + When set to additive, these inputs are added to the vessels current inputs. + This mode is the default. + When set to override, these inputs (if non-zero) override the vessels inputs. + This mode prevents keyboard control, or SAS, from interfering with the controls when + they are set. + + :Attribute: Can be read or written + :rtype: :class:`ControlInputMode` + :Game Scenes: Flight + + .. attribute:: pitch + + The state of the pitch control. + A value between -1 and 1. + Equivalent to the w and s keys. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: yaw + + The state of the yaw control. + A value between -1 and 1. + Equivalent to the a and d keys. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: roll + + The state of the roll control. + A value between -1 and 1. + Equivalent to the q and e keys. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: forward + + The state of the forward translational control. + A value between -1 and 1. + Equivalent to the h and n keys. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: up + + The state of the up translational control. + A value between -1 and 1. + Equivalent to the i and k keys. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: right + + The state of the right translational control. + A value between -1 and 1. + Equivalent to the j and l keys. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: wheel_throttle + + The state of the wheel throttle. + A value between -1 and 1. + A value of 1 rotates the wheels forwards, a value of -1 rotates + the wheels backwards. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: wheel_steering + + The state of the wheel steering. + A value between -1 and 1. + A value of 1 steers to the left, and a value of -1 steers to the right. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: custom_axis01 + + The state of CustomAxis01. + A value between -1 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: custom_axis02 + + The state of CustomAxis02. + A value between -1 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: custom_axis03 + + The state of CustomAxis03. + A value between -1 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: custom_axis04 + + The state of CustomAxis04. + A value between -1 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: current_stage + + The current stage of the vessel. Corresponds to the stage number in + the in-game UI. + + :Attribute: Read-only, cannot be set + :rtype: int + :Game Scenes: Flight + + .. method:: activate_next_stage() + + Activates the next stage. Equivalent to pressing the space bar in-game. + + :returns: A list of vessel objects that are jettisoned from the active vessel. + :rtype: list(:class:`Vessel`) + :Game Scenes: Flight + + + .. note:: + + When called, the active vessel may change. It is therefore possible that, + after calling this function, the object(s) returned by previous call(s) to + :attr:`active_vessel` no longer refer to the active vessel. + Throws an exception if staging is locked. + + .. attribute:: stage_lock + + Whether staging is locked on the vessel. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + .. note:: + + This is equivalent to locking the staging using Alt+L + + .. method:: get_action_group(group) + + Returns ``True`` if the given action group is enabled. + + :param int group: A number between 0 and 9 inclusive, or between 0 and 250 inclusive when the `Extended Action Groups mod `_ is installed. + :rtype: bool + :Game Scenes: Flight + + .. method:: set_action_group(group, state) + + Sets the state of the given action group. + + :param int group: A number between 0 and 9 inclusive, or between 0 and 250 inclusive when the `Extended Action Groups mod `_ is installed. + :param bool state: + :Game Scenes: Flight + + .. method:: toggle_action_group(group) + + Toggles the state of the given action group. + + :param int group: A number between 0 and 9 inclusive, or between 0 and 250 inclusive when the `Extended Action Groups mod `_ is installed. + :Game Scenes: Flight + + .. method:: add_node(ut, [prograde = 0.0], [normal = 0.0], [radial = 0.0]) + + Creates a maneuver node at the given universal time, and returns a + :class:`Node` object that can be used to modify it. + Optionally sets the magnitude of the delta-v for the maneuver node + in the prograde, normal and radial directions. + + :param float ut: Universal time of the maneuver node. + :param float prograde: Delta-v in the prograde direction. + :param float normal: Delta-v in the normal direction. + :param float radial: Delta-v in the radial direction. + :rtype: :class:`Node` + :Game Scenes: Flight + + .. attribute:: nodes + + Returns a list of all existing maneuver nodes, ordered by time from first to last. + + :Attribute: Read-only, cannot be set + :rtype: list(:class:`Node`) + :Game Scenes: Flight + + .. method:: remove_nodes() + + Remove all maneuver nodes. + + :Game Scenes: Flight + + + +.. class:: ControlState + + The control state of a vessel. + See :attr:`Control.state`. + + + .. data:: full + + Full controllable. + + + .. data:: partial + + Partially controllable. + + + .. data:: none + + Not controllable. + + + +.. class:: ControlSource + + The control source of a vessel. + See :attr:`Control.source`. + + + .. data:: kerbal + + Vessel is controlled by a Kerbal. + + + .. data:: probe + + Vessel is controlled by a probe core. + + + .. data:: none + + Vessel is not controlled. + + + +.. class:: SASMode + + The behavior of the SAS auto-pilot. See :attr:`AutoPilot.sas_mode`. + + + .. data:: stability_assist + + Stability assist mode. Dampen out any rotation. + + + .. data:: maneuver + + Point in the burn direction of the next maneuver node. + + + .. data:: prograde + + Point in the prograde direction. + + + .. data:: retrograde + + Point in the retrograde direction. + + + .. data:: normal + + Point in the orbit normal direction. + + + .. data:: anti_normal + + Point in the orbit anti-normal direction. + + + .. data:: radial + + Point in the orbit radial direction. + + + .. data:: anti_radial + + Point in the orbit anti-radial direction. + + + .. data:: target + + Point in the direction of the current target. + + + .. data:: anti_target + + Point away from the current target. + + + +.. class:: SpeedMode + + The mode of the speed reported in the navball. + See :attr:`Control.speed_mode`. + + + .. data:: orbit + + Speed is relative to the vessel's orbit. + + + .. data:: surface + + Speed is relative to the surface of the body being orbited. + + + .. data:: target + + Speed is relative to the current target. + + + +.. class:: ControlInputMode + + See :attr:`Control.input_mode`. + + + .. data:: additive + + Control inputs are added to the vessels current control inputs. + + + .. data:: override + + Control inputs (when they are non-zero) override the vessels current control inputs. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +Resources +========= + + +.. class:: Resources + + Represents the collection of resources stored in a vessel, stage or part. + Created by calling :attr:`Vessel.resources`, + :meth:`Vessel.resources_in_decouple_stage` or + :attr:`Part.resources`. + + .. attribute:: all + + All the individual resources that can be stored. + + :Attribute: Read-only, cannot be set + :rtype: list(:class:`Resource`) + :Game Scenes: Flight + + .. method:: with_resource(name) + + All the individual resources with the given name that can be stored. + + :param str name: + :rtype: list(:class:`Resource`) + :Game Scenes: Flight + + .. attribute:: names + + A list of resource names that can be stored. + + :Attribute: Read-only, cannot be set + :rtype: list(str) + :Game Scenes: Flight + + .. method:: has_resource(name) + + Check whether the named resource can be stored. + + :param str name: The name of the resource. + :rtype: bool + :Game Scenes: Flight + + .. method:: amount(name) + + Returns the amount of a resource that is currently stored. + + :param str name: The name of the resource. + :rtype: float + :Game Scenes: Flight + + .. method:: max(name) + + Returns the amount of a resource that can be stored. + + :param str name: The name of the resource. + :rtype: float + :Game Scenes: Flight + + .. staticmethod:: density(name) + + Returns the density of a resource, in :math:`kg/l`. + + :param str name: The name of the resource. + :rtype: float + :Game Scenes: Flight + + .. staticmethod:: flow_mode(name) + + Returns the flow mode of a resource. + + :param str name: The name of the resource. + :rtype: :class:`ResourceFlowMode` + :Game Scenes: Flight + + .. attribute:: enabled + + Whether use of all the resources are enabled. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + .. note:: + + This is ``True`` if all of the resources are enabled. + If any of the resources are not enabled, this is ``False``. + + + +.. class:: Resource + + An individual resource stored within a part. + Created using methods in the :class:`Resources` class. + + .. attribute:: name + + The name of the resource. + + :Attribute: Read-only, cannot be set + :rtype: str + + + .. attribute:: part + + The part containing the resource. + + :Attribute: Read-only, cannot be set + :rtype: :class:`Part` + + + .. attribute:: amount + + The amount of the resource that is currently stored in the part. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: max + + The total amount of the resource that can be stored in the part. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: density + + The density of the resource, in :math:`kg/l`. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: flow_mode + + The flow mode of the resource. + + :Attribute: Read-only, cannot be set + :rtype: :class:`ResourceFlowMode` + + + .. attribute:: enabled + + Whether use of this resource is enabled. + + :Attribute: Can be read or written + :rtype: bool + + + + +.. class:: ResourceTransfer + + Transfer resources between parts. + + .. staticmethod:: start(from_part, to_part, resource, max_amount) + + Start transferring a resource transfer between a pair of parts. The transfer will move + at most *max_amount* units of the resource, depending on how much of + the resource is available in the source part and how much storage is available in the + destination part. + Use :attr:`ResourceTransfer.complete` to check if the transfer is complete. + Use :attr:`ResourceTransfer.amount` to see how much of the resource has been transferred. + + :param Part from_part: The part to transfer to. + :param Part to_part: The part to transfer from. + :param str resource: The name of the resource to transfer. + :param float max_amount: The maximum amount of resource to transfer. + :rtype: :class:`ResourceTransfer` + + + .. attribute:: amount + + The amount of the resource that has been transferred. + + :Attribute: Read-only, cannot be set + :rtype: float + + + .. attribute:: complete + + Whether the transfer has completed. + + :Attribute: Read-only, cannot be set + :rtype: bool + + + + +.. class:: ResourceFlowMode + + The way in which a resource flows between parts. See :meth:`Resources.flow_mode`. + + + .. data:: vessel + + The resource flows to any part in the vessel. For example, electric charge. + + + .. data:: stage + + The resource flows from parts in the first stage, followed by the second, + and so on. For example, mono-propellant. + + + .. data:: adjacent + + The resource flows between adjacent parts within the vessel. For example, + liquid fuel or oxidizer. + + + .. data:: none + + The resource does not flow. For example, solid fuel. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: SpaceCenter + +AutoPilot +========= + + +.. class:: AutoPilot + + Provides basic auto-piloting utilities for a vessel. + Created by calling :attr:`Vessel.auto_pilot`. + + .. note:: + + If a client engages the auto-pilot and then closes its connection to the server, + the auto-pilot will be disengaged and its target reference frame, direction and roll + reset to default. + + .. method:: engage() + + Engage the auto-pilot. + + :Game Scenes: Flight + + .. method:: disengage() + + Disengage the auto-pilot. + + :Game Scenes: Flight + + .. method:: wait() + + Blocks until the vessel is pointing in the target direction and has + the target roll (if set). Throws an exception if the auto-pilot has not been engaged. + + :Game Scenes: Flight + + .. attribute:: error + + The error, in degrees, between the direction the ship has been asked + to point in and the direction it is pointing in. Throws an exception if the auto-pilot + has not been engaged and SAS is not enabled or is in stability assist mode. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: pitch_error + + The error, in degrees, between the vessels current and target pitch. + Throws an exception if the auto-pilot has not been engaged. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: heading_error + + The error, in degrees, between the vessels current and target heading. + Throws an exception if the auto-pilot has not been engaged. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: roll_error + + The error, in degrees, between the vessels current and target roll. + Throws an exception if the auto-pilot has not been engaged or no target roll is set. + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: reference_frame + + The reference frame for the target direction (:attr:`AutoPilot.target_direction`). + + :Attribute: Can be read or written + :rtype: :class:`ReferenceFrame` + :Game Scenes: Flight + + + .. note:: + + An error will be thrown if this property is set to a reference frame that rotates with + the vessel being controlled, as it is impossible to rotate the vessel in such a + reference frame. + + .. attribute:: target_pitch + + The target pitch, in degrees, between -90° and +90°. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: target_heading + + The target heading, in degrees, between 0° and 360°. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: target_roll + + The target roll, in degrees. ``NaN`` if no target roll is set. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: target_direction + + Direction vector corresponding to the target pitch and heading. + This is in the reference frame specified by :class:`ReferenceFrame`. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: target_pitch_and_heading(pitch, heading) + + Set target pitch and heading angles. + + :param float pitch: Target pitch angle, in degrees between -90° and +90°. + :param float heading: Target heading angle, in degrees between 0° and 360°. + :Game Scenes: Flight + + .. attribute:: sas + + The state of SAS. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + .. note:: + + Equivalent to :attr:`Control.sas` + + .. attribute:: sas_mode + + The current :class:`SASMode`. + These modes are equivalent to the mode buttons to the left of the navball that appear + when SAS is enabled. + + :Attribute: Can be read or written + :rtype: :class:`SASMode` + :Game Scenes: Flight + + + .. note:: + + Equivalent to :attr:`Control.sas_mode` + + .. attribute:: roll_threshold + + The threshold at which the autopilot will try to match the target roll angle, if any. + Defaults to 5 degrees. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: stopping_time + + The maximum amount of time that the vessel should need to come to a complete stop. + This determines the maximum angular velocity of the vessel. + A vector of three stopping times, in seconds, one for each of the pitch, roll + and yaw axes. Defaults to 0.5 seconds for each axis. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: deceleration_time + + The time the vessel should take to come to a stop pointing in the target direction. + This determines the angular acceleration used to decelerate the vessel. + A vector of three times, in seconds, one for each of the pitch, roll and yaw axes. + Defaults to 5 seconds for each axis. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: attenuation_angle + + The angle at which the autopilot considers the vessel to be pointing + close to the target. + This determines the midpoint of the target velocity attenuation function. + A vector of three angles, in degrees, one for each of the pitch, roll and yaw axes. + Defaults to 1° for each axis. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: auto_tune + + Whether the rotation rate controllers PID parameters should be automatically tuned + using the vessels moment of inertia and available torque. Defaults to ``True``. + See :attr:`AutoPilot.time_to_peak` and :attr:`AutoPilot.overshoot`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: time_to_peak + + The target time to peak used to autotune the PID controllers. + A vector of three times, in seconds, for each of the pitch, roll and yaw axes. + Defaults to 3 seconds for each axis. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: overshoot + + The target overshoot percentage used to autotune the PID controllers. + A vector of three values, between 0 and 1, for each of the pitch, roll and yaw axes. + Defaults to 0.01 for each axis. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: pitch_pid_gains + + Gains for the pitch PID controller. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + + .. note:: + + When :attr:`AutoPilot.auto_tune` is true, these values are updated automatically, + which will overwrite any manual changes. + + .. attribute:: roll_pid_gains + + Gains for the roll PID controller. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + + .. note:: + + When :attr:`AutoPilot.auto_tune` is true, these values are updated automatically, + which will overwrite any manual changes. + + .. attribute:: yaw_pid_gains + + Gains for the yaw PID controller. + + :Attribute: Can be read or written + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + + .. note:: + + When :attr:`AutoPilot.auto_tune` is true, these values are updated automatically, + which will overwrite any manual changes. \ No newline at end of file diff --git a/kosmos/prompts/mechjeb_readmellm.txt b/kosmos/prompts/mechjeb_readmellm.txt new file mode 100644 index 0000000..aabb029 --- /dev/null +++ b/kosmos/prompts/mechjeb_readmellm.txt @@ -0,0 +1,3349 @@ +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +MechJeb service +=============== + + +.. module:: MechJeb + +This service provides functionality to interact with `MechJeb 2 `_. + + +.. attribute:: api_ready + + A value indicating whether the service is available. + + :Attribute: Read-only, cannot be set + :rtype: bool + :Game Scenes: Flight + + + + + +.. attribute:: airplane_autopilot + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`AirplaneAutopilot` + :Game Scenes: Flight + + + + + +.. attribute:: antenna_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`DeployableController` + :Game Scenes: Flight + + + + + +.. attribute:: ascent_autopilot + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`AscentAutopilot` + :Game Scenes: Flight + + + + + +.. attribute:: docking_autopilot + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`DockingAutopilot` + :Game Scenes: Flight + + + + + +.. attribute:: landing_autopilot + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`LandingAutopilot` + :Game Scenes: Flight + + + + + +.. attribute:: maneuver_planner + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`ManeuverPlanner` + :Game Scenes: Flight + + + + + +.. attribute:: node_executor + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`NodeExecutor` + :Game Scenes: Flight + + + + + +.. attribute:: rcs_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`RCSController` + :Game Scenes: Flight + + + + + +.. attribute:: rendezvous_autopilot + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`RendezvousAutopilot` + :Game Scenes: Flight + + + + + +.. attribute:: smart_ass + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`SmartASS` + :Game Scenes: Flight + + + + + +.. attribute:: smart_rcs + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`SmartRCS` + :Game Scenes: Flight + + + + + +.. attribute:: solar_panel_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`DeployableController` + :Game Scenes: Flight + + + + + +.. attribute:: staging_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`StagingController` + :Game Scenes: Flight + + + + + +.. attribute:: target_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TargetController` + :Game Scenes: Flight + + + + + +.. attribute:: thrust_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`ThrustController` + :Game Scenes: Flight + + + + + +.. attribute:: translatron + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`Translatron` + :Game Scenes: Flight + + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +AscentAutopilot +=============== + + +.. class:: AscentAutopilot + + This module controls the Ascent Guidance in MechJeb 2. + + .. note:: + + See `MechJeb2 wiki `_ for more guidance on how to optimally set up this autopilot. + + .. attribute:: enabled + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: status + + The autopilot status; it depends on the selected ascent path. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. attribute:: ascent_path_index + + The selected ascent path. + + 0 = :class:`AscentClassic` (Classic Ascent Profile) + + 1 = :class:`AscentGT` (Stock-style GravityTurn) + + 2 = :class:`AscentPVG` (Primer Vector Guidance (RSS/RO)) + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: ascent_path_classic + + Get Classic Ascent Profile settings. + + :Attribute: Read-only, cannot be set + :rtype: :class:`AscentClassic` + :Game Scenes: Flight + + .. attribute:: ascent_path_gt + + Get Stock-style GravityTurn profile settings. + + :Attribute: Read-only, cannot be set + :rtype: :class:`AscentGT` + :Game Scenes: Flight + + .. attribute:: ascent_path_pvg + + Get Powered Explicit Guidance (RSS/RO) profile settings. + + :Attribute: Read-only, cannot be set + :rtype: :class:`AscentPVG` + :Game Scenes: Flight + + .. attribute:: desired_inclination + + The desired inclination in degrees for the final circular orbit. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: desired_orbit_altitude + + The desired altitude in meters for the final circular orbit. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: thrust_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`ThrustController` + :Game Scenes: Flight + + + .. note:: + + Equivalent to :attr:`thrust_controller`. + + .. attribute:: force_roll + + The state of force roll. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: turn_roll + + The turn roll used by the autopilot. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: vertical_roll + + The vertical/climb roll used by the autopilot. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: limit_ao_a + + Whether to limit angle of attack. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: max_ao_a + + The maximal angle of attack used by the autopilot. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: ao_a_limit_fadeout_pressure + + The pressure value when AoA limit is automatically deactivated. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: corrective_steering + + Will cause the craft to steer based on the more accurate velocity vector rather than positional vector (large craft may actually perform better with this box unchecked). + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: corrective_steering_gain + + The gain of corrective steering used by the autopilot. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: autostage + + The autopilot will automatically stage when the current stage has run out of fuel. + Paramethers can be set in :class:`StagingController`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: staging_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`StagingController` + :Game Scenes: Flight + + + .. note:: + + Equivalent to :attr:`staging_controller`. + + .. attribute:: autodeploy_solar_panels + + Whether to deploy solar panels automatically when the ascent finishes. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: auto_deploy_antennas + + Whether to deploy antennas automatically when the ascent finishes. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: skip_circularization + + Whether to skip circularization burn and do only the ascent. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: warp_count_down + + + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: launch_lan_difference + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: launch_phase_angle + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: launch_mode + + Current autopilot mode. Useful for determining whether the autopilot is performing a timed launch or not. + + :Attribute: Read-only, cannot be set + :rtype: :class:`AscentLaunchMode` + :Game Scenes: Flight + + .. method:: abort_timed_launch() + + Abort a known timed launch when it has not started yet + + :Game Scenes: Flight + + .. method:: launch_to_rendezvous() + + Launch to rendezvous with the selected target. + + :Game Scenes: Flight + + .. method:: launch_to_target_plane() + + Launch into the plane of the selected target. + + :Game Scenes: Flight + + + +.. class:: AscentLaunchMode + + + + + .. data:: normal + + The autopilot is not performing a timed launch. + + + .. data:: rendezvous + + The autopilot is performing a timed launch to rendezvous with the target vessel. + + + .. data:: target_plane + + The autopilot is performing a timed launch to target plane. + + + .. data:: unknown + + The autopilot is performing an unknown timed launch. + + + +AscentClassic +------------- + + +.. class:: AscentClassic + + The Classic Ascent Profile. + + .. attribute:: auto_path + + Whether to enable automatic altitude turn. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: auto_turn_percent + + A value between 0 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: auto_turn_speed_factor + + A value between 0 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: auto_turn_start_altitude + + + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: auto_turn_start_velocity + + + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: auto_turn_end_altitude + + + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_start_altitude + + The turn starts when this altitude is reached. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_start_velocity + + The turn starts when this velocity is reached. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_end_altitude + + The turn ends when this altitude is reached. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_end_angle + + The final flight path angle. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_shape_exponent + + A value between 0 - 1 describing how steep the turn is. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + +AscentGT +-------- + + +.. class:: AscentGT + + This profile is similar to the gravity turn mod. It is a 3-burn to orbit style of launch that can get to orbit with about 2800 dV on stock Kerbin. + If you want to have fun make a rocket that is basically a nose cone, a jumbo-64 a mainsail and some fairly big fins, have the pitch program flip it over aggressively (uncheck the AoA limiter, set the values to like 0.5 / 50 / 40 / 45 / 1) and let it rip. + + .. note:: + + It's not precisely the GT mod algorithm and it does not do any pitch-up during the intermediate burn right now, so it won't handle low TWR upper stages. + + .. attribute:: hold_ap_time + + At the intermediate altitude with this much time-to-apoapsis left the engine will start burning prograde to lift the apoapsis. + The engine will throttle down in order to burn closer to the apoapsis. + This is very similar to the lead-time of a maneuver node in concept, but with throttling down in the case where the player has initiated the burn too early (the corollary is that if you see lots of throttling down at the start, you likely need less HoldAP time). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: intermediate_altitude + + Intermediate apoapsis altitude to coast to and then raise the apoapsis up to the eventual final target. May be set to equal the final target in order to skip the intermediate phase. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_start_altitude + + Altitude in km to pitch over and initiate the Gravity Turn (higher values for lower-TWR rockets). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_start_pitch + + Pitch that the pitch program immediately applies. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: turn_start_velocity + + Velocity in m/s which triggers pitch over and initiates the Gravity Turn (higher values for lower-TWR rockets). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + +AscentPVG +--------- + + +.. class:: AscentPVG + + The Primer Vector Guidance (RSS/RO) profile. + + .. attribute:: attach_alt_flag + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: desired_apoapsis + + The target apoapsis in meters. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: desired_attach_alt + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: dynamic_pressure_trigger + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: fixed_coast + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: fixed_coast_length + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: pitch_rate + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: pitch_start_velocity + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: staging_trigger + + + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: staging_trigger_flag + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +DockingAutopilot +================ + + +.. class:: DockingAutopilot + + + + .. attribute:: enabled + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: status + + + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. attribute:: speed_limit + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: override_safe_distance + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: overriden_safe_distance + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: override_target_size + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: overriden_target_size + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: safe_distance + + + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: target_size + + + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: force_roll + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: roll + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +LandingAutopilot +================ + + +.. class:: LandingAutopilot + + The Landing Guidance module provides targeted and non-targeted landing autopilot. + + .. attribute:: enabled + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: status + + + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. attribute:: deploy_chutes + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: deploy_gears + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. method:: land_at_position_target() + + + + :Game Scenes: Flight + + .. method:: land_untargeted() + + + + :Game Scenes: Flight + + .. attribute:: limit_chutes_stage + + + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: limit_gears_stage + + + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: rcs_adjustment + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. method:: stop_landing() + + + + :Game Scenes: Flight + + .. attribute:: touchdown_speed + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +RendezvousAutopilot +=================== + + +.. class:: RendezvousAutopilot + + + + .. attribute:: enabled + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: status + + + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. attribute:: desired_distance + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: max_phasing_orbits + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + +.. class:: MJServiceException + + General exception for errors in the service. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +ManeuverPlanner +=============== + + +.. class:: ManeuverPlanner + + + + .. attribute:: operation_apoapsis + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationApoapsis` + :Game Scenes: Flight + + .. attribute:: operation_circularize + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationCircularize` + :Game Scenes: Flight + + .. attribute:: operation_course_correction + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationCourseCorrection` + :Game Scenes: Flight + + .. attribute:: operation_ellipticize + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationEllipticize` + :Game Scenes: Flight + + .. attribute:: operation_inclination + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationInclination` + :Game Scenes: Flight + + .. attribute:: operation_interplanetary_transfer + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationInterplanetaryTransfer` + :Game Scenes: Flight + + .. attribute:: operation_kill_rel_vel + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationKillRelVel` + :Game Scenes: Flight + + .. attribute:: operation_lambert + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationLambert` + :Game Scenes: Flight + + .. attribute:: operation_lan + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationLan` + :Game Scenes: Flight + + .. attribute:: operation_longitude + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationLongitude` + :Game Scenes: Flight + + .. attribute:: operation_moon_return + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationMoonReturn` + :Game Scenes: Flight + + .. attribute:: operation_periapsis + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationPeriapsis` + :Game Scenes: Flight + + .. attribute:: operation_plane + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationPlane` + :Game Scenes: Flight + + .. attribute:: operation_resonant_orbit + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationResonantOrbit` + :Game Scenes: Flight + + .. attribute:: operation_semi_major + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationSemiMajor` + :Game Scenes: Flight + + .. attribute:: operation_transfer + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`OperationTransfer` + :Game Scenes: Flight + + + +.. class:: OperationException + + This exception is thrown when there is something wrong with the operation (e.g. the target is not set when the operation needs it). + + + +TimeSelector +------------ + + +.. class:: TimeSelector + + + + .. attribute:: circularize_altitude + + To be used with :attr:`TimeReference.altitude`. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: lead_time + + To be used with :attr:`TimeReference.x_from_now`. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_reference + + + + :Attribute: Can be read or written + :rtype: :class:`TimeReference` + :Game Scenes: Flight + + + +.. class:: TimeReference + + **IMPORTANT**: `TimeReference` is an enum accessed from the `mj` object, NOT from `maneuver_planner`. + + + .. data:: altitude + + At the selected :attr:`TimeSelector.circularize_altitude`. + + + .. data:: apoapsis + + At the next apoapsis. + + + .. data:: closest_approach + + At the closest approach to the target. + + + .. data:: computed + + At the optimum time. + + + .. data:: eq_ascending + + At the equatorial ascending node. + + + .. data:: eq_descending + + At the equatorial descending node. + + + .. data:: eq_highest_ad + + At the cheapest equatorial AN/DN. + + + .. data:: eq_nearest_ad + + At the nearest equatorial AN/DN. + + + .. data:: periapsis + + At the next periapsis. + + + .. data:: rel_ascending + + At the next ascending node with the target. + + + .. data:: rel_descending + + At the next descending node with the target. + + + .. data:: rel_highest_ad + + At the cheapest AN/DN with the target. + + + .. data:: rel_nearest_ad + + At the nearest AN/DN with the target. + + + .. data:: x_from_now + + After a fixed :attr:`TimeSelector.lead_time`. + + + +Operations +---------- + +OperationApoapsis +^^^^^^^^^^^^^^^^^ + + +.. class:: OperationApoapsis + + Create a maneuver to set a new apoapsis + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_apoapsis + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationCircularize +^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationCircularize + + This mode creates a manevuer to match your apoapsis to periapsis. + To match apoapsis to periapsis, set the time to :attr:`TimeReference.periapsis`; to match periapsis to apoapsis, set the time to :attr:`TimeReference.apoapsis`. These are the most efficient, but it can also create node at specific height or after specific time. + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationCourseCorrection +^^^^^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationCourseCorrection + + Create a maneuver to fine-tune closest approach to target + + .. attribute:: course_correct_final_pe_a + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. attribute:: intercept_distance + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + + +OperationEllipticize +^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationEllipticize + + Create a maneuver to change both periapsis and apoapsis + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_apoapsis + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: new_periapsis + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationInclination +^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationInclination + + Create a maneuver to change inclination + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_inclination + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationInterplanetaryTransfer +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationInterplanetaryTransfer + + Create a maneuver to transfer to another planet + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: wait_for_phase_angle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + +OperationKillRelVel +^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationKillRelVel + + Match velocities with target + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationLambert +^^^^^^^^^^^^^^^^ + + +.. class:: OperationLambert + + Create a maneuver to set the chosen time + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. attribute:: intercept_interval + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationLan +^^^^^^^^^^^^ + + +.. class:: OperationLan + + Change longitude of ascending node + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_lan + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationLongitude +^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationLongitude + + Change surface longitude of apsis + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_surface_longitude + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationMoonReturn +^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationMoonReturn + + Create a maneuver to return from a moon approximately at the specified altitude + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: moon_return_altitude + + Approximate return altitude from a moon (from an orbiting body to the parent body). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + +OperationPeriapsis +^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationPeriapsis + + Create a maneuver to set a new periapsis + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_periapsis + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationPlane +^^^^^^^^^^^^^^ + + +.. class:: OperationPlane + + Create a maneuver to match planes with target + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationResonantOrbit +^^^^^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationResonantOrbit + + Resonant orbit is useful for placing satellites to a constellation. This mode should be used starting from a orbit in the desired orbital plane. Important parameter to this mode is the desired orbital ratio, which is the ratio between period of your current orbit and the new orbit. + To deploy satellites, set the denominator to number of satellites you want to have in the constellation. Setting the nominator to one less than denominator is the most efficient, but not necessary the fastest. To successfully deploy all satellites, make sure the numbers are incommensurable. + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: resonance_denominator + + + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: resonance_numerator + + + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationSemiMajor +^^^^^^^^^^^^^^^^^^ + + +.. class:: OperationSemiMajor + + Create a maneuver to set a new semi-major axis + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: new_semi_major_axis + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + + + +OperationTransfer +^^^^^^^^^^^^^^^^^ + + +.. class:: OperationTransfer + + Bi-impulsive (Hohmann) transfer to target. + + This option is used to plan transfer to target in single sphere of influence. It is suitable for rendezvous with other vessels or moons. + Contrary to the name, the transfer is often uni-impulsive. You can select when you want the manevuer to happen or select optimum time. + + .. attribute:: error_message + + A warning may be stored there during MakeNode() call. + + :Attribute: Read-only, cannot be set + :rtype: str + :Game Scenes: Flight + + .. method:: make_node() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: The first maneuver node necessary to perform this operation. + :rtype: :class:`SpaceCenter.Node` + :Game Scenes: Flight + + + .. note:: + + This method is deprecated, use MakeNodes instead. + + .. method:: make_nodes() + + Execute the operation and create appropriate maneuver nodes. + A warning may be stored in ErrorMessage during this process; so it may be useful to check its value. + + OperationException is thrown when there is something wrong with the operation. + MJServiceException - Internal service error. + + :returns: A list of maneuver nodes necessary to perform this operation + :rtype: list(:class:`SpaceCenter.Node`) + :Game Scenes: Flight + + .. attribute:: intercept_only + + Intercept only, no capture burn (impact/flyby) + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: period_offset + + Fractional target period offset + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: simple_transfer + + Simple coplanar Hohmann transfer. + Set it to true if you are used to the old version of transfer maneuver. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + .. note:: + + If set to true, TimeSelector property is ignored. + + .. attribute:: time_selector + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`TimeSelector` + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +SmartASS +======== + + +.. class:: SmartASS + + The Smart A.S.S. module provides aids for vessel pitch control. + + .. attribute:: interface_mode + + GUI mode; doesn't do anything except changing SmartASS GUI buttons to a specified mode. + + :Attribute: Can be read or written + :rtype: :class:`SmartASSInterfaceMode` + :Game Scenes: Flight + + .. attribute:: autopilot_mode + + Current autopilot mode. + + :Attribute: Can be read or written + :rtype: :class:`SmartASSAutopilotMode` + :Game Scenes: Flight + + .. method:: update(reset_pid) + + Update SmartASS position to use new values. + + :param bool reset_pid: False most of the time, use true only if it doesn't work. + :Game Scenes: Flight + + .. attribute:: force_yaw + + Enable yaw control for :attr:`SmartASS.surface_heading`, :attr:`SmartASSAutopilotMode.surface_prograde` and :attr:`SmartASSAutopilotMode.surface_retrograde`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: force_pitch + + Enable pitch control for :attr:`SmartASS.surface_pitch`, :attr:`SmartASSAutopilotMode.surface_prograde` and :attr:`SmartASSAutopilotMode.surface_retrograde`. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: force_roll + + Enable roll control. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: surface_heading + + Heading; Also called or azimuth, or the direction where you want to go. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.surface` mode. + + .. attribute:: surface_pitch + + Pitch or inclination; 0 is horizontal and 90 is straight up. Can be negative. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.surface` mode. + + .. attribute:: surface_roll + + Roll; 0 is top side up. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.surface` mode. + + .. attribute:: surface_vel_yaw + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.surface_prograde` and :attr:`SmartASSAutopilotMode.surface_retrograde` mode. + + .. attribute:: surface_vel_pitch + + Pitch or inclination; 0 is horizontal and 90 is straight up. Can be negative. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.surface_prograde` and :attr:`SmartASSAutopilotMode.surface_retrograde` mode. + + .. attribute:: surface_vel_roll + + Roll; 0 is top side up. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.surface_prograde` and :attr:`SmartASSAutopilotMode.surface_retrograde` mode. + + .. attribute:: advanced_reference + + + + :Attribute: Can be read or written + :rtype: :class:`AttitudeReference` + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.advanced` mode. + + .. attribute:: advanced_direction + + + + :Attribute: Can be read or written + :rtype: :class:`Direction` + :Game Scenes: Flight + + + .. note:: + + Works only in :attr:`SmartASSAutopilotMode.advanced` mode. + + + +.. class:: SmartASSInterfaceMode + + + + + .. data:: orbital + + + + + .. data:: surface + + + + + .. data:: target + + + + + .. data:: advanced + + + + + .. data:: automatic + + Internal mode, do not set. + + + +.. class:: SmartASSAutopilotMode + + + + + .. data:: off + + Switch off Smart A.S.S. + + + .. data:: kill_rot + + "Kill" the spacecraft's rotation (counters rotation/tumbling). + + + .. data:: node + + Point the vessel to a maneuver node. + + + .. data:: advanced + + Advanced mode. + + + .. data:: automatic + + Automatic mode (internal mode, only for getting status). + + + .. data:: prograde + + ORBIT: Orient to orbital prograde. + + + .. data:: retrograde + + ORBIT: Orient to orbital retrograde. + + + .. data:: normal_plus + + ORBIT: Orient to orbital normal (change inclination). + + + .. data:: normal_minus + + ORBIT: Orient to orbital anti-normal (change inclination). + + + .. data:: radial_plus + + ORBIT: Orient to radial outward (away from SOI). + + + .. data:: radial_minus + + ORBIT: Orient to radial inward (towards SOI). + + + .. data:: surface_prograde + + SURFACE: Orient in the direction of movement relative to the ground. Useful during lift-off for rockets which don't have fins or are otherwise instable. + + + .. data:: surface_retrograde + + SURFACE: Orient in the opposite direction of movement relative to the ground. Useful during reentry or aerobraking with an aerodynamically unstable craft. + + + .. data:: horizontal_plus + + SURFACE: Orient in the direction of horizontal movement relative to the ground. + + + .. data:: horizontal_minus + + SURFACE: Orient in the opposite direction of horizontal movement relative to the ground. + + + .. data:: surface + + SURFACE: Orient the vessel in specific direction relative to surface. + + + .. data:: vertical_plus + + SURFACE: Orient "up", perpendicular to the surface. + + + .. data:: target_plus + + TARGET: Orient towards the target. + + + .. data:: target_minus + + TARGET: Orient away from the target. + + + .. data:: relative_plus + + TARGET: Orient toward your relative velocity. Burning this direction will increase your relative velocity. + + + .. data:: relative_minus + + TARGET: Orient away from your relative velocity. Burning this direction will decrease your relative velocity. + + + .. data:: parallel_plus + + TARGET: Orient parallel to the target's orientation. If the target is a docking node it orients the ship along the docking axis, pointing away from the node. + + + .. data:: parallel_minus + + TARGET: Orient antiparallel to the target's orientation. If the target is a docking node it orients the ship along the docking axis, pointing toward the node. + + + +.. class:: AttitudeReference + + + + + .. data:: inertial + + World coordinate system. + + + .. data:: orbit + + forward = prograde, left = normal plus, up = radial plus + + + .. data:: orbit_horizontal + + forward = surface projection of orbit velocity, up = surface normal + + + .. data:: surface_north + + forward = north, left = west, up = surface normal + + + .. data:: surface_velocity + + forward = surface frame vessel velocity, up = perpendicular component of surface normal + + + .. data:: target + + forward = toward target, up = perpendicular component of vessel heading + + + .. data:: relative_velocity + + forward = toward relative velocity direction, up = tbd + + + .. data:: target_orientation + + forward = direction target is facing, up = target up + + + .. data:: maneuver_node + + forward = next maneuver node direction, up = tbd + + + .. data:: sun + + forward = orbit velocity of the parent body orbiting the sun, up = radial plus of that orbit + + + .. data:: surface_horizontal + + forward = surface velocity horizontal component, up = surface normal + + + +.. class:: Direction + + + + + .. data:: forward + + + + + .. data:: back + + + + + .. data:: up + + + + + .. data:: down + + + + + .. data:: right + + + + + .. data:: left + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +SmartRCS +======== + + +.. class:: SmartRCS + + + + .. attribute:: auto_disable_smart_rcs + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: mode + + + + :Attribute: Can be read or written + :rtype: :class:`SmartRCSMode` + :Game Scenes: Flight + + .. attribute:: rcs_controller + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`RCSController` + :Game Scenes: Flight + + + +.. class:: SmartRCSMode + + + + + .. data:: off + + + + + .. data:: zero_relative_velocity + + + + + .. data:: zero_velocity + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +Translatron +=========== + + +.. class:: Translatron + + The Translatron module controls the vessel's throttle/velocity. + + .. attribute:: mode + + Current translatron mode. + + :Attribute: Can be read or written + :rtype: :class:`TranslatronMode` + :Game Scenes: Flight + + .. attribute:: translation_speed + + Speed which trasnlatron will hold + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: kill_horizontal_speed + + Kill horizontal speed + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. method:: panic_switch() + + Abort mission by seperating all but the last stage and activating landing autopilot. + + :Game Scenes: Flight + + + +.. class:: TranslatronMode + + + + + .. data:: off + + Switch off Translatron. + + + .. data:: keep_orbital + + Keep orbital velocity. + + + .. data:: keep_surface + + Keep surface velocity. + + + .. data:: keep_vertical + + Keep vertical velocity (climb/descent speed). + + + .. data:: keep_relative + + Internal mode, do not set. + + + .. data:: direct + + Internal mode, do not set. + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +DeployableController +==================== + + +.. class:: DeployableController + + + + .. method:: all_retracted() + + Check if all deployable modules of this type are retracted. + + :returns: True if all modules are retracted; False otherwise + :rtype: bool + :Game Scenes: Flight + + .. attribute:: auto_deploy + + Automatically deploy modules of this type when controlled by a MechJeb autopilot + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. method:: extend_all() + + Extend all deployable modules of this type. + + :Game Scenes: Flight + + .. method:: retract_all() + + Retract all deployable modules of this type. + + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +NodeExecutor +============ + + +.. class:: NodeExecutor + + + + .. attribute:: enabled + + + + :Attribute: Read-only, cannot be set + :rtype: bool + :Game Scenes: Flight + + .. method:: abort() + + + + :Game Scenes: Flight + + .. attribute:: autowarp + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. method:: execute_all_nodes() + + + + :Game Scenes: Flight + + .. method:: execute_one_node() + + + + :Game Scenes: Flight + + .. attribute:: lead_time + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: tolerance + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +RCSController +============= + + +.. class:: RCSController + + + + .. attribute:: rcs_for_rotation + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: rcs_throttle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +StagingController +================= + + +.. class:: StagingController + + + + .. attribute:: enabled + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: autostaging_once + + The autostaging mode. If set to true, it will automatically disable itself after one staging action. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + + .. note:: + + The controller needs to be enabled for this to work. + + .. attribute:: autostage_limit + + Stop at the selected stage - staging will not occur beyond this stage number. + + :Attribute: Can be read or written + :rtype: int + :Game Scenes: Flight + + .. attribute:: autostage_post_delay + + The autopilot will pause the actual staging after ? seconds for each stage. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: autostage_pre_delay + + The autopilot will pause the actual staging before ? seconds for each stage. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: clamp_auto_stage_thrust_pct + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: fairing_max_aerothermal_flux + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: fairing_max_dynamic_pressure + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: fairing_min_altitude + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: hot_staging + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: hot_staging_lead_time + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +TargetController +================ + + +.. class:: TargetController + + + + .. attribute:: can_align + + + + :Attribute: Read-only, cannot be set + :rtype: bool + :Game Scenes: Flight + + .. attribute:: distance + + + + :Attribute: Read-only, cannot be set + :rtype: float + :Game Scenes: Flight + + .. attribute:: docking_axis + + + + :Attribute: Read-only, cannot be set + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: get_position_target_position() + + + + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: get_position_target_string() + + + + :rtype: str + :Game Scenes: Flight + + .. attribute:: normal_target_exists + + + + :Attribute: Read-only, cannot be set + :rtype: bool + :Game Scenes: Flight + + .. method:: pick_position_target_on_map() + + + + :Game Scenes: Flight + + .. attribute:: position + + + + :Attribute: Read-only, cannot be set + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: position_target_exists + + + + :Attribute: Read-only, cannot be set + :rtype: bool + :Game Scenes: Flight + + .. attribute:: relative_position + + + + :Attribute: Read-only, cannot be set + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. attribute:: relative_velocity + + + + :Attribute: Read-only, cannot be set + :rtype: tuple(float, float, float) + :Game Scenes: Flight + + .. method:: set_direction_target(name) + + + + :param str name: + :Game Scenes: Flight + + .. method:: set_position_target(body, latitude, longitude) + + + + :param SpaceCenter.CelestialBody body: + :param float latitude: + :param float longitude: + :Game Scenes: Flight + + .. attribute:: target_orbit + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`SpaceCenter.Orbit` + :Game Scenes: Flight + + .. method:: update_direction_target(direction) + + + + :param tuple direction: + :Game Scenes: Flight + +.. default-domain:: py +.. highlight:: py +.. currentmodule:: MechJeb + +ThrustController +================ + + +.. class:: ThrustController + + + + .. attribute:: differential_throttle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: differential_throttle_status + + + + :Attribute: Read-only, cannot be set + :rtype: :class:`DifferentialThrottleStatus` + :Game Scenes: Flight + + .. attribute:: electric_throttle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: electric_throttle_hi + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: electric_throttle_lo + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: flameout_safety_pct + + The jet safety margin. A value between 0 and 1. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: limit_acceleration + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: limit_dynamic_pressure + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: limit_throttle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: limit_to_prevent_flameout + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: limit_to_prevent_overheats + + Limits the throttle to prevent parts from overheating. + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: limiter_min_throttle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: manage_intakes + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: max_acceleration + + Limit acceleration to [m/s^2] (never exceed the acceleration during ascent). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: max_dynamic_pressure + + Limit the maximal dynamic pressure in Pa. + This avoids that pieces break off during launch because of atmospheric pressure. + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: max_throttle + + Never exceed the percentage of the throttle during ascent (value between 0 and 1). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: min_throttle + + Never go below the percentage of the throttle during ascent (value between 0 and 1). + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + .. attribute:: smooth_throttle + + + + :Attribute: Can be read or written + :rtype: bool + :Game Scenes: Flight + + .. attribute:: throttle_smoothing_time + + + + :Attribute: Can be read or written + :rtype: float + :Game Scenes: Flight + + + +.. class:: DifferentialThrottleStatus + + + + + .. data:: all_engines_off + + + + + .. data:: more_engines_required + + + + + .. data:: solver_failed + + + + + .. data:: success \ No newline at end of file diff --git a/kosmos/utils/json_utils.py b/kosmos/utils/json_utils.py index e69de29..f48a26a 100644 --- a/kosmos/utils/json_utils.py +++ b/kosmos/utils/json_utils.py @@ -0,0 +1,271 @@ +import json +import re +from typing import Any, Dict, Union +from .file_utils import f_join + + +def json_load(*file_path, **kwargs): + file_path = f_join(file_path) + try: + with open(file_path, "r") as fp: + return json.load(fp, **kwargs) + except FileNotFoundError: + # Return empty dict for missing files (common case for checkpoints) + return {} + + +def json_loads(string, **kwargs): + return json.loads(string, **kwargs) + + +def json_dump(data, *file_path, **kwargs): + file_path = f_join(file_path) + with open(file_path, "w") as fp: + json.dump(data, fp, **kwargs) + + +def json_dumps(data, **kwargs): + """ + Returns: string + """ + return json.dumps(data, **kwargs) + + +# ---------------- Aliases ----------------- +# add aliases where verb goes first, json_load -> load_json +load_json = json_load +loads_json = json_loads +dump_json = json_dump +dumps_json = json_dumps + + +def extract_char_position(error_message: str) -> int: + """Extract the character position from the JSONDecodeError message. + Args: + error_message (str): The error message from the JSONDecodeError + exception. + Returns: + int: The character position. + """ + import re + + char_pattern = re.compile(r"\(char (\d+)\)") + if match := char_pattern.search(error_message): + return int(match[1]) + else: + raise ValueError("Character position not found in the error message.") + + +def add_quotes_to_property_names(json_string: str) -> str: + """ + Add quotes to property names in a JSON string. + Args: + json_string (str): The JSON string. + Returns: + str: The JSON string with quotes added to property names. + """ + + def replace_func(match): + return f'"{match.group(1)}":' + + property_name_pattern = re.compile(r"(\w+):") + corrected_json_string = property_name_pattern.sub(replace_func, json_string) + + try: + json.loads(corrected_json_string) + return corrected_json_string + except json.JSONDecodeError as e: + raise e + + +def balance_braces(json_string: str) -> str: + """ + Balance the braces in a JSON string. + Args: + json_string (str): The JSON string. + Returns: + str: The JSON string with braces balanced. + """ + + open_braces_count = json_string.count("{") + close_braces_count = json_string.count("}") + + while open_braces_count > close_braces_count: + json_string += "}" + close_braces_count += 1 + + while close_braces_count > open_braces_count: + json_string = json_string.rstrip("}") + close_braces_count -= 1 + + try: + json.loads(json_string) + return json_string + except json.JSONDecodeError as e: + raise e + + +def fix_invalid_escape(json_str: str, error_message: str) -> str: + while error_message.startswith("Invalid \\escape"): + bad_escape_location = extract_char_position(error_message) + json_str = json_str[:bad_escape_location] + json_str[bad_escape_location + 1 :] + try: + json.loads(json_str) + return json_str + except json.JSONDecodeError as e: + error_message = str(e) + return json_str + + +def correct_json(json_str: str) -> str: + """ + Correct common JSON errors. + Args: + json_str (str): The JSON string. + """ + + try: + json.loads(json_str) + return json_str + except json.JSONDecodeError as e: + error_message = str(e) + if error_message.startswith("Invalid \\escape"): + json_str = fix_invalid_escape(json_str, error_message) + if error_message.startswith( + "Expecting property name enclosed in double quotes" + ): + json_str = add_quotes_to_property_names(json_str) + try: + json.loads(json_str) + return json_str + except json.JSONDecodeError as e: + error_message = str(e) + if balanced_str := balance_braces(json_str): + return balanced_str + return json_str + + +def fix_and_parse_json( + json_str: str, try_to_fix_with_gpt: bool = True +) -> Union[str, Dict[Any, Any]]: + """Fix and parse JSON string""" + import re + + # Handle None or empty string + if not json_str or json_str.strip() == "": + raise json.JSONDecodeError("Empty or None JSON string", "", 0) + + # First, try to extract JSON from markdown code blocks + # Use greedy match to capture the entire JSON object, not just the first part + json_pattern = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL) + match = json_pattern.search(json_str) + if match: + json_str = match.group(1) + + # Clean up whitespace and normalize + json_str = json_str.strip() + + # Remove any leading/trailing whitespace from each line (common LLM formatting issue) + lines = json_str.split('\n') + json_str_cleaned = '\n'.join(line.strip() for line in lines) + + # Try direct parsing first + try: + return json.loads(json_str) + except json.JSONDecodeError as e: + print(f"DEBUG: Initial JSON parse failed: {e}") + + # Try with cleaned version + try: + return json.loads(json_str_cleaned) + except json.JSONDecodeError: + pass + + # Remove tabs but preserve newlines in strings + json_str_no_tabs = json_str.replace("\t", " ") + try: + return json.loads(json_str_no_tabs) + except json.JSONDecodeError: + pass + + # Try fixing common JSON errors + try: + json_str_fixed = correct_json(json_str) + return json.loads(json_str_fixed) + except json.JSONDecodeError as e: + print(f"DEBUG: Corrected JSON parse failed: {e}") + + # Check if JSON is missing opening/closing braces + # Sometimes LLMs return just the fields without the enclosing {} + if "{" not in json_str: + print(f"DEBUG: No opening brace found, attempting to add braces") + # Try wrapping in braces + try: + wrapped = "{" + json_str.strip() + "}" + return json.loads(wrapped) + except json.JSONDecodeError: + pass + + # Check if JSON is missing closing brace + if "{" in json_str and "}" not in json_str: + print(f"DEBUG: No closing brace found, attempting to add closing brace") + try: + fixed = json_str.strip() + "}" + return json.loads(fixed) + except json.JSONDecodeError: + pass + + # Manual extraction: find the first { and find matching } by counting braces + # This handles cases where there's text before/after the JSON object + try: + # Find first opening brace + brace_start = json_str.index("{") + # Count braces to find the matching closing brace + brace_count = 0 + brace_end = -1 + in_string = False + escape_next = False + + for i in range(brace_start, len(json_str)): + char = json_str[i] + + # Handle string content (don't count braces inside strings) + if escape_next: + escape_next = False + continue + if char == '\\': + escape_next = True + continue + if char == '"': + in_string = not in_string + continue + + # Count braces only outside strings + if not in_string: + if char == '{': + brace_count += 1 + elif char == '}': + brace_count -= 1 + if brace_count == 0: + brace_end = i + break + + if brace_end > brace_start: + extracted_json = json_str[brace_start:brace_end + 1] + print(f"DEBUG: Extracted JSON from position {brace_start} to {brace_end}") + try: + return json.loads(extracted_json) + except json.JSONDecodeError: + # Try fixing the extracted JSON + fixed = correct_json(extracted_json) + return json.loads(fixed) + except (ValueError, json.JSONDecodeError) as e: + print(f"DEBUG: Manual extraction failed: {e}") + + # If all else fails, raise an error with useful debugging info + preview = json_str[:500] if len(json_str) > 500 else json_str + raise json.JSONDecodeError( + f"Failed to parse JSON after all attempts. Preview: {repr(preview)}", + json_str, + 0 + ) \ No newline at end of file diff --git a/kosmos/utils/telemetry_collector.py b/kosmos/utils/telemetry_collector.py new file mode 100644 index 0000000..82f9dc9 --- /dev/null +++ b/kosmos/utils/telemetry_collector.py @@ -0,0 +1,626 @@ +#!/usr/bin/env python3 +""" +Comprehensive kRPC Telemetry Collector for AI Agents + +This module provides a simple interface to collect all available telemetry +data from Kerbal Space Program via kRPC for AI agent decision making. +""" + +import krpc +from typing import Dict, Any, Optional, Tuple +import time + + +class TelemetryCollector: + """ + A comprehensive telemetry collector for KSP vessels. + + This class provides methods to gather all available telemetry data + from a vessel in Kerbal Space Program, organized by category for + easy access by AI agents. + """ + + def __init__(self, connection_name: str = "AI_Agent"): + """ + Initialize the telemetry collector. + + Args: + connection_name: Name for the kRPC connection + """ + self.conn = krpc.connect(name=connection_name) + self.space_center = self.conn.space_center + self.vessel = None + self.flight = None + self.orbit = None + self.control = None + self.resources = None + + def set_vessel(self, vessel_name: Optional[str] = None): + """ + Set the active vessel for telemetry collection. + + Args: + vessel_name: Name of vessel to track. If None, uses active vessel. + """ + if vessel_name: + vessels = self.space_center.vessels + self.vessel = next((v for v in vessels if v.name == vessel_name), None) + if not self.vessel: + raise ValueError(f"Vessel '{vessel_name}' not found") + else: + self.vessel = self.space_center.active_vessel + + if not self.vessel: + raise ValueError("No active vessel available") + + # Initialize related objects + self.flight = self.vessel.flight() + self.orbit = self.vessel.orbit + self.control = self.vessel.control + self.resources = self.vessel.resources + + def get_basic_vessel_data(self) -> Dict[str, Any]: + """Get basic vessel information.""" + if not self.vessel: + return {} + + return { + 'name': self.vessel.name, + 'type': str(self.vessel.type), + 'situation': str(self.vessel.situation), + 'mass': self.vessel.mass, + 'dry_mass': self.vessel.dry_mass, + 'crew_count': self.vessel.crew_count, + 'crew_capacity': self.vessel.crew_capacity, + 'biome': self.vessel.biome, + 'recoverable': self.vessel.recoverable, + 'met': self.vessel.met, # Mission Elapsed Time + } + + def get_performance_data(self) -> Dict[str, Any]: + """Get vessel performance metrics.""" + if not self.vessel: + return {} + + return { + 'thrust': self.vessel.thrust, + 'max_thrust': self.vessel.max_thrust, + 'max_vacuum_thrust': self.vessel.max_vacuum_thrust, + 'specific_impulse': self.vessel.specific_impulse, + 'kerbin_sea_level_specific_impulse': self.vessel.kerbin_sea_level_specific_impulse, + 'vacuum_specific_impulse': self.vessel.vacuum_specific_impulse, + } + + def get_torque_data(self) -> Dict[str, Any]: + """Get available torque and control capabilities.""" + if not self.vessel: + return {} + + return { + 'available_control_surface_torque': self.vessel.available_control_surface_torque, + 'available_engine_torque': self.vessel.available_engine_torque, + 'available_rcs_torque': self.vessel.available_rcs_torque, + 'available_reaction_wheel_torque': self.vessel.available_reaction_wheel_torque, + 'available_thrust': self.vessel.available_thrust, + 'available_torque': self.vessel.available_torque, + } + + def get_position_velocity_data(self) -> Dict[str, Any]: + """Get position and velocity information in multiple reference frames.""" + if not self.flight or not self.vessel: + return {} + + # Get reference frames + vessel_rf = self.vessel.reference_frame + orbital_rf = self.vessel.orbital_reference_frame + surface_rf = self.vessel.surface_reference_frame + + return { + # Vessel-relative position and velocity + 'position_vessel': self.vessel.position(vessel_rf), + 'velocity_vessel': self.vessel.velocity(vessel_rf), + + # Orbital-relative position and velocity + 'position_orbital': self.vessel.position(orbital_rf), + 'velocity_orbital': self.vessel.velocity(orbital_rf), + + # Surface-relative position and velocity + 'position_surface': self.vessel.position(surface_rf), + 'velocity_surface': self.vessel.velocity(surface_rf), + + # Flight data (uses default reference frame) + 'speed': self.flight.speed, + 'horizontal_speed': self.flight.horizontal_speed, + 'vertical_speed': self.flight.vertical_speed, + 'equivalent_air_speed': self.flight.equivalent_air_speed, + 'true_air_speed': self.flight.true_air_speed, + 'terminal_velocity': self.flight.terminal_velocity, + } + + def get_altitude_location_data(self) -> Dict[str, Any]: + """Get altitude and location information.""" + if not self.flight: + return {} + + return { + 'mean_altitude': self.flight.mean_altitude, + 'surface_altitude': self.flight.surface_altitude, + 'bedrock_altitude': self.flight.bedrock_altitude, + 'latitude': self.flight.latitude, + 'longitude': self.flight.longitude, + 'elevation': self.flight.elevation, + } + + def get_aerodynamics_data(self) -> Dict[str, Any]: + """Get aerodynamic information (stock KSP + FAR if available).""" + if not self.flight: + return {} + + # Basic aerodynamics (available in stock KSP) + aero_data = { + 'atmosphere_density': self.flight.atmosphere_density, + 'dynamic_pressure': self.flight.dynamic_pressure, + 'static_pressure': self.flight.static_pressure, + 'static_pressure_at_msl': self.flight.static_pressure_at_msl, + 'drag': self.flight.drag, + 'lift': self.flight.lift, + 'mach': self.flight.mach, + } + + # FAR-specific properties (optional - only if FAR mod is installed) + # These will be None if FAR is not available + try: + aero_data['drag_coefficient'] = self.flight.drag_coefficient + except: + aero_data['drag_coefficient'] = None + + try: + aero_data['lift_coefficient'] = self.flight.lift_coefficient + except: + aero_data['lift_coefficient'] = None + + try: + aero_data['ballistic_coefficient'] = self.flight.ballistic_coefficient + except: + aero_data['ballistic_coefficient'] = None + + try: + aero_data['reynolds_number'] = self.flight.reynolds_number + except: + aero_data['reynolds_number'] = None + + return aero_data + + def get_orientation_data(self) -> Dict[str, Any]: + """Get vessel orientation information.""" + if not self.flight: + return {} + + return { + 'heading': self.flight.heading, + 'pitch': self.flight.pitch, + 'roll': self.flight.roll, + 'direction': self.flight.direction, + 'rotation': self.flight.rotation, + 'angle_of_attack': self.flight.angle_of_attack, + 'sideslip_angle': self.flight.sideslip_angle, + } + + def get_flight_dynamics_data(self) -> Dict[str, Any]: + """Get flight dynamics information (stock KSP + FAR if available).""" + if not self.flight: + return {} + + dynamics_data = { + 'g_force': self.flight.g_force, + 'center_of_mass': self.flight.center_of_mass, + 'aerodynamic_force': self.flight.aerodynamic_force, + } + + # FAR-specific properties (optional - only if FAR mod is installed) + try: + dynamics_data['thrust_specific_fuel_consumption'] = self.flight.thrust_specific_fuel_consumption + except: + dynamics_data['thrust_specific_fuel_consumption'] = None + + try: + dynamics_data['stall_fraction'] = self.flight.stall_fraction + except: + dynamics_data['stall_fraction'] = None + + return dynamics_data + + def get_reference_vectors(self) -> Dict[str, Any]: + """Get reference direction vectors.""" + if not self.flight: + return {} + + return { + 'prograde': self.flight.prograde, + 'retrograde': self.flight.retrograde, + 'normal': self.flight.normal, + 'anti_normal': self.flight.anti_normal, + 'radial': self.flight.radial, + 'anti_radial': self.flight.anti_radial, + } + + def get_reference_frame_data(self) -> Dict[str, Any]: + """Get reference frame information and positions in different coordinate systems.""" + if not self.vessel: + return {} + + # Get reference frames + vessel_rf = self.vessel.reference_frame + orbital_rf = self.vessel.orbital_reference_frame + surface_rf = self.vessel.surface_reference_frame + + # Get positions in different reference frames + vessel_pos = self.vessel.position(vessel_rf) + orbital_pos = self.vessel.position(orbital_rf) + surface_pos = self.vessel.position(surface_rf) + + # Get velocities in different reference frames + vessel_vel = self.vessel.velocity(vessel_rf) + orbital_vel = self.vessel.velocity(orbital_rf) + surface_vel = self.vessel.velocity(surface_rf) + + return { + 'reference_frames': { + 'vessel': { + 'position': vessel_pos, + 'velocity': vessel_vel, + 'description': 'Vessel-relative coordinates (X=right, Y=forward, Z=up)' + }, + 'orbital': { + 'position': orbital_pos, + 'velocity': orbital_vel, + 'description': 'Orbital coordinates (X=anti-radial, Y=prograde, Z=normal)' + }, + 'surface': { + 'position': surface_pos, + 'velocity': surface_vel, + 'description': 'Surface coordinates (X=zenith, Y=north, Z=east)' + } + }, + 'coordinate_systems': { + 'vessel_available': vessel_rf is not None, + 'orbital_available': orbital_rf is not None, + 'surface_available': surface_rf is not None, + } + } + + def get_orbital_data(self) -> Dict[str, Any]: + """Get orbital information.""" + if not self.orbit: + return {} + + return { + # Orbital elements + 'semi_major_axis': self.orbit.semi_major_axis, + 'semi_minor_axis': self.orbit.semi_minor_axis, + 'eccentricity': self.orbit.eccentricity, + 'inclination': self.orbit.inclination, + 'longitude_of_ascending_node': self.orbit.longitude_of_ascending_node, + 'argument_of_periapsis': self.orbit.argument_of_periapsis, + 'mean_anomaly': self.orbit.mean_anomaly, + 'eccentric_anomaly': self.orbit.eccentric_anomaly, + 'true_anomaly': self.orbit.true_anomaly, + + # Orbital characteristics + 'apoapsis': self.orbit.apoapsis, + 'periapsis': self.orbit.periapsis, + 'apoapsis_altitude': self.orbit.apoapsis_altitude, + 'periapsis_altitude': self.orbit.periapsis_altitude, + 'period': self.orbit.period, + 'orbital_speed': self.orbit.orbital_speed, + 'speed': self.orbit.speed, + 'radius': self.orbit.radius, + + # Timing + 'time_to_apoapsis': self.orbit.time_to_apoapsis, + 'time_to_periapsis': self.orbit.time_to_periapsis, + 'time_to_soi_change': self.orbit.time_to_soi_change, + 'epoch': self.orbit.epoch, + 'mean_anomaly_at_epoch': self.orbit.mean_anomaly_at_epoch, + + # Body information + 'body_name': self.orbit.body.name if self.orbit.body else None, + } + + def get_control_data(self) -> Dict[str, Any]: + """Get current control inputs and system status.""" + if not self.control: + return {} + + return { + # Flight controls + 'pitch': self.control.pitch, + 'yaw': self.control.yaw, + 'roll': self.control.roll, + 'throttle': self.control.throttle, + 'forward': self.control.forward, + 'up': self.control.up, + 'right': self.control.right, + + # System controls + 'sas': self.control.sas, + 'rcs': self.control.rcs, + 'brakes': self.control.brakes, + 'gear': self.control.gear, + 'lights': self.control.lights, + 'abort': self.control.abort, + + # Advanced controls + 'custom_axis01': self.control.custom_axis01, + 'custom_axis02': self.control.custom_axis02, + 'custom_axis03': self.control.custom_axis03, + 'custom_axis04': self.control.custom_axis04, + 'wheel_steering': self.control.wheel_steering, + 'wheel_throttle': self.control.wheel_throttle, + + # System status + 'state': str(self.control.state), + 'source': str(self.control.source), + 'current_stage': self.control.current_stage, + 'stage_lock': self.control.stage_lock, + 'sas_mode': str(self.control.sas_mode), + 'input_mode': str(self.control.input_mode), + } + + def get_resource_data(self) -> Dict[str, Any]: + """Get vessel resource information.""" + if not self.resources: + return {} + + # Get all available resources + resource_data = {} + for resource in self.resources.names: + res_info = { + 'amount': self.resources.amount(resource), + 'max': self.resources.max(resource), + } + + # These properties may not be available for all resources or configurations + try: + res_info['flow_mode'] = str(self.resources.flow_mode(resource)) + except: + res_info['flow_mode'] = None + + try: + res_info['density'] = self.resources.density(resource) + except: + res_info['density'] = None + + resource_data[resource] = res_info + + return resource_data + + def get_comprehensive_telemetry(self) -> Dict[str, Any]: + """ + Get all available telemetry data in one comprehensive dictionary. + + Returns: + Dictionary containing all telemetry data organized by category + """ + return { + 'timestamp': time.time(), + 'basic_vessel': self.get_basic_vessel_data(), + 'performance': self.get_performance_data(), + 'torque': self.get_torque_data(), + 'position_velocity': self.get_position_velocity_data(), + 'altitude_location': self.get_altitude_location_data(), + 'aerodynamics': self.get_aerodynamics_data(), + 'orientation': self.get_orientation_data(), + 'flight_dynamics': self.get_flight_dynamics_data(), + 'reference_vectors': self.get_reference_vectors(), + 'reference_frames': self.get_reference_frame_data(), + 'orbital': self.get_orbital_data(), + 'control': self.get_control_data(), + 'resources': self.get_resource_data(), + } + + def get_ai_decision_data(self) -> Dict[str, Any]: + """ + Get a simplified dataset optimized for AI decision making. + + This includes only the most critical data points for AI agents + to make flight decisions. + """ + if not self.vessel or not self.flight or not self.orbit: + return {} + + return { + 'timestamp': time.time(), + + # Critical vessel state + 'name': self.vessel.name, + 'situation': str(self.vessel.situation), + 'mass': self.vessel.mass, + 'thrust': self.vessel.thrust, + 'max_thrust': self.vessel.max_thrust, + + # Position and motion (in different reference frames) + 'position_vessel': self.vessel.position(self.vessel.reference_frame), + 'velocity_vessel': self.vessel.velocity(self.vessel.reference_frame), + 'position_orbital': self.vessel.position(self.vessel.orbital_reference_frame), + 'velocity_orbital': self.vessel.velocity(self.vessel.orbital_reference_frame), + 'position_surface': self.vessel.position(self.vessel.surface_reference_frame), + 'velocity_surface': self.vessel.velocity(self.vessel.surface_reference_frame), + 'speed': self.flight.speed, + 'altitude': self.flight.mean_altitude, + 'surface_altitude': self.flight.surface_altitude, + + # Orientation + 'heading': self.flight.heading, + 'pitch': self.flight.pitch, + 'roll': self.flight.roll, + + # Orbital state + 'apoapsis_altitude': self.orbit.apoapsis_altitude, + 'periapsis_altitude': self.orbit.periapsis_altitude, + 'eccentricity': self.orbit.eccentricity, + 'inclination': self.orbit.inclination, + 'orbital_speed': self.orbit.orbital_speed, + + # Control inputs + 'throttle': self.control.throttle if self.control else 0, + 'pitch_input': self.control.pitch if self.control else 0, + 'yaw_input': self.control.yaw if self.control else 0, + 'roll_input': self.control.roll if self.control else 0, + + # System status + 'sas_enabled': self.control.sas if self.control else False, + 'rcs_enabled': self.control.rcs if self.control else False, + 'gear_deployed': self.control.gear if self.control else False, + + # Resources (key ones only) + 'fuel_amount': self.resources.amount('LiquidFuel') if self.resources else 0, + 'fuel_max': self.resources.max('LiquidFuel') if self.resources else 0, + 'electric_charge': self.resources.amount('ElectricCharge') if self.resources else 0, + 'electric_charge_max': self.resources.max('ElectricCharge') if self.resources else 0, + + # Parts information + 'part_count': len(self.vessel.parts.all) if hasattr(self.vessel, 'parts') else 0, + 'current_stage': self.vessel.control.current_stage if self.vessel.control else 0, + } + + def get_reference_frame_for_mission(self, mission_type: str) -> Dict[str, Any]: + """ + Get reference frame data optimized for specific mission types. + + Args: + mission_type: Type of mission ('launch', 'orbital', 'landing', 'docking', 'surface') + + Returns: + Dictionary with reference frame data relevant to the mission type + """ + if not self.vessel: + return {} + + base_data = { + 'mission_type': mission_type, + 'reference_frames_available': { + 'vessel': self.vessel.reference_frame is not None, + 'orbital': self.vessel.orbital_reference_frame is not None, + 'surface': self.vessel.surface_reference_frame is not None, + } + } + + if mission_type == 'launch': + # For launch, we need surface and vessel reference frames + return { + **base_data, + 'surface_position': self.vessel.position(self.vessel.surface_reference_frame), + 'surface_velocity': self.vessel.velocity(self.vessel.surface_reference_frame), + 'vessel_position': self.vessel.position(self.vessel.reference_frame), + 'vessel_velocity': self.vessel.velocity(self.vessel.reference_frame), + 'altitude': self.flight.mean_altitude, + 'vertical_speed': self.flight.vertical_speed, + } + + elif mission_type == 'orbital': + # For orbital operations, we need orbital reference frame + return { + **base_data, + 'orbital_position': self.vessel.position(self.vessel.orbital_reference_frame), + 'orbital_velocity': self.vessel.velocity(self.vessel.orbital_reference_frame), + 'prograde': self.flight.prograde, + 'retrograde': self.flight.retrograde, + 'normal': self.flight.normal, + 'radial': self.flight.radial, + } + + elif mission_type == 'landing': + # For landing, we need surface reference frame + return { + **base_data, + 'surface_position': self.vessel.position(self.vessel.surface_reference_frame), + 'surface_velocity': self.vessel.velocity(self.vessel.surface_reference_frame), + 'surface_altitude': self.flight.surface_altitude, + 'vertical_speed': self.flight.vertical_speed, + 'horizontal_speed': self.flight.horizontal_speed, + } + + elif mission_type == 'docking': + # For docking, we need vessel reference frame + return { + **base_data, + 'vessel_position': self.vessel.position(self.vessel.reference_frame), + 'vessel_velocity': self.vessel.velocity(self.vessel.reference_frame), + 'vessel_orientation': { + 'heading': self.flight.heading, + 'pitch': self.flight.pitch, + 'roll': self.flight.roll, + } + } + + elif mission_type == 'surface': + # For surface operations, we need surface reference frame + return { + **base_data, + 'surface_position': self.vessel.position(self.vessel.surface_reference_frame), + 'surface_velocity': self.vessel.velocity(self.vessel.surface_reference_frame), + 'latitude': self.flight.latitude, + 'longitude': self.flight.longitude, + 'heading': self.flight.heading, + } + + else: + # Default: return all reference frame data + return { + **base_data, + 'all_reference_frames': self.get_reference_frame_data() + } + + def close(self): + """Close the kRPC connection.""" + if self.conn: + self.conn.close() + + +# Example usage and testing +if __name__ == "__main__": + # Example of how to use the telemetry collector + try: + # Initialize collector + collector = TelemetryCollector("AI_Agent_Test") + + # Set active vessel + collector.set_vessel() + + # Get comprehensive telemetry + print("Getting comprehensive telemetry...") + telemetry = collector.get_comprehensive_telemetry() + print(f"Collected {len(telemetry)} categories of data") + + # Get AI-optimized data + print("\nGetting AI decision data...") + ai_data = collector.get_ai_decision_data() + print(f"AI data contains {len(ai_data)} key metrics") + + # Print some sample data + print(f"\nVessel: {ai_data.get('name', 'Unknown')}") + print(f"Situation: {ai_data.get('situation', 'Unknown')}") + print(f"Altitude: {ai_data.get('altitude', 0):.1f}m") + print(f"Speed: {ai_data.get('speed', 0):.1f}m/s") + print(f"Throttle: {ai_data.get('throttle', 0):.2f}") + + # Demonstrate reference frame usage + print("\nReference Frame Data:") + print(f"Vessel Position: {ai_data.get('position_vessel', (0,0,0))}") + print(f"Orbital Position: {ai_data.get('position_orbital', (0,0,0))}") + print(f"Surface Position: {ai_data.get('position_surface', (0,0,0))}") + + # Demonstrate mission-specific reference frames + print("\nMission-specific Reference Frames:") + for mission_type in ['launch', 'orbital', 'landing', 'docking', 'surface']: + mission_data = collector.get_reference_frame_for_mission(mission_type) + print(f"{mission_type.capitalize()}: {len(mission_data)} data points") + + except Exception as e: + print(f"Error: {e}") + print("Make sure Kerbal Space Program is running with kRPC mod installed") + + finally: + if 'collector' in locals(): + collector.close()