### SimClient Example Source: https://github.com/nunobrum/spicelib/blob/main/doc/readme.md Example of using SimClient to connect to a server, run a simulation, and process results. Ensure the server is running before executing. ```python import logging import sys import zipfile import os from spicelib.simlib import SimClient _logger = logging.getLogger("spicelib.SimClient") _logger.setLevel(logging.DEBUG) _logger.addHandler(logging.StreamHandler(sys.stdout)) server = SimClient('http://localhost', 9000) print(server.session_id) runid = server.run("./testfiles/testfile.net") print("Got Job id", runid) for runid in server: # May not arrive in the same order as runids were launched zip_filename = server.get_runno_data(runid) print(f"Received {zip_filename} from runid {runid}") if zip_filename is None: print(f"Run id {runid} has no data") continue # the zip file normally contains a `.raw` and a `.log` file, # but it can instead only hold a `.fail` file in case of a simulation error. with zipfile.ZipFile(zip_filename, 'r') as zipf: # Extract the contents of the zip file for name in zipf.namelist(): print(f"Extracting {name} from {zip_filename}") zipf.extract(name) os.remove(zip_filename) # Remove the zip file server.close_session() ``` -------------------------------- ### Setup Worst Case Analysis Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/sim_analysis.md Use the WorstCaseAnalysis class to automate the setup of worst-case simulations. Define component tolerances and parameter deviations before proceeding. ```python from spicelib.editor.asc_editor import AscEditor from spicelib.sim.tookit.worst_case import WorstCaseAnalysis sallenkey = AscEditor("./testfiles/sallenkey.asc") wca = WorstCaseAnalysis(sallenkey) # The following lines set the default tolerances for the components wca.set_tolerance('R', 0.01) wca.set_tolerance('C', 0.1) wca.set_tolerance('V', 0.1) # Some components can have a different tolerance wca.set_tolerance('R1', 0.05) # Tolerances can be set for parameters as well. wca.set_parameter_deviation('Vos', 3e-4, 5e-3) ``` -------------------------------- ### Setup Monte Carlo Simulation Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/sim_analysis.md Use the Montecarlo class to automate the setup of Monte Carlo simulations. Define component tolerances and parameter deviations before preparing the testbench and saving the netlist. ```python from spicelib.editor.asc_editor import AscEditor from spicelib.sim.tookit.montecarlo import Montecarlo sallenkey = AscEditor("./testfiles/sallenkey.asc") mc = Montecarlo(sallenkey) # The following lines set the default tolerances for the components mc.set_tolerance('R', 0.01) mc.set_tolerance('C', 0.1, distribution='uniform') mc.set_tolerance('V', 0.1, distribution='normal') # Some components can have a different tolerance mc.set_tolerance('R1', 0.05) # Tolerances can be set for parameters as well mc.set_parameter_deviation('Vos', 3e-4, 5e-3, 'uniform') mc.prepare_testbench(1000) # Finally the netlist is saved to a file mc.save_netlist('./testfiles/sallenkey_mc.net') ``` -------------------------------- ### Windows Spice Simulator Subclass Example Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/simulator_sim.md Example of a subclass for a Windows Spice simulator installation. Ensure 'spice_exe' points to the correct executable path and 'process_name' matches the task manager entry. ```python class MySpiceWindowsInstallation(Simulator): spice_exe = [''] process_name = "" ``` -------------------------------- ### SpiceLib SimClient Example Source: https://github.com/nunobrum/spicelib/blob/main/README.md Demonstrates how to use the SimClient to connect to a running server, initiate a simulation, retrieve results, and handle potential errors. ```python _logger = logging.getLogger("spicelib.SimClient") _logger.setLevel(logging.DEBUG) _logger.addHandler(logging.StreamHandler(sys.stdout)) server = SimClient('http://localhost', 9000) print(server.session_id) runid = server.run("./testfiles/testfile.net") print("Got Job id", runid) for runid in server: # May not arrive in the same order as runids were launched zip_filename = server.get_runno_data(runid) print(f"Received {zip_filename} from runid {runid}") if zip_filename is None: print(f"Run id {runid} has no data") continue # the zip file normally contains a `.raw` and a `.log` file, # but it can instead only hold a `.fail` file in case of a simulation error. with zipfile.ZipFile(zip_filename, 'r') as zipf: # Extract the contents of the zip file for name in zipf.namelist(): print(f"Extracting {name} from {zip_filename}") zipf.extract(name) os.remove(zip_filename) # Remove the zip file server.close_session() ``` -------------------------------- ### Start SpiceLib Server Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/client_server.md Command to start the SpiceLib server. Ensure the specified port is open and machines are on the same network. The default port is 9000 if not specified. ```bash python -m spicelib.scripts.run_server --port 9000 --parallel 4 --output ./temp LTSpice 300 ``` -------------------------------- ### Linux Spice Simulator Subclass Example Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/simulator_sim.md Example of a subclass for a Linux Spice simulator installation. For Linux and MacOS, 'spice_exe' may include a loader like 'wine'. ```python class MySpiceLinuxInstallation(Simulator): spice_exe = ['', ''] process_name = "" ``` -------------------------------- ### Initialize SimClient and Run Simulation Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/sim_client.md Demonstrates how to initialize a SimClient, connect to a server, and run a simulation using a netlist file. It also shows how to retrieve the job ID and iterate over server jobs to get simulation results. ```python import zipfile from PySpice.sim.sim_client import SimClient import os server = SimClient('http://localhost', 9000) # Use another computer address. print(server.session_id) runid = server.run("../../tests/testfile.net") print("Got Job id", runid) for runid in server: # may not arrive in the same order as runids were launched zip_filename = server.get_runno_data(runid) print(f"Received {zip_filename} from runid {runid}") if zip_filename is None: print(f"Run id {runid} has no data") continue # the zip file normally contains a `.raw` and a `.log` file, # but it can instead only hold a `.fail` file in case of a simulation error. with zipfile.ZipFile(zip_filename, 'r') as zipf: # Extract the contents of the zip file for name in zipf.namelist(): print(f"Extracting {name} from {zip_filename}") zipf.extract(name) os.remove(zip_filename) # Remove the zip file ``` -------------------------------- ### Get Steps by Keyword Arguments Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Retrieves simulation steps based on specified parameter values. Requires a corresponding .log file for step information. ```python raw_read.get_steps(V5=1.2, TEMP=25) ``` -------------------------------- ### Initialize AscEditor and SimRunner for Circuit Manipulation Source: https://github.com/nunobrum/spicelib/blob/main/README.md Read an ASCII circuit file into memory and set up a simulation runner for managing simulation outputs. This is the initial setup for advanced circuit analysis and simulation. ```python from spicelib import AscEditor, SimRunner from spicelib.sim.tookit.montecarlo import Montecarlo from spicelib.simulators.ltspice_simulator import LTspice sallenkey = AscEditor("./testfiles/sallenkey.asc") runner = SimRunner(simulator=LTspice, output_folder='./temp_mc', verbose=True) ``` -------------------------------- ### Set Default Simulation Parameters and Run Source: https://github.com/nunobrum/spicelib/blob/main/doc/readme.md Configures simulation parameters, component values, and models, then runs all defined simulations. It also includes an example of processing simulation results and cleaning up files. ```python Stepper.set_parameters(res=0, cap=100e-6) Stepper.set_component_value('R2', '2k') Stepper.set_component_value('R1', '4k') Stepper.set_element_model('V3', "SINE(0 1 3k 0 0 0)") # define simulation Stepper.add_instructions( "; Simulation settings", ";.param run = 0", ".lib ADI1.lib", # This is needed for accessing AD712 ) Stepper.set_parameter('run', 0) Stepper.set_parameter('test_param2', 20) Stepper.add_model_sweep('XU1', ('AD712', 'AD820_ALT')) Stepper.add_value_sweep('V1', (5, 10, 15)) # Stepper.add_value_sweep('V1', (-5, -10, -15)) run_netlist_file = "run_OPAMP_{XU1}_VDD_{V1}.net" Stepper.run_all(callback=processing_data, filenamer=run_netlist_file.format) # Sim Statistics print(f'Successful/Total Simulations: {Stepper.okSim}/{Stepper.runno}') Stepper.export_step_info("./temp2/export.csv") runner.cleanup_files() ``` -------------------------------- ### Command-Line Usage of readme_update Source: https://github.com/nunobrum/spicelib/blob/main/doc/utilities/readme_update.md These examples show how to execute the readme_update script from the command line. Ensure the script is in your PATH or provide the full path to the executable. ```bash readme_update ``` ```bash python3 spicelib/scripts/readme_update.py README.md ``` -------------------------------- ### Example Log File Excerpt Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/SemiOpLogReader.md An excerpt from an LTSpice log file showing the format of Semiconductor Device Operating Points for diodes and bipolar transistors. ```text Semiconductor Device Operating Points: --- Diodes --- Name: d:m6:1:para2:1 d:m4:1:para2:1 d:m3:1:para2:1 d:m6:1:para1:2 Model: m6:1:para2:dpar_5v_psubnburd m4:1:para2:dpar_5v_psubnburd m3:1:para2:dpar_5v_psubnburd dpar_pburdnburdsw Id: 3.45e-19 3.45e-19 3.45e-19 1.11e-13 Vd: 3.27e-07 3.27e-07 3.27e-07 9.27e-02 ... CAP: 3.15e-14 3.15e-14 3.15e-14 5.20e-14 --- Bipolar Transistors --- Name: q:q2:1:2 q:q2:1:1 q:q1:1:2 q:q1:1:1 q:q7:3 Model: q2:1:qnl_pnp q2:1:qnl_m q1:1:qnl_pnp q1:1:qnl_m qpl_parc Ib: 3.94e-12 4.69e-08 7.43e-13 4.70e-08 3.75e-12 Ic: -2.34e-12 4.57e-06 -7.44e-13 4.50e-06 -2.35e-12 Vbe: 1.60e+00 7.40e-01 -7.88e-04 7.40e-01 1.40e+00 ``` -------------------------------- ### Run Remote Simulation Server Client Source: https://github.com/nunobrum/spicelib/blob/main/README.md Example of how to use the SimClient to connect to a running simulation server. Ensure a server is running on the remote machine before executing this client script. ```python import os import zipfile import logging import sys from spicelib.client_server.sim_client import SimClient # In order for this, to work, you need to have a server running. To start a server, run the following command: ``` -------------------------------- ### Generate RAW File with Sine and Cosine Waves Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/write_rawfiles.md This example demonstrates writing a RAW file containing a 3ms transient simulation with a 10kHz sine and a 9.997kHz cosine wave. It requires numpy for data generation and spicelib for RawWrite and Trace objects. ```python import numpy as np from spicelib import Trace, RawWrite LW = RawWrite() tx = Trace('time', np.arange(0.0, 3e-3, 997E-11)) vy = Trace('N001', np.sin(2 * np.pi * tx.data * 10000)) vz = Trace('N002', np.cos(2 * np.pi * tx.data * 9970)) LW.add_trace(tx) LW.add_trace(vy) LW.add_trace(vz) LW.save("test_sincos.raw") ``` -------------------------------- ### Setting up Multi-dimensional Simulation Sweeps Source: https://github.com/nunobrum/spicelib/blob/main/README.md Initializes a SimStepper to manage multi-dimensional simulation sweeps, avoiding nested loops. This example selects a SPICE model and sets up the simulation runner. ```python import os from spicelib import SpiceEditor, SimRunner from spicelib.simulators.ltspice_simulator import LTspice from spicelib.sim.sim_stepping import SimStepper def processing_data(raw_file, log_file): print("Handling the simulation data of %s" % log_file) runner = SimRunner(parallel_sims=4, output_folder='./temp2', simulator=LTspice) # select spice model Stepper = SimStepper(SpiceEditor("./testfiles/Batch_Test.net"), runner) ``` -------------------------------- ### Initializing and Accessing Components in Hierarchical Circuits Source: https://github.com/nunobrum/spicelib/blob/main/README.md Demonstrates initializing SpiceEditor with a netlist and accessing components within subcircuits. It shows equivalent ways to get a component's value and parameters using dot notation or dictionary-like access. ```python import spicelib # my_edt = spicelib.AscEditor("top_circuit.asc") my_edt = spicelib.SpiceEditor("top_circuit.net") # or from a netlist... print(my_edt.get_subcircuit("X1").get_components()) # prints ['C1', 'X2', 'L1'] # The following are equivalent: l1_value0 = my_edt.get_component_value("X1:L1") l1_value1 = my_edt.get_subcircuit("X1").get_component_value("L1") l1_value2 = my_edt["X1:L1"].value # Likewise, for accessing parameters the following are equivalent: x1_c1_prms0 = my_edt.get_subcircuit("X1").get_component_parameters('C1') x1_c1_prms1 = my_edt["X1:C1"].params ``` -------------------------------- ### Running Simulations with Processes and Encapsulated Callback Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/run_simulations.md Utilize processes for running simulations, requiring the callback function to be a static method within a subclass of `ProcessCallback`. All simulation setup and execution code must be within an `if __name__ == "__main__":` block. ```python from spicelib.sim.process_callback import ProcessCallback # Importing the ProcessCallback class type class CallbackProc(ProcessCallback): """Class encapsulating the callback function. It can have whatever name.""" @staticmethod # This decorator defines the callback as a static method, i.e., it doesn't receive the `self`. def callback(raw_file, log_file): # This function must be called callback """This is a call back function that just prints the filenames""" print("Simulation Raw file is %s. The log is %s" % (raw_filename, log_filename) # Other code below either using ltsteps.py or raw_read.py log_info = LTSpiceLogReader(log_filename) log_info.read_measures() rise, measures = log_info.dataset["rise_time"] return rise, measures if __name__ == "__main__": # The code below must be only executed once. # Without this clause, it doesn't work. Don't forget to indent ALL the code below runner = SimRunner(output_folder='./temp', simulator=LTspice) # Configures the output folder and simulator for supply_voltage in (5, 10, 15): netlist.set_component_value('V1', supply_voltage) netlist.set_component_value('V2', -supply_voltage) runner.run(netlist, callback=CallbackProc) for rise, measures in runner: print("The return of the callback function is ", rise, measures) ``` -------------------------------- ### port_list() Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/spice_circuit.md Gets a list of all port names associated with the component. ```APIDOC ## port_list() ### Description Gets the port names of the component as a list. ### Returns List of port names (list[str]) ``` -------------------------------- ### port_names(sep=' ') Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/spice_circuit.md Gets the port names of the component, optionally separated by a specified string. ```APIDOC ## port_names(sep=' ') ### Description Gets the port names of the component. ### Parameters #### Query Parameters - **sep** (str) - Optional - The separator string to use between port names. Defaults to a space. ``` -------------------------------- ### start_session Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/sim_server.md Initiates a new simulation session and returns a unique session identifier. ```APIDOC ## start_session() ### Description Returns an unique key that represents the session. It will be later used to sort the sim_tasks belonging to the session. ### Returns: A unique key that represents the session. ### Return type: str ``` -------------------------------- ### SimServer Constructor Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/sim_server.md Initializes the SimServer with specified parameters for running simulations. ```APIDOC ## class spicelib.client_server.sim_server.SimServer(simulator=None, *, parallel_sims=4, output_folder='./temp', timeout=300, port=9000, host='localhost') ### Description This class implements a server that can run simulations by request of a client located in a different machine. The server is implemented using the SimpleXMLRPCServer class from the xmlrpc.server module. The client can request the server to start a session, run a simulation, check the status of the simulations and retrieve the results of the simulations. The server can run multiple simulations in parallel, but the number of parallel simulations is limited by the parallel_sims parameter. The server can be stopped by the client by calling the stop_server method. ### Parameters: * **simulator** (type | None) – The simulator to be used. It must be a class that derives from the BaseSimulator class. * **parallel_sims** (int) – The maximum number of parallel simulations that the server can run. Default is 4. * **output_folder** (str) – The folder where the results of the simulations will be stored. Default is ‘./temp’ * **timeout** (float) – The maximum time that a simulation can run. Default is None, which means that there is no timeout. * **port** (int) – The port where the server will listen for requests. Default is 9000 * **host** (str) – The IP address where the server will listen for requests. Default is ‘localhost’, which might mean that the server will only accept requests from the local machine. Use ‘0.0.0.0’ to accept requests from any IP address (if your firewall allows it). ``` -------------------------------- ### Get Raw File Type Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Returns the type of the raw file, which can be 'binary' or 'values'. ```python raw_read.raw_type ``` -------------------------------- ### Get Number of Points Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Retrieves the total number of data points in the raw file. ```python raw_read.nPoints ``` -------------------------------- ### Add Simulation Instructions and Set Parameters Source: https://github.com/nunobrum/spicelib/blob/main/doc/readme.md Shows how to add simulation instructions and set parameters using the SpiceEditor. ```python netlist.add_instructions( "; Simulation settings", ";.param run = 0" ) netlist.set_parameter('run', 0) ``` -------------------------------- ### Get Number of Variables Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Retrieves the total number of variables (traces) available in the raw file. ```python raw_read.nVariables ``` -------------------------------- ### prepare_for_simulator(simulator) Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/spice_editor.md A class method that configures library paths for a given simulator, essential for accurate simulation, especially under Wine or with diverse simulator configurations. ```APIDOC ## *classmethod* prepare_for_simulator(simulator) ### Description Sets the library paths that should be correct for the simulator object. The simulator object should have had the executable path (spice_exe) set correctly. This is especially useful in 2 cases: : * when the simulator is running under wine, as it is difficult to detect the correct library paths in that case. * when the editor can be used with different simulators, that have different library paths. ### NOTE * you can always also set the library paths manually via set_custom_library_paths() * this method is a class method and will affect all instances of the class ### Parameters **simulator** ([*Simulator*](simulator_sim.md#spicelib.sim.simulator.Simulator)) – Simulator object from which the library paths will be taken. ### Returns Nothing ### Return type None ``` -------------------------------- ### Get All Trace Names Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Returns a list of all available trace names within the raw file. ```python raw_read.get_trace_names() ``` -------------------------------- ### RawRead.dialect Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Gets the detected dialect of the RAW file, indicating the simulator used (e.g., 'ltspice', 'qspice', 'ngspice', 'xyce'). ```APIDOC ## *property* dialect *: str | None* ### Description The dialect of the RAW file, either ‘ltspice’, ‘qspice’, ‘ngspice’ or ‘xyce’ ``` -------------------------------- ### Retrieve Waveform Data for a Trace Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Gets the waveform data for a specified trace, optionally for a particular step. Returns a numpy array. ```python raw_read.get_wave(trace_ref='V(out)', step=0) ``` -------------------------------- ### to_excel Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Saves the raw file data to an Excel file, with options to specify columns and steps. Requires the 'pandas' module to be installed. ```APIDOC ## to_excel(filename, columns=None, step=-1, **kwargs) ### Description Saves the data to an Excel file. ### Parameters #### Path Parameters - **filename** (str | Path) - Required - Name of the file to save the data to #### Query Parameters - **columns** (list | None) - Optional - List of traces to use as columns. Default is None, meaning all traces - **step** (int | list[int]) - Optional - Step number to retrieve, defaults to -1. - **kwargs** (dict) - Additional arguments to pass to the pandas.DataFrame.to_excel function ### Returns None ### Raises - **ImportError** – when the ‘pandas’ module is not installed ``` -------------------------------- ### prepare_for_simulator Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/asc_editor.md Sets the library paths required for a given simulator. This class method is particularly useful when running simulators under Wine or when using the editor with multiple simulators having different library paths. ```APIDOC ## *classmethod* prepare_for_simulator(simulator) ### Description Sets the library paths that should be correct for the simulator object. The simulator object should have had the executable path (spice_exe) set correctly. This is especially useful in 2 cases: when the simulator is running under wine, as it is difficult to detect the correct library paths in that case, and when the editor can be used with different simulators, that have different library paths. ### Parameters #### Path Parameters * **simulator** (Simulator) - Required - Simulator object from which the library paths will be taken. ### Returns Nothing. ### Return type None ### NOTE * You can always also set the library paths manually via set_custom_library_paths() * This method is a class method and will affect all instances of the class ``` -------------------------------- ### Define Simulation Settings and Run Source: https://github.com/nunobrum/spicelib/blob/main/doc/modules/run_simulations.md Adds simulation settings and iterates through different op-amp models and supply voltages to run simulations. It overrides automatic netlist naming and launches simulations in parallel. ```python netlist.add_instructions( "; Simulation settings", ".param run = 0" ) for opamp in ('AD712', 'AD820_XU1'): # don't use AD820, it is defined in the file and will mess up newer LTspice versions netlist.set_element_model('XU1', opamp) for supply_voltage in (5, 10, 15): netlist.set_component_value('V1', supply_voltage) netlist.set_component_value('V2', -supply_voltage) # overriding he automatic netlist naming run_netlist_file = f"{netlist.netlist_file.name}_{opamp}_{supply_voltage}.net" # This will launch up to 'parallel_sims' simulations in background before waiting for resources runner.run(netlist, run_filename=run_netlist_file, callback=processing_data) # This will wait for the all the simulations launched before to complete. runner.wait_completion() # The timeout counter is reset everytime a simulation is finished. # Sim Statistics print(f'Successful/Total Simulations: {runner.okSim}/{runner.runno}') ``` -------------------------------- ### Add a Control Section to Netlist Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/spice_editor.md Adds a control section to the netlist. The instruction must be a multi-line string starting with '.CONTROL' and ending with '.ENDC'. ```python editor.add_control_section(".CONTROL\nrun\n.ENDC") ``` -------------------------------- ### write_lines(stream) Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/spice_circuit.md Gets the SPICE representation of the component as a string, creating a new line from the attributes alone. Returns the number of characters written. ```APIDOC ## write_lines(stream) ### Description Gets the SPICE representation of the component as a string. This creates a new line from the attributes alone. ### Parameters #### Path Parameters - **stream** (file-like object) - The stream to write the SPICE representation to. ### Returns Number of characters written (int) ``` -------------------------------- ### add_instructions Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/sim_stepper.md Adds multiple SPICE instructions to the netlist from an argument list. ```APIDOC ## add_instructions(*instructions) ### Description Adds a list of instructions to the SPICE NETLIST. ### Parameters * **instructions** - Argument list of instructions to add ### Returns Nothing ### Return type None ``` -------------------------------- ### Save Data to Excel Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/raw_read.md Saves the raw file data to an Excel file, with options to specify columns and step. Requires pandas to be installed. ```python raw_read.to_excel(filename='output.xlsx', columns=None, step=-1) ``` -------------------------------- ### Instantiate Montecarlo Toolkit Source: https://github.com/nunobrum/spicelib/blob/main/README.md Create an instance of the Montecarlo class, linking the AscEditor instance with the SimRunner. This prepares the system for Monte Carlo simulations. ```python mc = Montecarlo(sallenkey, runner) ``` -------------------------------- ### Iterate and Simulate with Different Models and Voltages Source: https://github.com/nunobrum/spicelib/blob/main/README.md This snippet iterates through different op-amp models and supply voltages, updating the netlist and running simulations. It also shows how to conditionally set solver options. ```python alt_solver = True for opamp in ('AD712', 'AD820_ALT'): # When updating an instance, the instance name gets appended to the subcircuit netlist['XU1'].model = opamp # or netlist.set_element_model('XU1', opamp) for supply_voltage in (5, 10, 15): netlist['V1'].value = supply_voltage netlist['V2'].value = -supply_voltage print("simulating OpAmp", opamp, "Voltage", supply_voltage) # small example on how to use options, here how to force the solver opts = [] if alt_solver: opts.append('-alt') else: opts.append('-norm') runner.run(netlist, switches=opts, exe_log=True) # run, and log console output fo file ``` -------------------------------- ### add_control_section Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/spice_editor.md Adds a control section to the netlist, which must start with '.CONTROL' and end with '.ENDC'. This method provides format checking for the control section instruction. ```APIDOC ## add_control_section(instruction) ### Description Adds a control section to the netlist. The instruction should be a multi-line string that starts with ‘.CONTROL’ and ends with ‘.ENDC’. It will be added as a ControlEditor object to the netlist. You can also use the add_instruction() method, but that method has less checking of the format. ### Parameters * **instruction** (str) - control section instruction ### Raises * **ValueError** - if the instruction does not start with `.CONTROL` or does not end with `.ENDC` ``` -------------------------------- ### Get and Set Subcircuit Component Values Source: https://github.com/nunobrum/spicelib/blob/main/README.md Demonstrates how to retrieve and modify the values of components within a subcircuit. Ensure the component is not from a library to avoid exceptions. ```python import spicelib my_edt = spicelib.SpiceEditor("top_circuit.net") my_sub = my_edt.get_subcircuit_named("MYSUBCKT") print(my_sub.get_components()) # prints ['C1', 'X2', 'L1'] # The following are equivalent: l1_value0 = my_sub.get_component_value("L1") l1_value1 = my_sub["L1"].value # Note that this will not work if the component X1 is from a library. An exception will occur in that case. my_sub.set_component_value("L1", 2e-6) # sets L1 in X1 instance to 2uH my_sub["L1"].value = 2e-6 # Same as the instructionn above ``` -------------------------------- ### Set Default Simulation Parameters Source: https://github.com/nunobrum/spicelib/blob/main/README.md Configure default simulation settings like resolution and capacitance. Use this to establish baseline parameters before running simulations. ```python Stepper.set_parameters(res=0, cap=100e-6) ``` -------------------------------- ### get_wave Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/trace.md Returns the data contained in the trace object. For stepped simulations, a step number must be provided. Returns a numpy array if numpy is installed. ```APIDOC ## get_wave(step=0) ### Description Returns the data contained in this object. For stepped simulations an argument must be passed specifying the step number. If no steps exist, the argument must be left blank. To know whether stepped data exist, the user can use the get_raw_property(‘Flags’) method. If numpy is available the get_wave() method will return a numpy array. ### Parameters #### Path Parameters - **step** (int) - Optional - To be used when stepped data exist on the RAW file. ### Returns - **ndarray** - a List or numpy array (if installed) containing the data contained in this object. ``` -------------------------------- ### Parameter Sweeps with SimStepper Source: https://github.com/nunobrum/spicelib/blob/main/doc/classes/sim_stepper.md Demonstrates how to perform the same parameter sweeps as the manual method but using the SimStepper class for a more concise and readable code. It utilizes methods like add_model_sweep, add_component_sweep, and add_parameter_sweep. ```python netlist = SpiceEditor("my_circuit.asc") Stepper = SimStepper(netlist, SimRunner(parallel_sims=4, output_folder="./output")) Stepper.add_model_sweep('D1', "BAT54", "BAT46WJ") Stepper.add_component_sweep('R1', sweep(2.2, 2,4, 0.2)) # Steps from 2.2 to 2.4 with 0.2 increments Stepper.add_parameter_sweep('temp', sweep(0, 80, 20)) # Makes temperature step from 0 to 80 degrees in 20 # degree steps Stepper.add_component_sweep('R2', (10, 25, 32)) # Updates the resistor R2 value to be 3.3k Stepper.run_all() ``` -------------------------------- ### Accessing and Modifying Subcircuit Components Source: https://github.com/nunobrum/spicelib/blob/main/doc/readme.md Demonstrates how to get a subcircuit, list its components, and modify the values and parameters of its components. Note that this functionality is restricted for components from libraries. ```python import spicelib my_edt = spicelib.SpiceEditor("top_circuit.net") my_sub = my_edt.get_subcircuit_named("MYSUBCKT") print(my_sub.get_components()) # prints ['C1', 'X2', 'L1'] # The following are equivalent: l1_value0 = my_sub.get_component_value("L1") l1_value1 = my_sub["L1"].value # Note that this will not work if the component X1 is from a library. An exception will occur in that case. my_sub.set_component_value("L1", 2e-6) # sets L1 in X1 instance to 2uH my_sub["L1"].value = 2e-6 # Same as the instructionn above # Likewise, for accessing parameters the following are equivalent: c1_value0 = my_sub.get_component_parameters('C1') c1_value1 = my_sub["C1"].params # Likewise, the following are equivalent: # Note that this will not work if the component X1 is from a library. An exception will occur in that case. my_sub.set_component_parameters("C1", Rser=1) my_sub["C1"].set_params(Rser=1) my_sub["C1"].params = dict(Rser=1) ``` -------------------------------- ### Accessing Component Values in Hierarchical Circuits Source: https://github.com/nunobrum/spicelib/blob/main/doc/readme.md Demonstrates equivalent ways to get the value of a component within a subcircuit using SpiceLib. Assumes the subcircuit is not from a library. ```python import spicelib # my_edt = spicelib.AscEditor("top_circuit.asc") my_edt = spicelib.SpiceEditor("top_circuit.net") # or from a netlist... print(my_edt.get_subcircuit("X1").get_components()) # prints ['C1', 'X2', 'L1'] # The following are equivalent: l1_value0 = my_edt.get_component_value("X1:L1") l1_value1 = my_edt.get_subcircuit("X1").get_component_value("L1") l1_value2 = my_edt["X1:L1"].value ``` -------------------------------- ### Get and Set Subcircuit Component Parameters Source: https://github.com/nunobrum/spicelib/blob/main/README.md Shows how to access and change parameters of components within a subcircuit. This operation will raise an exception if the component originates from a library. ```python # Likewise, for accessing parameters the following are equivalent: c1_value0 = my_sub.get_component_parameters('C1') c1_value1 = my_sub["C1"].params # Likewise, the following are equivalent: # Note that this will not work if the component X1 is from a library. An exception will occur in that case. my_sub.set_component_parameters("C1", Rser=1) my_sub["C1"].set_params(Rser=1) my_sub["C1"].params = dict(Rser=1) ``` -------------------------------- ### Configure SpiceLib Logging Source: https://github.com/nunobrum/spicelib/blob/main/README.md Demonstrates how to set global and module-specific logging levels for the SpiceLib library using Python's logging module. ```python import logging logging.basicConfig(level=logging.INFO) # Set up the root logger first import spicelib # Import spicelib to set the logging levels spicelib.set_log_level(logging.DEBUG) # Set spicelib's global log level logging.getLogger("spicelib.RawRead").level = logging.WARNING # Set the log level for only RawRead to warning ``` -------------------------------- ### Rawplot Command Line Usage Source: https://github.com/nunobrum/spicelib/blob/main/README.md Plot data from a raw file using Matplotlib. Requires Matplotlib to be installed. Specify the raw file and the trace name to plot. ```text Usage: rawplot RAW_FILE TRACE_NAME ``` -------------------------------- ### asc_to_qsch Options Source: https://github.com/nunobrum/spicelib/blob/main/doc/utilities/asc_to_qsch.md Available command-line options for the asc_to_qsch utility, including help and symbol path addition. ```text Options: --version show program's version number and exit -h, --help show this help message and exit -a , --add= Add a path for searching for symbols ``` -------------------------------- ### Add Simulation Instructions Source: https://github.com/nunobrum/spicelib/blob/main/README.md Demonstrates how to add simulation control instructions to the netlist. These are typically comments or simulation commands. ```python netlist.add_instructions( "; Simulation settings", ";.param run = 0" ) ``` -------------------------------- ### Modify Component Value in Subcircuit Source: https://github.com/nunobrum/spicelib/blob/main/README.md Shows how to change the value of a specific component within a subcircuit instance. The example targets component 'C2' within the subcircuit instance 'XU1'. ```python netlist.set_component_value('XU1:C2', 20e-12) ``` -------------------------------- ### Add Simulation Instructions and Parameters Source: https://github.com/nunobrum/spicelib/blob/main/README.md Include custom simulation directives and set simulation parameters. This is essential for defining simulation behavior, such as loading libraries or setting run parameters. ```python Stepper.add_instructions( "; Simulation settings", ";.param run = 0", ".lib ADI1.lib", # This is needed for accessing AD712 ) ``` ```python Stepper.set_parameter('run', 0) Stepper.set_parameter('test_param2', 20) ```