Skip to content

Instantly share code, notes, and snippets.

@widlarizer
Last active March 18, 2025 09:51
Show Gist options
  • Save widlarizer/0e0873a46942fb6fb396108d00abc4fa to your computer and use it in GitHub Desktop.
Save widlarizer/0e0873a46942fb6fb396108d00abc4fa to your computer and use it in GitHub Desktop.
linear scale thingy for gamozo
import math, random
import numpy as np
import matplotlib.pyplot as plt
import csv
def read_iq_data(filename):
i_data = []
q_data = []
try:
with open(filename, 'r') as file:
# I removed duplicate spaces from the file beforehand btw
reader = csv.reader(file, delimiter=' ')
for row in reader:
filtered = list(filter(bool, row))
# print(filtered)
try:
i_value = float(filtered[1])
q_value = float(filtered[2])
i_data.append(i_value)
q_data.append(q_value)
except ValueError:
print(f"Warning: Could not convert values in row: {filtered}")
continue
except Exception as e:
print(f"Error reading the file: {e}")
return np.array(i_data), np.array(q_data)
def analyze_iq_data(i_data, q_data):
"""
Perform basic analysis on I/Q data.
Parameters:
- i_data: Array of I values
- q_data: Array of Q values
Returns:
- Dictionary of analysis results
"""
i_mean = np.mean(i_data)
q_mean = np.mean(q_data)
i_diff = i_data - i_mean
q_diff = q_data - q_mean
# Calculate magnitude and phase
# Calculate the absolute phase
abs_phase = np.arctan2(q_diff, i_diff)
# Use NumPy's unwrap function to remove discontinuities larger than pi
unwrapped_phase = np.unwrap(abs_phase)
# If you need the cumulative sum as in your original code
cums = unwrapped_phase
dist = cums * (- 1e3 * 20e-6 / (2 * np.pi))
# Calculate statistics
analysis = {
"i_mean": i_mean,
"q_mean": q_mean,
"i_std": np.std(i_data),
"q_std": np.std(q_data),
"dist_mean": np.mean(dist),
"dist_std": np.std(dist)
}
return analysis, dist
def plot_iq_data(i_data, q_data, cum):
fig, axs = plt.subplots(2, 1, figsize=(12, 10))
# I/Q constellation plot
axs[0].scatter(i_data, q_data, alpha=0.6, s=0.1)
axs[0].set_title('I/Q Constellation')
axs[0].set_xlabel('I')
axs[0].set_ylabel('Q')
axs[0].grid(True)
axs[0].axis('equal')
# Time series of I and Q
t = np.arange(len(i_data)) / 100000
# Phase
axs[1].plot(t, cum)
axs[1].set_title('Physical distance from start')
axs[1].set_xlabel('Time [s]')
axs[1].set_ylabel('Distance [mm]')
axs[1].grid(True)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
filename = "log.txt"
i_data, q_data = read_iq_data(filename)
if len(i_data) > 0:
print(f"Successfully read {len(i_data)} I/Q samples")
# Analyze the data
analysis, dist = analyze_iq_data(i_data, q_data)
# Print analysis results
print("\nAnalysis Results:")
for key, value in analysis.items():
print(f"{key}: {value}")
# Plot the data
start = 0
length = -1
plot_iq_data(i_data[start:start+length], q_data[start:start+length], dist[start:start+length])
print(dist[0])
print(dist[-1])
else:
print("No data was read from the file")
# if __name__ == "__main__":
# # filename = "log.txt"
# i_data, q_data = [], []
# for a in range(100):
# # i_data.append(float(random.randint(0, 100)) / 100)
# # q_data.append(float(random.randint(0, 100)) / 100)
# i_data.append(math.cos(a / 10))
# q_data.append(math.sin(a / 10))
# for a in range(100):
# i_data.append(math.sin(a / 10))
# q_data.append(math.cos(a / 10))
# i_data = np.array(i_data)
# q_data = np.array(q_data)
# # Analyze the data
# analysis, cum, phase = analyze_iq_data(i_data, q_data)
# # Print analysis results
# print("\nAnalysis Results:")
# for key, value in analysis.items():
# print(f"{key}: {value}")
# # Plot the data
# # start = 600000
# # length = 10000
# start = 0
# length = 1000
# plot_iq_data(i_data[start:start+length], q_data[start:start+length], cum[start:start+length], phase[start:start+length])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment