### Install PyLTSpice Source: https://github.com/nunobrum/pyltspice/blob/master/README.md Install the PyLTSpice library using pip. ```bash pip install PyLTSpice ``` -------------------------------- ### Define Linux Spice Simulator Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Example of a subclass for a Linux Spice installation. Use `spice_exe` to specify the wine command and the path to the executable. `process_name` should be the system process name. ```python class MySpiceLinuxInstallation(Simulator): spice_exe = ['', ''] process_name = "" ``` -------------------------------- ### Setup Monte Carlo Simulation with PyLTSpice Source: https://github.com/nunobrum/pyltspice/blob/master/doc/modules/sim_analysis.md Use the Montecarlo class to automate the setup of Monte Carlo simulations. Specify component tolerances, parameter deviations, and prepare the testbench for a specified number of runs. The netlist is then saved with modifications to generate random values and include the .step command. ```python from PyLTSpice import AscEditor # Imports the class that manipulates the asc file from PyLTSpice.sim.tookit.montecarlo import Montecarlo # Imports the Montecarlo toolkit class sallenkey = AscEditor("./testfiles/sallenkey.asc") # Reads the asc file into memory mc = Montecarlo(sallenkey) # Instantiates the Montecarlo class, with the asc file already in memory # The following lines set the default tolerances for the components mc.set_tolerance('R', 0.01) # 1% tolerance, default distribution is uniform mc.set_tolerance('C', 0.1, distribution='uniform') # 10% tolerance, explicit uniform distribution mc.set_tolerance('V', 0.1, distribution='normal') # 10% tolerance, but using a normal distribution # Some components can have a different tolerance mc.set_tolerance('R1', 0.05) # 5% tolerance for R1 only. This only overrides the default tolerance for R1 # Tolerances can be set for parameters as well mc.set_parameter_deviation('Vos', 3e-4, 5e-3, 'uniform') # The keyword 'distribution' is optional mc.prepare_testbench(1000) # Prepares the testbench for 1000 simulations # Finally the netlist is saved to a file mc.save_netlist('./testfiles/sallenkey_mc.net') ``` -------------------------------- ### SimRunner.create_netlist Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/simulation_classes.md Creates a netlist from the current simulation setup. ```APIDOC ## SimRunner.create_netlist() ### Description Creates a netlist file for the simulation. ### Method This is a method of the SimRunner class. ### Parameters None explicitly documented. ### Request Example ```python sim_runner.create_netlist() ``` ### Response None explicitly documented. The primary effect is the creation of a netlist file. ``` -------------------------------- ### Define Windows Spice Simulator Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Example of a subclass for a Windows Spice installation. Set the `spice_exe` to the path of the executable and `process_name` to its name in Task Manager. ```python class MySpiceWindowsInstallation(Simulator): spice_exe = [''] process_name = "" ``` -------------------------------- ### Simulator.is_available Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Checks if the simulator is installed and available on the system. ```APIDOC ## classmethod is_available() ### Description This method checks if the simulator exists in the system. It will return a boolean value indicating if the simulator is installed or not. ``` -------------------------------- ### PyLTSpice Process Callback Example Source: https://github.com/nunobrum/pyltspice/blob/master/doc/modules/run_simulations.md Demonstrates how to define a static callback method within a `ProcessCallback` subclass for parallel simulation execution. Ensure all simulation setup and execution code is within an `if __name__ == '__main__':` block. ```python from PyLTSpice.sim.process_callback import ProcessCallback 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) ``` -------------------------------- ### Sequential LTSpice Simulation Setup and Execution Source: https://github.com/nunobrum/pyltspice/blob/master/doc/modules/run_simulations.md Configures a simulator to use a specific output folder and then opens a Spice netlist file. It proceeds to modify netlist parameters, component values, and models before running a single simulation. This method is less efficient as it runs simulations one after another. ```python from PyLTSpice import SimRunner, SpiceEditor, LTspice runner = SimRunner(output_folder='./temp_batch3', simulator=LTspice) # Configures the simulator to use and output # folder netlist = SpiceEditor("Batch_Test.asc") # Open the Spice Model, and creates the .net # set default arguments netlist.set_parameters(res=0, cap=100e-6) netlist.set_component_value('R2', '2k') # Modifying the value of a resistor netlist.set_component_value('R1', '4k') # Set component temperature, Tc 50ppm, remove power rating : netlist.set_component_parameters('R1', temp=100, tc=0.000050, pwr=None) netlist.set_element_model('V3', "SINE(0 1 3k 0 0 0)") # Modifying the model of a voltage source netlist.set_component_value('XU1:C2', 20e-12) # modifying an internal component value # define simulation netlist.add_instructions( "; Simulation settings", ".param run = 0" ) for opamp in ('AD712', 'AD820'): 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 = "{}_{}_{}.net".format(netlist.netlist_file.name, opamp, supply_voltage) raw, log = runner.run_now(netlist, run_filename=run_netlist_file) # Process here the simulation results ``` -------------------------------- ### Setup Worst Case Analysis with PyLTSpice Source: https://github.com/nunobrum/pyltspice/blob/master/doc/modules/sim_analysis.md Use the WorstCaseAnalysis class to set up worst-case simulations. Define component tolerances and parameter deviations. For worst-case analysis, the distribution type is irrelevant. ```python from PyLTSpice import AscEditor # Imports the class that manipulates the asc file from PyLTSpice.sim.tookit.worst_case import WorstCaseAnalysis sallenkey = AscEditor("./testfiles/sallenkey.asc") # Reads the asc file into memory wca = WorstCaseAnalysis(sallenkey) # Instantiates the Worst Case Analysis class # The following lines set the default tolerances for the components wca.set_tolerance('R', 0.01) # 1% tolerance wca.set_tolerance('C', 0.1) # 10% tolerance wca.set_tolerance('V', 0.1) # 10% tolerance. For Worst Case analysis, the distribution is irrelevant # Some components can have a different tolerance wca.set_tolerance('R1', 0.05) # 5% tolerance for R1 only. This only overrides the default tolerance for R1 # Tolerances can be set for parameters as well. wca.set_parameter_deviation('Vos', 3e-4, 5e-3) ``` -------------------------------- ### Get Simulation Steps Source: https://github.com/nunobrum/pyltspice/blob/master/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) ``` -------------------------------- ### Run and Modify LTspice Simulations Source: https://github.com/nunobrum/pyltspice/blob/master/README.md Launches LTspice simulations from the command line, allowing modification of netlists and parameters. Results can be processed with RawRead or LTSteps. This example demonstrates setting parameters, component values, and models for multiple simulation runs. ```python from PyLTSpice import SimRunner from PyLTSpice import SpiceEditor # Force another simulatior simulator = r"C:\Program Files\LTC\LTspiceXVII\XVIIx64.exe" # select spice model LTC = SimRunner(output_folder='./temp') LTC.create_netlist('./testfiles/Batch_Test.asc') netlist = SpiceEditor('./testfiles/Batch_Test.net') # set default arguments netlist.set_parameters(res=0, cap=100e-6) netlist.set_component_value('R2', '2k') # Modifying the value of a resistor netlist.set_component_value('R1', '4k') netlist.set_element_model('V3', "SINE(0 1 3k 0 0 0)") # Modifying the netlist.set_component_value('XU1:C2', 20e-12) # modifying a define simulation netlist.add_instructions( "; Simulation settings", ";.param run = 0" ) netlist.set_parameter('run', 0) for opamp in ('AD712', 'AD820'): 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) print("simulating OpAmp", opamp, "Voltage", supply_voltage) LTC.run(netlist) for raw, log in LTC: print("Raw file: %s, Log file: %s" % (raw, log)) # do something with the data # raw_data = RawRead(raw) # log_data = LTSteps(log) # ... netlist.reset_netlist() netlist.add_instructions( "; Simulation settings", ".ac dec 30 10 1Meg", ".meas AC Gain MAX mag(V(out)) ; find the peak response and call it \"Gain\"", ".meas AC Fcut TRIG mag(V(out))=Gain/sqrt(2) FALL=last" ) # Sim Statistics print(f'Successful/Total Simulations: {LTC.okSim}/{LTC.runno}') enter = input("Press enter to delete created files") if enter == '': LTC.file_cleanup() ``` -------------------------------- ### Run LTSpice Server Command Line Interface Source: https://github.com/nunobrum/pyltspice/blob/master/README.md This command line interface starts a simulation server. It allows configuration of port, host, output directory, and parallel simulation threads. The first argument specifies the simulator to use. ```text usage: run_server.py [-h] [-p PORT] [-H HOST] [-o OUTPUT] [-l PARALLEL] [{ltspice,ngspice,xyce}] [timeout] Run the LTSpice Server. This is a command line interface to the SimServer class.The SimServer class is used to run simulations in parallel using a server-client architecture.The server is a machine that runs the SimServer class and the client is a machine that runs the SimClient class.The argument is the simulator to be used (LTSpice, NGSpice, XYCE, etc.) positional arguments: {ltspice,ngspice,xyce} Simulator to be used (LTSpice, NGSpice, XYCE, etc.). Default is LTSpice timeout Timeout for the simulations. Default is 300 seconds (5 minutes) options: -h, --help show this help message and exit -p, --port PORT Port to run the server. Default is 9000 -H, --host HOST 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 -o, --output OUTPUT Output folder for the results. Default is the current folder -l, --parallel PARALLEL Maximum number of parallel simulations. Default is 4 ``` -------------------------------- ### AscEditor.simulator_lib_paths Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/editor_classes.md Gets or sets the simulator library paths. ```APIDOC ## AscEditor.simulator_lib_paths ### Description Gets or sets the simulator library paths. ### Method (Not specified in source, likely a Python property) ### Parameters (Parameters not specified in source) ### Request Example ```python # Get paths paths = editor.simulator_lib_paths # Set paths editor.simulator_lib_paths = ['/path/to/lib1', '/path/to/lib2'] ``` ### Response (Response details not specified in source) ``` -------------------------------- ### Check Simulator Availability Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md The `is_available` classmethod checks if the simulator is installed on the system and returns a boolean value indicating its availability. ```python is_available() ``` -------------------------------- ### Get Default Library Paths Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md The `get_default_library_paths` classmethod returns a list of directories where standard simulator libraries are located. This is derived from the simulator's executable path and the platform. `spice_exe` must be set before calling. ```python get_default_library_paths() ``` -------------------------------- ### Expand and Check Local Directory Path Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md The `expand_and_check_local_dir` static method expands a directory path to an absolute path, handling potential wine usage on MacOS/Linux and verifying directory existence. It supports absolute paths or paths starting with '~'. ```python expand_and_check_local_dir(path, exe_path=None) ``` -------------------------------- ### Simulator.run Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Abstract class method to initiate a circuit simulation for a given netlist file. Subclasses must implement this method to define how the simulation is executed. ```APIDOC ## classmethod run(netlist_file, cmd_line_switches=None, timeout=None, stdout=None, stderr=None, cwd=None, exe_log=False) ### Description This method implements the call for the simulation of the netlist file. This should be overriden by its subclass. ### Parameters * **netlist_file** (str | Path) - The path to the netlist file to be simulated. * **cmd_line_switches** (list | None) - Optional list of command-line switches to pass to the simulator. * **timeout** (float | None) - Optional timeout in seconds for the simulation process. * **stdout** (file-like object | None) - Optional file-like object to capture standard output. * **stderr** (file-like object | None) - Optional file-like object to capture standard error. * **cwd** (str | Path | None) - Optional working directory for the simulation process. * **exe_log** (bool) - If True, enables logging of the executable's output. Defaults to False. ### Returns An integer representing the exit code of the simulation process. ``` -------------------------------- ### prepare_for_simulator Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/asc_editor.md Sets the library paths for a given simulator, especially useful for Wine or different simulator configurations. ```APIDOC ## 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. 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 #### Path Parameters - **simulator** (Simulator) - Simulator object from which the library paths will be taken. ### Returns - Nothing ``` -------------------------------- ### add_control_section Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/spice_editor.md Adds a control section to the netlist, which must start with '.CONTROL' and end with '.ENDC'. ```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` ``` -------------------------------- ### Create Simulator Instance from Path Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md The `create_from` classmethod allows creating a simulator class instance by providing the path to the simulator executable. It can optionally take a process name for killing phantom processes. ```python create_from(path_to_exe, process_name=None) ``` -------------------------------- ### Get Trace Names Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/raw_read.md Returns a list of all available trace names within the RAW file. ```python raw_read.get_trace_names() ``` -------------------------------- ### Get Waveform Data Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/raw_read.md Retrieves the waveform data for a specified trace, optionally for a particular simulation step. ```python raw_read.get_wave(trace_ref, step=0) ``` -------------------------------- ### add_instructions Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/asc_editor.md Adds a list of SPICE instructions to the netlist. ```APIDOC ## add_instructions *instructions ### Description Adds a list of instructions to the SPICE NETLIST. Example: ```python editor.add_instructions(".STEP run -1 1023 1", ".dc V1 -5 5") ``` ### Parameters * **instructions** – Argument list of instructions to add ### Returns Nothing ### Return type None ``` -------------------------------- ### Run Monte Carlo Simulation with PyLTSpice Source: https://github.com/nunobrum/pyltspice/blob/master/README.md This snippet demonstrates how to perform Monte Carlo simulations using PyLTSpice. It covers setting component tolerances, preparing the testbench for multiple runs, executing simulations, and analyzing the results. Use this for statistical analysis of circuit variations. ```python from PyLTSpice import AscEditor, SimRunner from PyLTSpice.sim.tookit.montecarlo import Montecarlo sallenkey = AscEditor("./testfiles/sallenkey.asc") runner = SimRunner(output_folder='./temp_mc') mc = Montecarlo(sallenkey, runner) mc.set_tolerance('R', 0.01) mc.set_tolerance('C', 0.1, distribution='uniform') mc.set_tolerance('V', 0.1, distribution='normal') mc.set_tolerance('R1', 0.05) mc.set_parameter_deviation('Vos', 3e-4, 5e-3, 'uniform') mc.prepare_testbench(num_runs=1000) mc.save_netlist('./testfiles/sallenkey_mc.net') mc.run_testbench(runs_per_sim=100) logs = mc.read_logfiles() logs.obtain_amplitude_and_phase_from_complex_values() logs.export_data('./temp_mc/data_testbench.csv') logs.plot_histogram('fcut') mc.cleanup_files() print("=====================================") mc.clear_simulation_data() mc.reset_netlist() mc.run_analysis(num_runs=1000) logs = mc.read_logfiles() logs.export_data('./temp_mc/data_sims.csv') logs.plot_histogram('fcut') mc.cleanup_files() ``` -------------------------------- ### Save Data to Excel Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/raw_read.md Saves selected trace data to an Excel file. Requires pandas to be installed. Allows selection of columns and steps. ```python raw_read.to_excel(filename, columns=None, step=-1, **kwargs) ``` -------------------------------- ### RawRead Methods Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/raw_read.md Provides methods to export data, retrieve axis information, get data lengths, plot names, and raw properties. ```APIDOC ### Methods: #### export(columns=None, step=-1, **kwargs) Returns a native python class structure with the requested trace data and steps. It consists of an ordered dictionary where the columns are the keys and the values are lists with the data. This function is used by the export functions. * **Parameters:** * **step** (*int* *|* *list* *[**int* *]*) – Step number to retrieve. If not given, it will return all steps * **columns** (*list* *|* *None*) – List of traces to use as columns. Default is all traces * **kwargs** (`**dict`) – Additional arguments to pass to the pandas.DataFrame constructor * **Returns:** A pandas DataFrame * **Return type:** dict[str, list] #### get_axis(step=0) This function is equivalent to get_trace(0).get_wave(step) instruction. It also implements a workaround on a LTSpice issue when using 2nd Order compression, where some values on the time trace have a negative value. * **Parameters:** **step** (*int*) – Step number, defaults to 0 * **Raises:** **RuntimeError** – if the RAW file does not have an axis. * **Returns:** Array with the X axis * **Return type:** *ndarray* | list[float] #### get_len(step=0) Returns the length of the data at the give step index. * **Parameters:** **step** (*int*) – the step index, defaults to 0 * **Returns:** The number of data points * **Return type:** int #### get_nr_plots() Returns the number of plots in the RAW file. * **Returns:** Number of plots * **Return type:** int #### get_plot_name() Returns the type of the plot read from the RAW file. Some examples: ‘AC Analysis’, ‘DC transfer characteristic’, ‘Operating Point’, ‘Transient Analysis’, ‘Transfer Function’, ‘Noise Spectral Density’, ‘Frequency Response Analysis’, ‘Noise Spectral Density Curves’, ‘Integrated Noise’ * **Returns:** plot name * **Return type:** str #### get_plot_names() Returns a list of plot names in the RAW file. * **Returns:** List of plot names * **Return type:** list[str] #### get_raw_properties() Get all raw properties. * **Returns:** Dictionary of all raw properties * **Return type:** dict[str, str] #### get_raw_property(property_name=None) Get a property. By default, it returns all properties defined in the RAW file. * **Parameters:** **property_name** (*str*) – name of the property to retrieve. If None, all properties are returned. * **Returns:** Property object * **Raises:** ValueError if the property doesn’t exist * **Return type:** str | dict[str, str] ``` -------------------------------- ### RunTask.run Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/simulation_classes.md Initiates the simulation task. ```APIDOC ## RunTask.run() ### Description Starts the execution of the simulation task. ### Method This is a method of the RunTask class. ### Parameters None explicitly documented. ### Request Example ```python run_task.run() ``` ### Response None explicitly documented. The method initiates an asynchronous or synchronous simulation run. ``` -------------------------------- ### Reset Netlist Edits Source: https://github.com/nunobrum/pyltspice/blob/master/README.md Resets all modifications made to the spice netlist, reverting it to its original state. This is useful if you need to start over with netlist editing. ```python reset_netlist() # Resets all edits done to the netlist. ``` -------------------------------- ### Plot Data from RAW Files with rawplot Source: https://github.com/nunobrum/pyltspice/blob/master/README.md Plots data from a specified raw file using a given trace name. Requires Matplotlib to be installed. ```text Usage: rawplot RAW_FILE TRACE_NAME ``` -------------------------------- ### Get Trace Data Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/raw_read.md Retrieves a specific trace's data by its name or index. Handles potential negative time values in specific LTSpice compression scenarios. ```python raw_read.get_trace(trace_ref) ``` -------------------------------- ### SpiceEditor Constructor Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/spice_editor.md Initializes the SpiceEditor with a netlist file. It can optionally create a blank file or handle include files. ```APIDOC ## SpiceEditor(netlist_file, encoding='autodetect', **kwargs) ### Description Provides interfaces to manipulate SPICE netlist files. The class doesn’t update the netlist file itself. After implementing the modifications, the user should call the “save_netlist” method to write a new netlist file. ### Parameters * **netlist_file** (*Path* *|* *str*) – Name of the .NET file to parse * **encoding** – Forcing the encoding to be used on the circuit netlile read. Defaults to ‘autodetect’ which will call a function that tries to detect the encoding automatically. This, however, is not 100% foolproof. * **Keyword Arguments:** * **create_blank** – Create a blank ‘.net’ file when ‘netlist_file’ not exist. False by default * **include_file** – If an include file is being parsed, the control of the ending .END statement is suppressed. ``` -------------------------------- ### Run Worst-Case Analysis with PyLTSpice Source: https://github.com/nunobrum/pyltspice/blob/master/README.md Demonstrates how to perform worst-case analysis on an LTSpice circuit. It involves setting component tolerances, running simulations, and analyzing the results. Ensure the output folder exists or is created. ```python from PyLTSpice import AscEditor, SimRunner # Imports the class that manipulates the asc file from PyLTSpice.sim.tookit.worst_case import WorstCaseAnalysis sallenkey = AscEditor("./testfiles/sallenkey.asc") # Reads the asc file into memory runner = SimRunner(output_folder='./temp_wca') # Instantiates the runner class, with the output folder already set wca = WorstCaseAnalysis(sallenkey, runner) # Instantiates the Worst Case Analysis class # The following lines set the default tolerances for the components wca.set_tolerance('R', 0.01) # 1% tolerance wca.set_tolerance('C', 0.1) # 10% tolerance wca.set_tolerance('V', 0.1) # 10% tolerance. For Worst Case analysis, the distribution is irrelevant # Some components can have a different tolerance wca.set_tolerance('R1', 0.05) # 5% tolerance for R1 only. This only overrides the default tolerance for R1 # Tolerances can be set for parameters as well. wca.set_parameter_deviation('Vos', 3e-4, 5e-3) # Finally the netlist is saved to a file wca.save_netlist('./testfiles/sallenkey_wc.asc') wca.run_testbench() # Runs the simulation with splits of 100 runs each logs = wca.read_logfiles() # Reads the log files and stores the results in the results attribute logs.export_data('./temp_wca/data.csv') # Exports the data to a csv file print("Worst case results:") for param in ('fcut', 'fcut_FROM'): print(f"{param}: min:{logs.min_measure_value(param)} max:{logs.max_measure_value(param)}") wca.cleanup_files() # Deletes the temporary files ``` -------------------------------- ### Implement Simulator run() Method Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md The `run()` method should be implemented as a classmethod to handle the simulation of a netlist file. It constructs the command and calls `run_function`. ```python @classmethod def run(cls, netlist_file: str | Path, cmd_line_switches: list | None = None, timeout: float | None = None, stdout=None, stderr=None, cwd: str | Path | None = None, exe_log: bool = False) -> int: '''This method implements the call for the simulation of the netlist file. ''' cmd_run = cls.spice_exe + ['-Run'] + ['-b'] + [netlist_file] + cmd_line_switches return run_function(cmd_run, timeout=timeout, stdout=stdout, stderr=stderr, cwd=cwd) ``` -------------------------------- ### Run Remote Simulations with SimClient Source: https://github.com/nunobrum/pyltspice/blob/master/README.md This snippet demonstrates how to use the SimClient to connect to a remote simulation server, submit a netlist, and retrieve simulation results. Ensure a server is running on the specified host and port. ```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: # python -m PyLTSpice.scripts.run_server --port 9000 --parallel 4 --output ./temp LTSpice 300 _logger = logging.getLogger("PyLTSpice.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() ``` -------------------------------- ### Simulator.create_from Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Creates a simulator class instance from a given path to the simulator executable. ```APIDOC ## classmethod create_from(path_to_exe, process_name=None) ### Description Creates a simulator class from a path to the simulator executable. ### Parameters * **path_to_exe** (pathlib.Path or str) - The path to the simulator executable. If a string, it can support multiple sections (e.g., for loaders like wine) and must be in POSIX format, with the last section being the executable. * **process_name** (str | None) - The process name to be used for killing phantom processes. If not provided, it will be inferred. ### Returns A class instance representing the Spice simulator. ### Return type [Simulator](#spicelib.sim.simulator.Simulator) ``` -------------------------------- ### begin_update Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/spice_editor.md Begins an update operation on the netlist. ```APIDOC ## begin_update() ### Description Begins an update operation. ``` -------------------------------- ### create_netlist Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Creates a netlist from a given circuit file. This class method allows for customization of command-line switches, timeouts, and output redirection. ```APIDOC ## classmethod create_netlist(circuit_file, cmd_line_switches=None, timeout=None, stdout=None, stderr=None, cwd=None, exe_log=False) ### Description Create a netlist out of the circuit file ### Parameters #### Path Parameters * **circuit_file** (str | Path) – path to the circuit file #### Query Parameters * **cmd_line_switches** (list | None) – additional command line options. Best to have been validated by valid_switch(), defaults to None * **timeout** (float | None) – If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised, defaults to None * **stdout** (_FILE, optional) – control redirection of the command’s stdout. Valid values are None, subprocess.PIPE, subprocess.DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings of None, no redirection will occur. Also see exe_log for a simpler form of control. * **stderr** (_FILE, optional) – Like stdout, but affecting the command’s error output. Also see exe_log for a simpler form of control. * **cwd** (str | Path | None) – The current working directory to run the command in. If None, no change will be done of the working directory. This may not work as wanted when using the simulator under wine. * **exe_log** (bool) – If True, stdout and stderr will be ignored, and the simulator’s execution console messages will be written to a log file (named …exe.log) instead of console. This is especially useful when running under wine or when running simultaneous tasks. ### Raises * NotImplementedError – when the requested execution is not possible on this platform. * RuntimeError – when the netlist cannot be created ### Returns path to the netlist produced ### Return type Path ``` -------------------------------- ### get_steps Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/raw_read.md Retrieves steps from the raw file that match the criteria specified in the keyword arguments. Requires a corresponding .log file. ```APIDOC ## get_steps(**kwargs) ### Description Returns the steps that correspond to the query set in the **kwargs parameters. This feature is only possible if a .log file with the same name as the .raw file exists in the same directory. Note: the correspondence between step numbers and .STEP information is stored on the .log file. ### Parameters #### Key kwargs: - key-value arguments in which the key correspond to a stepped parameter or source name, and the value is the stepped value. ### Returns The steps that match the query ### Return type list[int] | range ### Example ```python raw_read.get_steps(V5=1.2, TEMP=25) ``` ``` -------------------------------- ### save_as Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/spice_editor.md Saves the netlist to a new file. The new file will be created if it does not exist, and overwritten if it does exist. ```APIDOC ## save_as ### Description Saves the netlist to a new file. The new file will be created if it does not exist, and overwritten if it does exist. ### Method (Not specified, likely a class method) ### Parameters #### Path Parameters * **new_circuit_filepath** (str or Path) - Required - Path to the new netlist file ### Returns * **None** ``` -------------------------------- ### Simulator.expand_and_check_local_dir Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Expands a directory path to an absolute path, considering potential use under wine, and checks for its existence. ```APIDOC ## static expand_and_check_local_dir(path, exe_path=None) ### Description Expands a directory path to become an absolute path, while taking into account a potential use under wine (under MacOS and Linux). Will also check if that directory exists. The path must either be an absolute path or start with ~. Relative paths are not supported. On MacOS or Linux, it will try to replace any reference to the virtual windows root under wine into a host OS path. ### Parameters * **path** (str) - The path to expand. Must be in posix format; use PureWindowsPath(path).as_posix() to transform a windows path to a posix path. * **exe_path** (str | None) - Path to a related executable that may or may not be under wine, defaults to None, ignored on Windows. ### Returns The fully expanded path, as posix path. Will return None if the path does not exist. ### Return type str | None ``` -------------------------------- ### get_components Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/asc_editor.md Retrieves a list of components from the netlist that match the specified prefixes. ```APIDOC ## get_components(prefixes='*') ### Description Returns a list of components that match the list of prefixes indicated on the parameter prefixes. In case prefixes is left empty, it returns all the ones that are defined by the REPLACE_REGEXES. The list will contain the designators of all components found. ### Parameters #### Path Parameters - **prefixes** (str) - Type of prefixes to search for. Examples: ‘C’ for capacitors; ‘R’ for Resistors; etc… See prefixes in SPICE documentation for more details. The default prefix is ‘*’ which is a special case that returns all components. ### Returns - **components** (list) - A list of components matching the prefixes demanded. ``` -------------------------------- ### Histogram Help Usage Source: https://github.com/nunobrum/pyltspice/blob/master/doc/utilities/Histogram.md Call the script without arguments to display the help message and available options. ```text Usage: histogram [options] LOG_FILE TRACE ``` -------------------------------- ### run Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Executes an LTspice simulation run using a provided netlist file. This method generates .raw and .log files and allows for configuration of command-line switches, timeouts, and output handling. ```APIDOC ## classmethod run(netlist_file, cmd_line_switches=None, timeout=None, stdout=None, stderr=None, cwd=None, exe_log=False) ### Description Executes a LTspice simulation run. A raw file and a log file will be generated, with the same name as the netlist file, but with .raw and .log extension. ### Parameters #### Path Parameters * **netlist_file** (str | Path) – path to the netlist file #### Query Parameters * **cmd_line_switches** (list | None) – additional command line options. Best to have been validated by valid_switch(), defaults to None * **timeout** (float | None) – If timeout is given, and the process takes too long, a TimeoutExpired exception will be raised, defaults to None * **stdout** (_FILE, optional) – control redirection of the command’s stdout. Valid values are None, subprocess.PIPE, subprocess.DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings of None, no redirection will occur. Also see exe_log for a simpler form of control. * **stderr** (_FILE, optional) – Like stdout, but affecting the command’s error output. Also see exe_log for a simpler form of control. * **cwd** (str | Path | None) – The current working directory to run the command in. If None, no change will be done of the working directory. This may not work as wanted when using the simulator under wine. * **exe_log** (bool) – If True, stdout and stderr will be ignored, and the simulator’s execution console messages will be written to a log file (named …exe.log) instead of console. This is especially useful when running under wine or when running simultaneous tasks. ### Raises * SpiceSimulatorError – when the executable is not found. * NotImplementedError – when the requested execution is not possible on this platform. ### Returns return code from the process ### Return type int ``` -------------------------------- ### Trace Class Initialization Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/write_trace.md Initializes a Trace object representing a single trace in a raw file. This class is suitable for voltage or current traces and requires data to be provided. ```APIDOC ## Trace(name, data, whattype='voltage', numerical_type='') ### Description Helper class representing a trace. This class is based on DataSet, therefore, it doesn’t support STEPPED data. ### Parameters #### Parameters - **name** (*str*) – name of the trace being created - **whattype** (*str*) – time, frequency, voltage or current - **data** (*list* *or* *numpy.array*) – data for the data write - **numerical_type** (*str*) – real or complex ``` -------------------------------- ### Add and Remove Spice Instructions Source: https://github.com/nunobrum/pyltspice/blob/master/README.md These methods allow for the dynamic addition and removal of simulation instructions, such as .STEP or .DC, to a spice netlist. This is useful for setting up complex simulation sweeps. ```python add_instructions(".STEP run -1 1023 1", ".dc V1 -5 5") ``` ```python remove_instruction(".STEP run -1 1023 1") # Removes previously added instruction ``` -------------------------------- ### SimRunner Class Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_runner.md The SimRunner class implements methods for launching batches of LTSpice simulations. It can take either a .asc or .net file as input. ```APIDOC ## class SimRunner(*, simulator=None, parallel_sims=4, timeout=600.0, verbose=False, output_folder=None) ### Description The SimCommander class implements all the methods required for launching batches of LTSpice simulations. It takes a parameter the path to the LTSpice .asc file to be simulated, or directly the .net file. If an .asc file is given, the class will try to generate the respective .net file by calling LTspice with the –netlist option. :raises FileNotFoundError: When the file is not found /!This will be changed ### Parameters * **parallel_sims** (*int* *,* *optional*) – Defines the number of parallel simulations that can be executed at the same time. Ideally this number should be aligned to the number of CPUs (processor cores) available on the machine. * **timeout** (*float* *,* *optional*) – Timeout parameter as specified on the os subprocess.run() function. Default is 600 seconds, i.e. 10 minutes. For no timeout, set to None. * **verbose** (*bool* *,* *optional*) – If True, it enables a richer printout of the program execution. * **output_folder** (*str*) – specifying which directory shall be used for simulation files (raw and log files). * **simulator** (*str* *or* [*Simulator*](sim_simulator.md#spicelib.sim.simulator.Simulator) *,* *optional*) – Forcing a given simulator executable. ``` ```APIDOC ## create_netlist(asc_file, cmd_line_args=None) ### Description Creates a .net from an .asc using the LTSpice -netlist command line ``` -------------------------------- ### Update Parameters and Component Values in Netlist Source: https://github.com/nunobrum/pyltspice/blob/master/doc/modules/read_netlist.md Load a netlist, update global parameters and specific component values using the set_parameters and set_component_value methods, add simulation instructions, and save the modified netlist to a new file. ```python #read netlist import spicelib net = spicelib.SpiceEditor("Batch_Test.net") # Loading the Netlist net.set_parameters(res=0, cap=100e-6) # Updating parameters res and cap net.set_component_value('R2', '2k') # Updating the value of R2 to 2k net.set_component_value('R1', 4000) # Updating the value of R1 to 4k net.set_element_model('V3', "SINE(0 1 3k 0 0 0)") # changing the behaviour of V3 # add instructions net.add_instructions( "; Simulation settings", ".param run = 0" ) net.save_netlist("Batch_Test_Modified.net") # writes the modified netlist to the indicated file ``` -------------------------------- ### Command Line Usage of ltsteps Source: https://github.com/nunobrum/pyltspice/blob/master/doc/utilities/LTSteps.md Execute ltsteps from the command line, providing the path to an LTSpice file. The output format depends on the input file type (.log, .txt, or .mout). If no file is specified, the newest file is processed. ```bash $ ltsteps ``` -------------------------------- ### Histogram Options Source: https://github.com/nunobrum/pyltspice/blob/master/doc/utilities/Histogram.md Available options for the histogram command-line tool, including sigma, number of bins, filters, format, title, range, clipboard usage, and image output. ```text Options: --version show program's version number and exit -h, --help show this help message and exit -s SIGMA, --sigma=SIGMA Sigma to be used in the distribution fit. Default=3 -n NBINS, --nbins=NBINS Number of bins to be used in the histogram. Default=20 -c FILTERS, --condition=FILTERS Filter condition writen in python. More than one expression can be added but each expression should be preceded by -c. EXAMPLE: -c V(N001)>4 -c parameter==1 -c I(V1)<0.5 -f FORMAT, --format=FORMAT Format string for the X axis. Example: -f %3.4f -t TITLE, --title=TITLE Title to appear on the top of the histogram. -r RANGE, --range=RANGE Range of the X axis to use for the histogram in the form min:max. Example: -r -1:1 -C, --clipboard If the data from the clipboard is to be used. -i IMAGEFILE, --image=IMAGEFILE Name of the image File. extension 'png' ``` -------------------------------- ### get_components Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/spice_editor.md Retrieves a list of components from the netlist that match specified prefixes. If no prefixes are given, it returns all components defined by REPLACE_REGEXES. ```APIDOC ## get_components(prefixes='*') ### Description Returns a list of components that match the list of prefixes indicated on the parameter prefixes. In case prefixes is left empty, it returns all the ones that are defined by the REPLACE_REGEXES. The list will contain the designators of all components found. ### Parameters #### Query Parameters - **prefixes** (str) - Optional - Type of prefixes to search for. Examples: ‘C’ for capacitors; ‘R’ for Resistors; etc… See prefixes in SPICE documentation for more details. The default prefix is ‘*’ which is a special case that returns all components. ### Returns - list - A list of components matching the prefixes demanded. ``` -------------------------------- ### Simulator.get_default_library_paths Source: https://github.com/nunobrum/pyltspice/blob/master/doc/classes/sim_simulator.md Retrieves the default library paths for the simulator, based on its executable path and platform. ```APIDOC ## classmethod get_default_library_paths() ### Description Return the directories that contain the standard simulator’s libraries, as derived from the simulator’s executable path and platform. spice_exe must be set before calling this method. This is companion with set_custom_library_paths(). ### Returns The list of paths where the libraries should be located. ### Return type list[str] ``` -------------------------------- ### Histogram Command Line Usage Source: https://github.com/nunobrum/pyltspice/blob/master/doc/utilities/Histogram.md This is the basic command-line syntax for using the histogram module. Specify options and the data file or trace. ```text histogram [options] [data_file] TRACE ```