Thursday, February 7, 2013

Circuit Parameters - V

Couple of updates to the previous code:

1. Some elements will also have a polarity. In this case, the voltage source definitely will have one. The capacitor could also have but I'll consider an ac capacitor for now.

2. There will have to be provision to check if everytime the program is run, whether the circuit has changed. If the circuit is the same but the parameters need to be updated, then nw_params.csv should not be filled with default values as the user will have to update everything all over again or will have to remember to copy nw_params.csv to another backup file. A more elaborate method can be thought of later where the actual topology can be read - nodes, branches, loops etc and if that remains the same along with elements in every branch, then circuit can be considered the same. Because otherwise a small change to a branch such as lengthening with more "wire" elements will be seen as a new circuit. For that matter, even if major changes are to be made, only the changed elements can be considered. All this is user interface and will come later.


So anyway, here is the updated code (click on "view raw" below the code box for code going out of the window):



#! /usr/bin/env python
import sys, math
import network_reader as nw_rd
def reading_params(param_file):
""" Read a file. Ramove additional quotes and
carriage returns. Remove leading spaces. """
from_file=[]
for line in param_file:
from_file.append(line.split(","))
for c1 in range(len(from_file)):
for c2 in range(len(from_file[c1])-1, -1, -1):
# Remove additional quotes and carriage returns
if from_file[c1][c2]:
nw_rd.scrub_elements(from_file, c1, c2)
# Remove blank spaces and null elements
if from_file[c1][c2]==" " or from_file[c1][c2]=="":
del from_file[c1][c2]
return from_file
class Resistor:
def __init__(self, res_index, res_pos, res_elem):
self.res_number=res_index
self.res_pos=res_pos
self.res_elem=res_elem
def display(self):
print "Resistor is ",
print "R"+str(self.res_number),
print "= %f" %self.resistor,
print " located at ",
print self.res_pos, self.res_elem
def ask_values(self, x_list, ckt_mat):
res_params=["Resistor"]
res_params.append("R"+str(self.res_number))
res_params.append(self.res_pos)
res_params.append(100.0)
x_list.append(res_params)
def get_values(self, x_list, ckt_mat):
self.resistor=float(x_list[0])
class Inductor:
def __init__(self, ind_index, ind_pos, ind_elem):
self.ind_number=ind_index
self.ind_pos=ind_pos
self.ind_elem=ind_elem
def display(self):
print "Inductor is ",
print "L"+str(self.ind_number),
print "=%f" %self.inductor,
print " located at ",
print self.ind_pos, self.ind_elem
def ask_values(self, x_list, ckt_mat):
ind_params=["Inductor"]
ind_params.append("L"+str(self.ind_number))
ind_params.append(self.ind_pos)
ind_params.append(0.001)
x_list.append(ind_params)
def get_values(self, x_list, ckt_mat):
self.inductor=float(x_list[0])
class Capacitor:
def __init__(self, cap_index, cap_pos, cap_elem):
self.cap_number=cap_index
self.cap_pos=cap_pos
self.cap_elem=cap_elem
def display(self):
print "Capacitor is ",
print "C"+str(self.cap_number),
print "= %f" %self.capacitor,
print " located at ",
print self.cap_pos, self.cap_elem
def ask_values(self, x_list, ckt_mat):
cap_params=["Capacitor"]
cap_params.append("C"+str(self.cap_number))
cap_params.append(self.cap_pos)
cap_params.append(10.0e-6)
x_list.append(cap_params)
def get_values(self, x_list, ckt_mat):
self.capacitor=float(x_list[0])
class Voltage_Source:
def __init__(self, volt_index, volt_pos, volt_elem):
self.volt_number=volt_index
self.volt_pos=volt_pos
self.volt_elem=volt_elem
def display(self):
print "Voltage Source is ",
print "V"+str(self.volt_number),
print "of %f V(peak), %f Hz(frequency) and %f (degrees phase shift)" %(self.v_peak, self.v_freq, self.v_phase),
print " located at ",
print self.volt_pos, self.volt_elem,
print " with positive polarity towards %s %s" %(nw_rd.csv_element(self.v_polrty), self.v_polrty)
def ask_values(self, x_list, ckt_mat):
volt_params=["Voltage_Source"]
volt_params.append("V"+str(self.volt_number))
volt_params.append(self.volt_pos)
volt_params.append("Peak (Volts) = 120.0")
volt_params.append("Frequency (Hertz) = 60")
volt_params.append("Phase (degrees) = 0")
# Looking for a default value of polarity
# in the neighbouring cells
if self.volt_elem[0]>0:
if ckt_mat[self.volt_elem[0]-1][self.volt_elem[1]]:
self.v_polrty=[self.volt_elem[0]-1, self.volt_elem[1]]
elif self.volt_elem[1]>0:
if ckt_mat[self.volt_elem[0]][self.volt_elem[1]-1]:
self.v_polrty=[self.volt_elem[0], self.volt_elem[1]-1]
elif self.volt_elem[0]<len(ckt_mat)-1:
if ckt_mat[self.volt_elem[0]+1][self.volt_elem[1]]:
self.v_polrty=[self.volt_elem[0]+1, self.volt_elem[1]]
elif self.volt_elem[1]<len(ckt_mat)-1:
if ckt_mat[self.volt_elem[0]][self.volt_elem[1]+1]:
self.v_polrty=[self.volt_elem[0], self.volt_elem[1]+1]
volt_params.append("Positive polarity towards (cell) = %s" %nw_rd.csv_element(self.v_polrty))
x_list.append(volt_params)
def get_values(self, x_list, ckt_mat):
self.v_peak=float(x_list[0].split("=")[1])
self.v_freq=float(x_list[1].split("=")[1])
self.v_phase=float(x_list[2].split("=")[1])
volt_polrty=x_list[3].split("=")[1]
# Convert the human readable form of cell
# to [row, column] form
while volt_polrty[0]==" ":
volt_polrty=volt_polrty[1:]
volt_polrty.upper()
# Create a dictionary of alphabets
csv_col="A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
csv_dict={}
csv_col_list=csv_col.split(" ")
# Make the alphabets correspond to integers
for c1 in range(1, 27):
csv_dict[csv_col_list[c1-1]]=c1
# The cell position starts with a number
flag="number"
c1=0
while flag=="number":
# When conversion to int fails
# it means the element is an alphabet
try:
int(volt_polrty[c1])
except ValueError:
flag="alphabet"
else:
c1+=1
# Split them up into numbers and alphabets
pol_row=int(volt_polrty[0:c1])
pol_col=volt_polrty[c1:]
self.v_polrty=[pol_row-1, 0]
# Convert the alphabets to number
# Similar to converting binary to decimal
for c1 in range(len(pol_col)-1, -1, -1):
if len(pol_col)-1-c1>0:
self.v_polrty[1]+=26*(len(pol_col)-1-c1)*csv_dict[pol_col[c1]]
else:
self.v_polrty[1]+=csv_dict[pol_col[c1]]-1
if not ckt_mat[self.v_polrty[0]][self.v_polrty[1]]:
print "Polarity incorrect. Branch does not exist at %s" %nw_rd.csv_element(self.v_polrty)
component_list={"Resistor":Resistor, "Inductor":Inductor, "Capacitor":Capacitor, "Voltage_Source":Voltage_Source}
test_ckt=open("testckt1.csv","r")
# Read the circuit into tst_mat
# Also performs a scrubbing of tst_mat
tst_mat=nw_rd.csv_reader(test_ckt)
components_found={}
for c1 in range(len(tst_mat)):
for c2 in range(len(tst_mat[0])):
elem=tst_mat[c1][c2]
if elem:
# wire is a zero resistance connection
if elem.lower()!="wire":
# Check if component exists
if elem in component_list.keys():
# If found for the first time
# Create that dictionary element with key
# as component type
if elem not in components_found:
components_found[elem]=[[nw_rd.csv_element([c1, c2]), [c1, c2]]]
else:
# If already found, append it to
# dictionary item with that key.
components_found[elem].append([nw_rd.csv_element([c1, c2]), [c1, c2]])
else:
print "Error! Component at %s doesn't exist." %nw_rd.csv_element([c1, c2])
component_objects={}
for items in components_found.keys():
# Take every type of component found
# item -> resistor, inductor etc
for c1 in range(len(components_found[items])):
# Each component type will be occurring
# multiple times. Iterate through every find.
# The list corresponding to each component is
# the unique cell position in the spreadsheet
component_objects[components_found[items][c1][0]] = \
component_list[items](c1+1, components_found[items][c1][0], components_found[items][c1][1])
# Check if the nw_params.csv file exists.
try:
csv_check_values=open("nw_params.csv","r")
# If not, it has to be created and filled
# with default values.
except:
param_flag="no"
# If it exists, check if the circuit
# is the same and only parameters need to change
else:
params_from_file=reading_params(csv_check_values)
# A single change in the circuit topology
# will mean a new circuit.
same_ckt="yes"
for c1 in range(len(params_from_file)):
# Remove leading spaces if any
# The first column is the type of element
if params_from_file[c1][0][0]==" ":
params_from_file[c1][0]=params_from_file[c1][0][1:]
# Check if the type of element is
# in the same cell position as before
# Here a single occurance of the type of element
# in components_found and in the same position
# means it is the same.
element_same="no"
for c2 in range(len(components_found[params_from_file[c1][0]])):
if params_from_file[c1][2][0]==" ":
params_from_file[c1][2]=params_from_file[c1][2][1:]
if params_from_file[c1][2]==components_found[params_from_file[c1][0]][c2][0]:
element_same="yes"
# If a single element has changed,
# the circuit is new
if element_same=="no":
same_ckt="no"
csv_check_values.close()
# If the circuit is the same, the parameters
# can remain as they are
if same_ckt=="yes":
param_flag="yes"
# If not, default parameters need to be entered
# for a new circuit.
else:
param_flag="no"
# Enter default values into nw_params.csv
# or create it if its a new cicuit
if param_flag=="no":
values_to_file=[]
for items in component_objects.keys():
# Each component object has a method
# ask_values that prints in the csv file
# default values for parameters.
component_objects[items].ask_values(values_to_file, tst_mat)
csv_ask_values=open("nw_params.csv","w")
for c1 in range(len(values_to_file)):
for c2 in range(len(values_to_file[c1])):
csv_ask_values.write("%s" %values_to_file[c1][c2])
csv_ask_values.write(", ")
csv_ask_values.write("\n")
csv_ask_values.close()
# Wait for the user to enter parameters before
# reading the nw_params.csv file.
cont_ans="n"
while cont_ans.lower()!="y":
cont_ans=raw_input("Enter parameters in file nw_params.csv. When ready press y and enter to continue -> ")
csv_get_values=open("nw_params.csv","r")
params_from_file=reading_params(csv_get_values)
csv_get_values.close()
for c1 in range(len(params_from_file)):
# Getting rid of the beginning spaces
# in the component keys
if params_from_file[c1][2][0]==" ":
params_from_file[c1][2]=params_from_file[c1][2][1:]
component_objects[params_from_file[c1][2]].get_values(params_from_file[c1][3:], tst_mat)
# Just checking the objects
for items in component_objects.keys():
component_objects[items].display()
view raw csv_element2.py hosted with ❤ by GitHub

No comments:

Post a Comment