""" Simple RC Circuit Example This example demonstrates using the pyngspice Python extension to simulate a basic RC low-pass filter. """ # Note: This example requires the ngspice extension to be built and installed # Run: pip install -e . from the ngspice root directory try: from pyngspice import SimRunner, RawRead except ImportError: print("pyngspice extension not installed. Run: pip install -e .") print("This example shows the intended API usage.") exit(1) import numpy as np import os # Create a simple RC netlist netlist_content = """ * Simple RC Low-Pass Filter * Cutoff frequency: ~1.59 kHz V1 in 0 AC 1 SIN(0 1 1k) R1 in out 1k C1 out 0 100n .tran 10u 10m .end """ def main(): # Create output directory output_dir = "./output" os.makedirs(output_dir, exist_ok=True) # Write netlist to file netlist_file = os.path.join(output_dir, "simple_rc.net") with open(netlist_file, "w") as f: f.write(netlist_content) print(f"Created netlist: {netlist_file}") # Create SimRunner and run simulation print("Running simulation...") runner = SimRunner(output_folder=output_dir) raw_file, log_file = runner.run_now(netlist_file) print(f"Raw file: {raw_file}") print(f"Log file: {log_file}") # Read results raw = RawRead(raw_file) print(f"\nAnalysis type: {raw.analysis_type}") print(f"Number of traces: {raw.num_variables}") print(f"Number of points: {raw.num_points}") print(f"\nAvailable traces:") for name in raw.get_trace_names(): print(f" - {name}") # Get time and voltage data time = raw.get_trace("time").get_wave(0) v_in = raw.get_trace("V(in)").get_wave(0) v_out = raw.get_trace("V(out)").get_wave(0) print(f"\nTime range: {time[0]*1e3:.3f} ms to {time[-1]*1e3:.3f} ms") print(f"V(in) range: {min(v_in):.3f} V to {max(v_in):.3f} V") print(f"V(out) range: {min(v_out):.3f} V to {max(v_out):.3f} V") # Optional: Plot results if matplotlib is available try: import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(time * 1e3, v_in, label='V(in)', alpha=0.7) ax.plot(time * 1e3, v_out, label='V(out)', linewidth=2) ax.set_xlabel('Time (ms)') ax.set_ylabel('Voltage (V)') ax.set_title('RC Low-Pass Filter Response') ax.legend() ax.grid(True, alpha=0.3) plot_file = os.path.join(output_dir, "simple_rc.png") plt.savefig(plot_file, dpi=150) print(f"\nPlot saved to: {plot_file}") plt.show() except ImportError: print("\nNote: Install matplotlib to generate plots") if __name__ == "__main__": main()