Skip to content
Snippets Groups Projects
Commit 47207ff8 authored by Katharine H's avatar Katharine H
Browse files

data and analysis scripts

parent d0e2ba9d
No related branches found
No related tags found
No related merge requests found
read3.py 0 → 100644
import pandas as pd
import argparse
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import quad
from scipy.optimize import curve_fit
def low_pass(f, fl):
return (1 + (f / fl) ** 4) ** (-0.5)
def high_pass(f, fh):
return ((f / fh) ** 2) * (1 + (f / fh) ** 4) ** (-0.5)
def effective_bandwidth(lp_func, hp_func):
integrand = lambda f: (lp_func(f) ** 2) * (hp_func(f) ** 2)
result, _ = quad(integrand, 0, np.inf)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Read a CSV file, filter data, process gain, fit functions, and save outputs.")
parser.add_argument("file_path", type=str, help="Path to the CSV file")
parser.add_argument("output_gain_plot", type=str, help="Name of the output file for the gain plot")
parser.add_argument("output_fit_plot", type=str, help="Name of the output file for the fitted gain plot")
args = parser.parse_args()
try:
df = pd.read_csv(args.file_path)
except Exception as e:
print(f"Error processing the CSV file: {e}")
exit()
df.columns = df.columns.str.strip()
df = df[df["For_Analysis"] == True]
df.set_index("Frequency [Hz]", inplace=True)
# Compute Gain G(f) = Ch2 / Ch1
df["Gain"] = df["Ch2 RMS [V]"] / df["Ch1 RMS [V]"]
# Plot Gain G(f) vs Frequency (Logarithmic X-Axis)
plt.figure(figsize=(10, 6))
plt.semilogx(df.index, df["Gain"], 'ko-', label="Measured Gain")
plt.xlabel("Frequency [Hz]")
plt.ylabel("Gain G(f)")
plt.title("Gain vs Frequency")
plt.legend()
plt.grid(True, which="both", linestyle="--", linewidth=0.5)
plt.savefig(args.output_gain_plot)
print(f"Gain plot saved as {args.output_gain_plot}")
# Fit Low Pass and High Pass Functions
freqs = df.index.to_numpy()
gains = df["Gain"].to_numpy()
popt_lp, _ = curve_fit(low_pass, freqs, gains, p0=[1000]) # Initial guess for fl
popt_hp, _ = curve_fit(high_pass, freqs, gains, p0=[1000]) # Initial guess for fh
# Generate fitted curves
freqs_fit = np.logspace(np.log10(min(freqs)), np.log10(max(freqs)), 1000)
gain_lp_fit = low_pass(freqs_fit, *popt_lp)
gain_hp_fit = high_pass(freqs_fit, *popt_hp)
# Plot fitted curves
plt.figure(figsize=(10, 6))
plt.semilogx(freqs, gains, 'ko', label="Measured Gain")
plt.semilogx(freqs_fit, gain_lp_fit, 'r-', label=f"Low-Pass Fit (fl={popt_lp[0]:.2f} Hz)")
plt.semilogx(freqs_fit, gain_hp_fit, 'b-', label=f"High-Pass Fit (fh={popt_hp[0]:.2f} Hz)")
plt.xlabel("Frequency [Hz]")
plt.ylabel("Gain G(f)")
plt.title("Gain vs Frequency with Fit")
plt.legend()
plt.grid(True, which="both", linestyle="--", linewidth=0.5)
plt.savefig(args.output_fit_plot)
print(f"Fitted Gain plot saved as {args.output_fit_plot}")
# Compute Effective Bandwidth
delta_f_eff = effective_bandwidth(lambda f: low_pass(f, *popt_lp), lambda f: high_pass(f, *popt_hp))
df["Effective Bandwidth"] = delta_f_eff
print(df)
import pandas as pd
import argparse
def read_and_print_csv(file_path):
"""
Reads a CSV file into a Pandas DataFrame and prints it.
:param file_path: str, path to the CSV file
"""
try:
df = pd.read_csv(file_path) # Read CSV file into DataFrame
print(df) # Print DataFrame
except Exception as e:
print(f"Error reading the CSV file: {e}")
# Example usage
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Read a CSV file and print its contents.")
parser.add_argument("file_path", type=str, help="Path to the CSV file")
args = parser.parse_args()
read_and_print_csv(args.file_path)
import pandas as pd
import argparse
import matplotlib.pyplot as plt
import numpy as np
def plot_v_meter_squared_vs_rin(R_in, V_meter_squared, fit_line, VJ_squared, VN_squared, output_file):
"""Plot V_meter^2 vs R_in with the fit line."""
plt.figure(figsize=(8, 6))
plt.scatter(R_in, V_meter_squared, label="Measured Data", color="blue")
plt.plot(R_in, fit_line, label=f"Fit: $V_J^2={VJ_squared:.4f}$, $V_N^2={VN_squared:.4f}$", color="red")
plt.xlabel("Resistance $R_{in}$ [$\\Omega$]")
plt.ylabel("$V_{meter}^2$ [V²]")
plt.legend()
plt.grid()
plt.title("Measured Noise vs. Resistance with Fit")
plt.tight_layout()
plt.savefig(output_file)
plt.show()
def plot_residuals_vs_rin(R_in, residuals, output_file):
"""Plot residuals of the fit."""
plt.figure(figsize=(8, 6))
plt.scatter(R_in, residuals, color="black")
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("Resistance $R_{in}$ [$\\Omega$]")
plt.ylabel("Residuals")
plt.grid()
plt.title("Residuals of the Fit")
plt.tight_layout()
plt.savefig(output_file)
plt.show()
def plot_johnson_noise_contribution(R_in, Johnson_noise_contrib, output_file):
"""Plot Johnson noise contribution vs R_in."""
plt.figure(figsize=(8, 6))
plt.scatter(R_in, Johnson_noise_contrib, label="Johnson Noise Contribution", color="green")
plt.xlabel("Resistance $R_{in}$ [$\\Omega$]")
plt.ylabel("$V_J^2$ [V²]")
plt.legend()
plt.grid()
plt.title("Johnson Noise Contribution vs. Resistance")
plt.tight_layout()
plt.savefig(output_file)
plt.show()
def main():
# Set up command-line argument parsing
parser = argparse.ArgumentParser(description="Analyze Johnson noise data")
parser.add_argument("csv_file", type=str, help="Path to input CSV file")
parser.add_argument("output_files", nargs=3, type=str, help="Paths to save output plots (3 plots)")
args = parser.parse_args()
# Load the CSV file
df = pd.read_csv(args.csv_file)
# Strip spaces from column names to avoid errors
df.columns = df.columns.str.strip()
# Extracting correct columns
R_in = df["R_in [Ohm]"] # Resistance values
V_meter = df["V_meter [V]"] # Measured voltage
# Compute squared values
V_meter_squared = V_meter**2
# Perform linear fit: V_meter^2 = a * R_in + b
coeffs = np.polyfit(R_in, V_meter_squared, 1)
VJ_squared = coeffs[0] # Slope (Johnson noise contribution)
VN_squared = coeffs[1] # Intercept (Amplifier noise)
# Generate fitted values
fit_line = VJ_squared * R_in + VN_squared
# Compute residuals
residuals = V_meter_squared - fit_line
# Compute only Johnson noise contribution (without amplifier noise)
Johnson_noise_contrib = VJ_squared * R_in
# Plot and save each of the three plots to different output files
plot_v_meter_squared_vs_rin(R_in, V_meter_squared, fit_line, VJ_squared, VN_squared, args.output_files[0])
plot_residuals_vs_rin(R_in, residuals, args.output_files[1])
plot_johnson_noise_contribution(R_in, Johnson_noise_contrib, args.output_files[2])
# Print results
print(f"Fit Results: V_J^2 (slope) = {VJ_squared:.4f}, V_N^2 (intercept) = {VN_squared:.4f}")
if __name__ == "__main__":
main()
read5.py 0 → 100644
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import argparse
from scipy.optimize import curve_fit
# Step 1: Set up argparse to get CSV file and output path from command line
parser = argparse.ArgumentParser(description="Analyze Johnson Noise and Amplifier Noise from CSV data.")
parser.add_argument("csv_file", type=str, help="Path to the CSV file containing the data.")
parser.add_argument("output_file", type=str, help="Path to save the output plot (e.g., output.png).")
args = parser.parse_args()
# Step 2: Load the data
df = pd.read_csv(args.csv_file)
df.columns = df.columns.str.strip()
# Step 3: Extract relevant columns (modify column names based on actual CSV structure)
R_in = df["R_in [Ohm]"] # Resistance values
G_2 = df["G_2 [1]"] # Gain values
V_meter = df["V_meter [V]"] # Measured voltages
# Step 4: Define function for fitting
def noise_model(R, V_N):
V_J2 = (600 * G_2 / 10) ** 2 # Johnson noise squared
return np.sqrt(V_J2 + V_N**2)
# Step 5: Fit the data
V_meter_squared = V_meter ** 2
popt, pcov = curve_fit(noise_model, R_in, V_meter_squared)
V_N_fitted = popt[0]
# Step 6: Plot results
plt.figure(figsize=(8, 5))
plt.scatter(R_in, V_meter_squared, label="Measured Data", color="blue")
plt.plot(R_in, noise_model(R_in, V_N_fitted), label=f"Fitted Curve (V_N={V_N_fitted:.3f})", color="red")
plt.xlabel("Resistance (Ohms)")
plt.ylabel("$V_{meter}^2$ (V²)")
plt.legend()
plt.title("Decomposition of Measured Noise")
# Step 7: Save plot to specified output file
plt.savefig(args.output_file, dpi=300)
print(f"Plot saved as {args.output_file}")
read6.py 0 → 100644
import pandas as pd
import argparse
import numpy as np
import matplotlib.pyplot as plt
# Constants
k_B = 1.38e-23 # Boltzmann constant (J/K)
T = 300 # Room temperature in Kelvin
def process_frequency_dependence(csv_file, output_file):
"""
Analyze the dependence of Johnson noise on bandwidth.
Reads data from csv_file, calculates bandwidth, and generates a log-log plot.
Saves the plot to output_file.
"""
# Load the CSV file
df = pd.read_csv(csv_file)
# Strip spaces from column names to avoid issues
df.columns = df.columns.str.strip()
# Extract relevant data
R_fixed = df["R [Ohm]"].unique()[0]
f_high = df["f_high [Hz]"] # High-pass cutoff frequencies
f_low = df["f_low [Hz]"] # Low-pass cutoff frequencies
V_meter = df["V_meter [V]"] # Measured voltage values
# Compute squared values (voltage noise power)
V_meter_squared = V_meter ** 2
# Compute bandwidth (Δf)
bandwidth = f_high - f_low
# Compute theoretical Johnson noise
VJ_theoretical_squared = 4 * k_B * T * R_fixed * bandwidth
# Create a log-log plot
plt.figure(figsize=(8, 6))
plt.scatter(bandwidth, V_meter_squared, color="blue", label="Measured Data")
plt.plot(bandwidth, VJ_theoretical_squared, color="red", linestyle="--", label="Theoretical Johnson Noise")
plt.xscale("log")
plt.yscale("log")
plt.xlabel("Bandwidth Δf [Hz]")
plt.ylabel("$V_{meter}^2$ [V²]")
plt.title(f"Johnson Noise vs. Bandwidth")
plt.grid(True, which="both", linestyle="--", linewidth=0.5)
plt.legend()
# Save and show the plot
plt.savefig(output_file)
plt.show()
if __name__ == "__main__":
# Set up command-line arguments
parser = argparse.ArgumentParser(description="Analyze frequency dependence of Johnson noise")
parser.add_argument("csv_file", type=str, help="Path to input CSV file")
parser.add_argument("output_file", type=str, help="Path to save output plot")
args = parser.parse_args()
# Run the analysis
process_frequency_dependence(args.csv_file, args.output_file)
read9.py 0 → 100644
import pandas as pd
import numpy as np
import argparse
# Set up argument parser
parser = argparse.ArgumentParser(description='Calculate shot noise current fluctuations from CSV data.')
parser.add_argument('input_file', type=str, help='Input CSV file containing shot noise data')
parser.add_argument('output_file', type=str, help='Output CSV file to save results')
args = parser.parse_args()
# Load the CSV file
try:
data = pd.read_csv(args.input_file)
except FileNotFoundError:
print(f"Error: The file {args.input_file} was not found. Please check the file path.")
exit(1)
except Exception as e:
print(f"Error reading {args.input_file}: {e}")
exit(1)
data.columns = data.columns.str.strip()
# Map column names with units to internal names
data['R_f'] = data['R_f [Ohm]']
data['G_2'] = data['G_2 [1]']
data['V_HLEout'] = data['V_HLEout [V]']
data['V_HLEmonitor'] = data['V_HLEmonitor [V]']
# Assume V_HLEout is V_meter for this calculation
data['V_meter'] = data['V_HLEout']
# Calculate RMS current fluctuations
data['delta_i_squared'] = (data['V_meter'] * 10) / (100 * data['G_2'] * data['R_f'])**2
# Display results
print("Shot Noise Calculation:")
print(data[['R_f', 'G_2', 'V_meter', 'V_HLEmonitor', 'delta_i_squared']])
for index, row in data.iterrows():
print(f"Row {index + 2}: Mean square current fluctuation = {row['delta_i_squared']:.2e} A^2")
# Save results to the specified output CSV
data.to_csv(args.output_file, index=False)
print(f"Results saved to {args.output_file}")
import pandas as pd
import sys
def read_and_print_csv(file_path):
"""Reads a CSV file and prints its contents."""
try:
df = pd.read_csv(file_path)
print(df)
except Exception as e:
print(f"Error reading file: {e}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python read_csv.py <input_file.csv>")
else:
input_file = sys.argv[1]
read_and_print_csv(input_file)
......@@ -5,7 +5,7 @@ false, 6, 339.10e-03, 41.36e-03
true, 8, 346.76e-03, 39.89e-03
false, 12, 350.23e-03, 41.03e-03
false, 16, 351.24e-03, 41.71e-03
true, 20 349.88e-03, 41.35e-03
true, 20, 349.88e-03, 41.35e-03
false, 40, 356.19e-03, 41.76e-03
false, 60, 357.02e-03, 41.80e-03
true, 80, 349.00e-03, 41.10e-03
......
R_in [Ohm], G [1], V_meter [V]
R_in [Ohm], G_2 [1], V_meter [V]
1, 2e+03, 1.0193
10, 2e+03, 1.0231
100, 2e+03, 1.0458
......
High pass [Hz], Low Pass[Hz], V_meter [V]
10, 100e+03, 1.0381
30, 33e+03, 795.4e-03
1e+03, 10e+03, 449.7e-03
R [Ohm], f_high [Hz], f_low [Hz], V_meter [V]
10e+14, 100e+03, 10, 1.0381
10e+14, 33e+03, 30, 795.4e-03
10e+14, 10e+03, 1e+03, 449.7e-03
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment