Код: Выделить всё
from PyLTSpice import SimRunner, SpiceEditor, LTspice
from PyLTSpice import RawRead
import os
import time
# Define the file path
chip_piece_1_path = r"C:\Users\X\Desktop\Chip\Chip_Pieces\Piece_1\Chip_Piece_1.asc"
# Function to ensure the .END statement is present in the file
def ensure_end_statement(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
# Check if the last non-empty line is .END
if not any(line.strip().upper() == ".END" for line in lines):
# Add .END if it's missing
lines.append("\n.END\n")
print("Added .END to the file.")
# Write to the same file to allow opening in LTSpice
with open(file_path, 'w') as f:
f.writelines(lines)
return True
# Function to remove the .END statement for simulation
def remove_end_statement(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
# Remove the .END statement
lines = [line for line in lines if not line.strip().upper() == ".END"]
# Write back the modified lines without .END
with open(file_path, 'w') as f:
f.writelines(lines)
print("Removed .END from the file.")
return True
# Function to ensure the top line of the .asc file is "* Chip"
def ensure_chip_line(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
# Check the first line
if not lines or lines[0].strip() != "* Chip":
# Insert "* Chip" at the top and move existing lines down
lines.insert(0, "* Chip\n")
print("Inserted '* Chip' at the top of the file.")
# Write back to the same file
with open(file_path, 'w') as f:
f.writelines(lines)
return True
# Modify the run_and_read_pd_values function to include the new check
def run_and_read_pd_values():
# Ensure the top line is "* Chip"
ensure_chip_line(chip_piece_1_path)
# Ensure the .END statement is present
ensure_end_statement(chip_piece_1_path)
# Output directory
output_folder = os.path.dirname(chip_piece_1_path)
# Clean the output folder to avoid naming conflicts
for file in os.listdir(output_folder):
if file.endswith((".raw", ".log", ".net")): # Add more extensions if needed
os.remove(os.path.join(output_folder, file))
print(f"Removed existing file: {file}")
# Create a SimRunner object and set up the output folder
runner = SimRunner(output_folder=output_folder, simulator=LTspice)
# Create a SpiceEditor instance for manipulating the netlist
netlist = SpiceEditor(chip_piece_1_path)
# Remove .END before processing
remove_end_statement(chip_piece_1_path)
# Run the simulation with exception handling
try:
print("Running Chip Piece 1 simulation...")
raw_file, log_file = runner.run_now(netlist, run_filename=chip_piece_1_path)
# Introduce a longer delay to allow file writing to complete
time.sleep(1)
# Check the log file for errors
# if log_file:
# with open(log_file, 'r') as f:
# log_contents = f.read()
# print("Log file contents:")
# print(log_contents)
except Exception as e:
print(f"An error occurred during the simulation: {e}")
** netlist = SpiceEditor("Chip_Piece_1.net") # Loading the Netlist
netlist.set_component_value('R§Input_R_1', '2k') # Updating the value of R2 to 2k
netlist.save_netlist("Batch_Test_Modified.net") # writes the modified netlist to the
indicated file**
# Check if the raw file was created successfully
if raw_file:
print(f"Raw file generated: {raw_file}")
# Check if the raw file exists before attempting to read
if os.path.exists(raw_file):
print("Raw file exists, reading the data.")
# Read the raw data to get PD values
raw_data = RawRead(raw_file)
# Define The INPUT_1 through 9 values that go to CHIP 2 as inputs
pd_traces = {
'OUTPUT_1': 'V(n013)',
'OUTPUT_2': 'V(n015)',
'OUTPUT_3': 'V(n011)',
'OUTPUT_4': 'V(n030)',
'OUTPUT_5': 'V(n028)',
'OUTPUT_6': 'V(n026)',
'OUTPUT_7': 'V(n045)',
'OUTPUT_8': 'V(n041)',
'OUTPUT_9': 'V(n043)',
}
# Print PD values with labels, formatted to 4 decimal points
print()
print("Output values:")
for pd, trace in pd_traces.items():
try:
value = raw_data.get_trace(trace).get_wave(0)[0] # Get the first value of the trace
formatted_value = f"{value:.6f}" # Format to 6 decimal places
print(f'{pd}: {formatted_value}')
except Exception as e:
print(f"Error retrieving {pd} ({trace}): {e}")
# Define the traces for the LED indicators
led_traces = {
'LED 1': 'I(Pd_1)',
'LED 2': 'I(Pd_2)',
'LED 3': 'I(Pd_3)',
'LED 4': 'I(Pd_4)',
'LED 5': 'I(Pd_5)',
'LED 6': 'I(Pd_6)',
'LED 7': 'I(Pd_7)',
'LED 8': 'I(Pd_8)',
'LED 9': 'I(Pd_9)',
}
# Print LED status based on current values
print()
print("LED Status:")
for led, trace in led_traces.items():
try:
value = raw_data.get_trace(trace).get_wave(0)[0] # Get the first value of the trace
# Determine LED status based on current value
formatted_value = f"{value:.6f}" # Format to 6 decimal places
led_status = "ON" if value > 0 else "OFF"
print(f'{led}: {led_status}')
except Exception as e:
print(f"Error retrieving {led} ({trace}): {e}")
else:
print(f"Raw file not found at expected path: {raw_file}")
else:
print("Simulation failed to generate the raw file.")
# Run the process
run_and_read_pd_values()`
Кроме того, каждый форум, который я мог найти, а также экспериментировал с множеством конфигураций, включая повторный запуск моделирования после изменений (который перезаписывает мои изменения), перенос на другое имя файла (сбой) и т. д. п>
Подробнее здесь: https://stackoverflow.com/questions/790 ... -pyltspice