================================================================================
  Experiment 11: Real-Time ISS Location Tracker & Time-Series Plotting
================================================================================

FULL QUESTION:
Write a Python program to retrieve the real-time location of the International Space Station (ISS) every 5 seconds, store 100 location records in a CSV file, analyze the latitude and longitude data, and plot latitude vs. time and longitude vs. time graphs.

SHORT QUESTION:
Poll ISS Open-Notify API every 5s, log 100 points to CSV, perform statistical analysis, and plot time-series trajectory.

================================================================================
README & SETUP INSTRUCTIONS:
================================================================================
# Experiment 11: Real-Time ISS Location Tracker & Time-Series Plot

## Objective
Retrieve the real-time coordinates of the International Space Station every 5 seconds, log 100 records into a CSV file, analyze coordinate distribution, and plot Latitude vs. Time and Longitude vs. Time.

## Requirements
```bash
pip install requests pandas matplotlib
```

## How to Run
```bash
python iss_tracker.py
```
Outputs `iss_location.csv` and `iss_trajectory.png`.

================================================================================
SOURCE CODE FILES:
================================================================================

1. iss_tracker.py
--------------------------------------------------------------------------------
import csv
import os
import time
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
import requests

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
API_URL = "http://api.open-notify.org/iss-now.json"
CSV_FILE = os.path.join(BASE_DIR, "iss_location.csv")
DEFAULT_RECORDS = 100
INTERVAL = 5

print("ISS Real-Time Tracker")
has_existing = os.path.exists(CSV_FILE) and os.path.getsize(CSV_FILE) > 50

user_choice = input(
    f"Fetch new live ISS records? (Enter number of records [e.g. 5 or 100], or press Enter to {'use existing 100-record dataset' if has_existing else 'fetch 5 records for fast test'}): "
).strip()

if not user_choice and not has_existing:
    num_to_fetch = 5
elif user_choice.isdigit():
    num_to_fetch = int(user_choice)
elif user_choice.lower() in ("y", "yes"):
    num_to_fetch = DEFAULT_RECORDS
else:
    num_to_fetch = 0

if num_to_fetch > 0:
    with open(CSV_FILE, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["Timestamp", "Time_Str", "Latitude", "Longitude"])

        print(f"Collecting {num_to_fetch} record(s) from ISS API every {INTERVAL}s...")
        for i in range(num_to_fetch):
            try:
                response = requests.get(API_URL, timeout=5).json()
                pos = response["iss_position"]
                ts = response["timestamp"]
                time_str = datetime.fromtimestamp(ts).strftime("%H:%M:%S")
                lat = float(pos["latitude"])
                lon = float(pos["longitude"])

                writer.writerow([ts, time_str, lat, lon])
                file.flush()
                print(f"[{i+1}/{num_to_fetch}] {time_str} -> Lat: {lat}, Lon: {lon}")
            except Exception as e:
                print(f"Error fetching record {i+1}: {e}")
            if i < num_to_fetch - 1:
                time.sleep(INTERVAL)

df = pd.read_csv(CSV_FILE)
print("\nStatistical Summary:")
print(df[["Latitude", "Longitude"]].describe())

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8), sharex=True)

ax1.plot(df["Time_Str"], df["Latitude"], color="blue", marker="o", markersize=2)
ax1.set_ylabel("Latitude (degrees)")
ax1.set_title("ISS Latitude vs. Time")
ax1.grid(True)

ax2.plot(df["Time_Str"], df["Longitude"], color="green", marker="o", markersize=2)
ax2.set_xlabel("Time (HH:MM:SS)")
ax2.set_ylabel("Longitude (degrees)")
ax2.set_title("ISS Longitude vs. Time")
ax2.grid(True)

plt.xticks(rotation=45)
plt.tight_layout()
plot_path = os.path.join(BASE_DIR, "iss_trajectory.png")
plt.savefig(plot_path)
print(f"Saved plot to {plot_path}")
plt.show()
--------------------------------------------------------------------------------
