diff options
Diffstat (limited to 'src')
36 files changed, 4867 insertions, 3307 deletions
diff --git a/src/browser/UserManual.py b/src/browser/UserManual.py index bcff4f97..3bcfbace 100644 --- a/src/browser/UserManual.py +++ b/src/browser/UserManual.py @@ -1,17 +1,20 @@ from PyQt4 import QtGui import webbrowser + class UserManual(QtGui.QWidget): """ This class creates Welcome page of eSim. """ + def __init__(self): QtGui.QWidget.__init__(self) - + self.vlayout = QtGui.QVBoxLayout() - + self.url = "../browser/pages/User-Manual/eSim.html" - self.test = webbrowser.open("../browser/pages/User-Manual/eSim.html",new=2) - + self.test = webbrowser.open( + "../browser/pages/User-Manual/eSim.html", new=2) + self.setLayout(self.vlayout) - self.show()
\ No newline at end of file + self.show() diff --git a/src/browser/Welcome.py b/src/browser/Welcome.py index 0f50e153..52e7d5bd 100644 --- a/src/browser/Welcome.py +++ b/src/browser/Welcome.py @@ -1,19 +1,21 @@ -from PyQt4 import QtGui,QtCore +from PyQt4 import QtGui, QtCore class Welcome(QtGui.QWidget): """ This class creates Welcome page of eSim. """ + def __init__(self): + """Sdf.""" QtGui.QWidget.__init__(self) self.vlayout = QtGui.QVBoxLayout() - + self.browser = QtGui.QTextBrowser() self.browser.setSource(QtCore.QUrl("../browser/pages/welcome.html")) self.browser.setOpenExternalLinks(True) - self.browser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) - - self.vlayout.addWidget(self.browser) + self.browser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) + + self.vlayout.addWidget(self.browser) self.setLayout(self.vlayout) self.show() diff --git a/src/browser/Welcome.py.bak b/src/browser/Welcome.py.bak new file mode 100644 index 00000000..5c0195e2 --- /dev/null +++ b/src/browser/Welcome.py.bak @@ -0,0 +1,20 @@ +from PyQt4 import QtGui, QtCore + + +class Welcome(QtGui.QWidget): + """ + This class creates Welcome page of eSim. + """ + + def __init__(self): + QtGui.QWidget.__init__(self) + self.vlayout = QtGui.QVBoxLayout() + + self.browser = QtGui.QTextBrowser() + self.browser.setSource(QtCore.QUrl("../browser/pages/welcome.html")) + self.browser.setOpenExternalLinks(True) + self.browser.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) + + self.vlayout.addWidget(self.browser) + self.setLayout(self.vlayout) + self.show() diff --git a/src/configuration/Appconfig.py b/src/configuration/Appconfig.py index d9479137..40bb8ef6 100644 --- a/src/configuration/Appconfig.py +++ b/src/configuration/Appconfig.py @@ -1,85 +1,85 @@ -#=============================================================================== +# ========================================================================= # # FILE: Appconfig.py -# -# USAGE: --- -# -# DESCRIPTION: This define all configuration used in Application. -# +# +# USAGE: --- +# +# DESCRIPTION: This define all configuration used in Application. +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 04 February 2015 +# CREATED: Wednesday 04 February 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= from PyQt4 import QtGui import os import json -from ConfigParser import SafeConfigParser +from configparser import SafeConfigParser class Appconfig(QtGui.QWidget): - """ - All configuration goes here. - May change in future for code optimization. - """ - - #Home directory - home = os.path.join(os.path.expanduser("~"),"eSim-Workspace") - default_workspace = {"workspace":home} - #Current Project detail - current_project = {"ProjectName":None} - #Current Subcircuit detail - current_subcircuit = {"SubcircuitName":None} - #Workspace detail - workspace_text = '''eSim stores your project in a folder called a eSim-Workspace. You can choose a different workspace folder to use for this session.''' - procThread_list = [] - proc_dict={} #holds the pids of all external windows corresponds to the current project - dock_dict={} #holds all dockwidgets - dictPath = os.path.join(os.path.expanduser("~"), ".projectExplorer.txt") - noteArea = {} + """ + All configuration goes here. + May change in future for code optimization. + """ + + # Home directory + home = os.path.join(os.path.expanduser("~"), "eSim-Workspace") + default_workspace = {"workspace": home} + # Current Project detail + current_project = {"ProjectName": None} + # Current Subcircuit detail + current_subcircuit = {"SubcircuitName": None} + # Workspace detail + workspace_text = '''eSim stores your project in a folder called a \ + eSim-Workspace. You can choose a different workspace folder to use\ + for this session.''' + procThread_list = [] + proc_dict = {} + # holds the pids of all external windows corresponds to the current project + dock_dict = {} # holds all dockwidgets + dictPath = os.path.join(os.path.expanduser("~"), ".projectExplorer.txt") + noteArea = {} + + parser_esim = SafeConfigParser() + parser_esim.read( + os.path.join( + os.path.expanduser("~"), + os.path.join( + '.esim', + 'config.ini'))) + # Need to comment below line to execute on Windows 10 + # modelica_map_json = parser_esim.get('eSim', 'MODELICA_MAP_JSON') + try: + project_explorer = json.load(open(dictPath)) + except BaseException: + project_explorer = {} + process_obj = [] + + def __init__(self): + super(Appconfig, self).__init__() + # Application Details + self._APPLICATION = 'eSim' + self._VERSION = 'v1.1' + self._AUTHOR = 'Fahim' + + # Application geometry setting + self._app_xpos = 100 + self._app_ypos = 100 + self._app_width = 600 + self._app_heigth = 400 + + def print_info(self, info): + self.noteArea['Note'].append('[INFO]: ' + info) + + def print_warning(self, warning): + self.noteArea['Note'].append('[WARNING]: ' + warning) - parser_esim = SafeConfigParser() - parser_esim.read(os.path.join(os.path.expanduser("~"), os.path.join('.esim','config.ini'))) - modelica_map_json = parser_esim.get('eSim', 'MODELICA_MAP_JSON') - try: - project_explorer = json.load(open(dictPath)) - except: - project_explorer= {} - process_obj = [] - - def __init__(self): - super(Appconfig, self).__init__() - #Application Details - self._APPLICATION = 'eSim' - self._VERSION = 'v1.1' - self._AUTHOR = 'Fahim' - - #Application geometry setting - self._app_xpos = 100 - self._app_ypos = 100 - self._app_width = 600 - self._app_heigth = 400 - - - def print_info(self, info): - self.noteArea['Note'].append('[INFO]: ' + info) - - - def print_warning(self, warning): - self.noteArea['Note'].append('[WARNING]: ' + warning) - - - def print_error(self, error): - self.noteArea['Note'].append('[ERROR]: ' + error) - - - - - - + def print_error(self, error): + self.noteArea['Note'].append('[ERROR]: ' + error) diff --git a/src/configuration/browser/UserManual.py b/src/configuration/browser/UserManual.py new file mode 100644 index 00000000..3bcfbace --- /dev/null +++ b/src/configuration/browser/UserManual.py @@ -0,0 +1,20 @@ +from PyQt4 import QtGui +import webbrowser + + +class UserManual(QtGui.QWidget): + """ + This class creates Welcome page of eSim. + """ + + def __init__(self): + QtGui.QWidget.__init__(self) + + self.vlayout = QtGui.QVBoxLayout() + + self.url = "../browser/pages/User-Manual/eSim.html" + self.test = webbrowser.open( + "../browser/pages/User-Manual/eSim.html", new=2) + + self.setLayout(self.vlayout) + self.show() diff --git a/src/frontEnd/Application.py b/src/frontEnd/Application.py index 2f9bca28..19fe17ef 100755 --- a/src/frontEnd/Application.py +++ b/src/frontEnd/Application.py @@ -1,28 +1,21 @@ - -#=============================================================================== +# ========================================================================= # # FILE: Application.py -# -# USAGE: --- -# +# +# USAGE: --- +# # DESCRIPTION: This main file use to start the Application -# +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 21 January 2015 +# CREATED: Wednesday 21 January 2015 # REVISION: --- -#=============================================================================== -import os -import sys -#Setting PYTHONPATH -cwd = os.getcwd() -(setPath,fronEnd) = os.path.split(cwd) -sys.path.append(setPath) - +# ========================================================================= +import pathmagic # noqa from PyQt4 import QtGui, QtCore from configuration.Appconfig import Appconfig from projManagement.openProject import OpenProjectInfo @@ -35,108 +28,151 @@ from frontEnd import Workspace from frontEnd import DockArea import time from PyQt4.Qt import QSize +import sys +import os class Application(QtGui.QMainWindow): - global project_name + global project_name """ Its our main window of application """ - def __init__(self,*args): + + def __init__(self, *args): """ Initialize main Application window """ - #Calling __init__ of super class - QtGui.QMainWindow.__init__(self,*args) - - #Creating require Object + # Calling __init__ of super class + QtGui.QMainWindow.__init__(self, *args) + + # Creating require Object self.obj_workspace = Workspace.Workspace() self.obj_Mainview = MainView() self.obj_kicad = Kicad(self.obj_Mainview.obj_dockarea) - self.obj_appconfig = Appconfig() + self.obj_appconfig = Appconfig() self.obj_validation = Validation() - #Initialize all widget + # Initialize all widget self.setCentralWidget(self.obj_Mainview) self.initToolBar() - + self.setGeometry(self.obj_appconfig._app_xpos, self.obj_appconfig._app_ypos, self.obj_appconfig._app_width, self.obj_appconfig._app_heigth) - self.setWindowTitle(self.obj_appconfig._APPLICATION) + self.setWindowTitle(self.obj_appconfig._APPLICATION) self.showMaximized() self.setWindowIcon(QtGui.QIcon('../../images/logo.png')) - #self.show() + # self.show() self.systemTrayIcon = QtGui.QSystemTrayIcon(self) self.systemTrayIcon.setIcon(QtGui.QIcon('../../images/logo.png')) self.systemTrayIcon.setVisible(True) - - + def initToolBar(self): """ This function initialize Tool Bar """ - #Top Tool bar - self.newproj = QtGui.QAction(QtGui.QIcon('../../images/newProject.png'),'<b>New Project</b>',self) + # Top Tool bar + self.newproj = QtGui.QAction( + QtGui.QIcon('../../images/newProject.png'), + '<b>New Project</b>', + self) self.newproj.setShortcut('Ctrl+N') self.newproj.triggered.connect(self.new_project) - #self.newproj.connect(self.newproj,QtCore.SIGNAL('triggered()'),self,QtCore.SLOT(self.new_project())) - - self.openproj = QtGui.QAction(QtGui.QIcon('../../images/openProject.png'),'<b>Open Project</b>',self) + # self.newproj.connect(self.newproj,QtCore.SIGNAL('triggered()'),self,QtCore.SLOT(self.new_project())) + + self.openproj = QtGui.QAction( + QtGui.QIcon('../../images/openProject.png'), + '<b>Open Project</b>', + self) self.openproj.setShortcut('Ctrl+O') self.openproj.triggered.connect(self.open_project) - - self.closeproj = QtGui.QAction(QtGui.QIcon('../../images/closeProject.png'),'<b>Close Project</b>',self) + + self.closeproj = QtGui.QAction( + QtGui.QIcon('../../images/closeProject.png'), + '<b>Close Project</b>', + self) self.closeproj.setShortcut('Ctrl+X') self.closeproj.triggered.connect(self.close_project) - - self.helpfile = QtGui.QAction(QtGui.QIcon('../../images/helpProject.png'),'<b>Help</b>',self) + + self.helpfile = QtGui.QAction( + QtGui.QIcon('../../images/helpProject.png'), '<b>Help</b>', self) self.helpfile.setShortcut('Ctrl+H') self.helpfile.triggered.connect(self.help_project) - + self.topToolbar = self.addToolBar('Top Tool Bar') self.topToolbar.addAction(self.newproj) self.topToolbar.addAction(self.openproj) - + self.topToolbar.addAction(self.closeproj) self.topToolbar.addAction(self.helpfile) - + self.spacer = QtGui.QWidget() - self.spacer.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding) + self.spacer.setSizePolicy( + QtGui.QSizePolicy.Expanding, + QtGui.QSizePolicy.Expanding) self.topToolbar.addWidget(self.spacer) self.logo = QtGui.QLabel() - self.logopic = QtGui.QPixmap(os.path.join(os.path.abspath('../..'),'images','fosseeLogo.png')) - self.logopic = self.logopic.scaled(QSize(150,150),QtCore.Qt.KeepAspectRatio) + self.logopic = QtGui.QPixmap( + os.path.join( + os.path.abspath('../..'), + 'images', + 'fosseeLogo.png')) + self.logopic = self.logopic.scaled( + QSize(150, 150), QtCore.Qt.KeepAspectRatio) self.logo.setPixmap(self.logopic) self.logo.setStyleSheet("padding:0 15px 0 0;") self.topToolbar.addWidget(self.logo) - - #Left Tool bar Action Widget - self.kicad = QtGui.QAction(QtGui.QIcon('../../images/kicad.png'),'<b>Open Schematic</b>',self) + + # Left Tool bar Action Widget + self.kicad = QtGui.QAction( + QtGui.QIcon('../../images/kicad.png'), + '<b>Open Schematic</b>', + self) self.kicad.triggered.connect(self.obj_kicad.openSchematic) - - self.conversion = QtGui.QAction(QtGui.QIcon('../../images/ki-ng.png'),'<b>Convert Kicad to Ngspice</b>',self) + + self.conversion = QtGui.QAction( + QtGui.QIcon('../../images/ki-ng.png'), + '<b>Convert Kicad to Ngspice</b>', + self) self.conversion.triggered.connect(self.obj_kicad.openKicadToNgspice) - - self.ngspice = QtGui.QAction(QtGui.QIcon('../../images/ngspice.png'), '<b>Simulation</b>', self) + + self.ngspice = QtGui.QAction( + QtGui.QIcon('../../images/ngspice.png'), + '<b>Simulation</b>', + self) self.ngspice.triggered.connect(self.open_ngspice) - - self.model = QtGui.QAction(QtGui.QIcon('../../images/model.png'),'<b>Model Editor</b>',self) - self.model.triggered.connect(self.open_modelEditor) - - self.subcircuit=QtGui.QAction(QtGui.QIcon('../../images/subckt.png'),'<b>Subcircuit</b>',self) + + self.model = QtGui.QAction( + QtGui.QIcon('../../images/model.png'), + '<b>Model Editor</b>', + self) + self.model.triggered.connect(self.open_modelEditor) + + self.subcircuit = QtGui.QAction( + QtGui.QIcon('../../images/subckt.png'), + '<b>Subcircuit</b>', + self) self.subcircuit.triggered.connect(self.open_subcircuit) - self.nghdl = QtGui.QAction(QtGui.QIcon('../../images/nghdl.png'), '<b>Nghdl</b>', self) + self.nghdl = QtGui.QAction( + QtGui.QIcon('../../images/nghdl.png'), + '<b>Nghdl</b>', + self) self.nghdl.triggered.connect(self.open_nghdl) - - self.omedit = QtGui.QAction(QtGui.QIcon('../../images/omedit.png'),'<b>Modelica Converter</b>',self) - self.omedit.triggered.connect(self.open_OMedit) - - self.omoptim=QtGui.QAction(QtGui.QIcon('../../images/omoptim.png'),'<b>OM Optimisation</b>',self) + + self.omedit = QtGui.QAction( + QtGui.QIcon('../../images/omedit.png'), + '<b>Modelica Converter</b>', + self) + self.omedit.triggered.connect(self.open_OMedit) + + self.omoptim = QtGui.QAction( + QtGui.QIcon('../../images/omoptim.png'), + '<b>OM Optimisation</b>', + self) self.omoptim.triggered.connect(self.open_OMoptim) - - #Adding Action Widget to tool bar + + # Adding Action Widget to tool bar self.lefttoolbar = QtGui.QToolBar('Left ToolBar') self.addToolBar(QtCore.Qt.LeftToolBarArea, self.lefttoolbar) self.lefttoolbar.addAction(self.kicad) @@ -148,131 +184,140 @@ class Application(QtGui.QMainWindow): self.lefttoolbar.addAction(self.omedit) self.lefttoolbar.addAction(self.omoptim) self.lefttoolbar.setOrientation(QtCore.Qt.Vertical) - self.lefttoolbar.setIconSize(QSize(40,40)) - + self.lefttoolbar.setIconSize(QSize(40, 40)) + def closeEvent(self, event): - exit_msg = "Are you sure you want to exit the program ? All unsaved data will be lost." - reply = QtGui.QMessageBox.question(self, 'Message', - exit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) - - if reply == QtGui.QMessageBox.Yes: + exit_msg = "Are you sure you want to exit the program\ + ? All unsaved data will be lost." + reply = QtGui.QMessageBox.question( + self, 'Message', exit_msg, QtGui.QMessageBox.Yes, + QtGui.QMessageBox.No) + + if reply == QtGui.QMessageBox.Yes: for proc in self.obj_appconfig.procThread_list: - try: - proc.terminate() - except: - pass - try: + try: + proc.terminate() + except BaseException: + pass + try: for process_object in self.obj_appconfig.process_obj: try: process_object.close() - except: - pass - except: + except BaseException: + pass + except BaseException: pass - ##Just checking if open project and New project window is open. If yes just close it when application is closed + # Just checking if open project and New project window is open. If + # yes just close it when application is closed try: self.project.close() - except: + except BaseException: pass event.accept() self.systemTrayIcon.showMessage('Exit', 'eSim is Closed.') - + elif reply == QtGui.QMessageBox.No: event.ignore() - - + def close_project(self): - print "Function : Close Project" + print("Function : Close Project") current_project = self.obj_appconfig.current_project['ProjectName'] - if current_project==None: + if current_project is None: pass else: - for pid in self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']]: + temp = self.obj_appconfig.current_project['ProjectName'] + for pid in self.obj_appconfig.proc_dict[temp]: try: os.kill(pid, 9) - except: + except BaseException: pass self.obj_Mainview.obj_dockarea.closeDock() self.obj_appconfig.current_project['ProjectName'] = None - self.systemTrayIcon.showMessage('Close', 'Current project '+os.path.basename(current_project)+' is Closed.') - + self.systemTrayIcon.showMessage( + 'Close', + 'Current project ' + + os.path.basename(current_project) + + ' is Closed.') + def new_project(self): """ This function call New Project Info class. """ - text, ok = QtGui.QInputDialog.getText(self, 'New Project Info','Enter Project Name:') + text, ok = QtGui.QInputDialog.getText( + self, 'New Project Info', 'Enter Project Name:') if ok: self.projname = (str(text)) self.project = NewProjectInfo() - directory, filelist =self.project.createProject(self.projname) - - self.obj_Mainview.obj_projectExplorer.addTreeNode(directory, filelist) - + directory, filelist = self.project.createProject(self.projname) + + self.obj_Mainview.obj_projectExplorer.addTreeNode( + directory, filelist) + else: - print "No new project created" + print("No new project created") self.obj_appconfig.print_info('No new project created') try: - self.obj_appconfig.print_info('Current project is : ' + self.obj_appconfig.current_project["ProjectName"]) - except: + self.obj_appconfig.print_info( + 'Current project is : ' + + self.obj_appconfig.current_project["ProjectName"]) + except BaseException: pass - + def open_project(self): """ This project call Open Project Info class """ - print "Function : Open Project" + print("Function : Open Project") self.project = OpenProjectInfo() - + try: directory, filelist = self.project.body() - self.obj_Mainview.obj_projectExplorer.addTreeNode(directory, filelist) - except: + self.obj_Mainview.obj_projectExplorer.addTreeNode( + directory, filelist) + except BaseException: pass - - - - + def help_project(self): - print "Function : Help" + print("Function : Help") self.obj_appconfig.print_info('Help is called') - print "Current Project is : ",self.obj_appconfig.current_project - self.obj_Mainview.obj_dockarea.usermanual() - - + print("Current Project is : ", self.obj_appconfig.current_project) + self.obj_Mainview.obj_dockarea.usermanual() + def open_ngspice(self): """ This Function execute ngspice on current project """ - + self.projDir = self.obj_appconfig.current_project["ProjectName"] - - if self.projDir != None: + + if self.projDir is not None: self.obj_Mainview.obj_dockarea.ngspiceEditor(self.projDir) - time.sleep(2) #Need permanent solution - #Calling Python Plotting - + time.sleep(2) # Need permanent solution + # Calling Python Plotting + try: self.obj_Mainview.obj_dockarea.plottingEditor() except Exception as e: self.msg = QtGui.QErrorMessage(None) self.msg.showMessage('Error while opening python plotting Editor.\ Please look at console for more details ') - print "Exception Message:",str(e) + print("Exception Message:", str(e)) self.obj_appconfig.print_error('Exception Message : ' + str(e)) self.msg.setWindowTitle("Error Message") - + else: self.msg = QtGui.QErrorMessage() - self.msg.showMessage('Please select the project first. You can either create new project or open existing project') + self.msg.showMessage('Please select the project first. You can either\ + create new project or open existing project') self.msg.setWindowTitle("Error Message") - + def open_subcircuit(self): - print "Function : Subcircuit editor" + print("Function : Subcircuit editor") self.obj_appconfig.print_info('Subcircuit editor is called') self.obj_Mainview.obj_dockarea.subcircuiteditor() def open_nghdl(self): - print "Function : Nghdl" + print("Function : Nghdl") self.obj_appconfig.print_info('Nghdl is called') if self.obj_validation.validateTool('nghdl'): @@ -282,80 +327,100 @@ class Application(QtGui.QMainWindow): else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('Error while opening nghdl. Please make sure nghdl is installed') - self.obj_appconfig.print_error('Error while opening nghdl. Please make sure nghdl is installed') + self.msg.showMessage('Error while opening nghdl.\ + Please make sure nghdl is installed') + self.obj_appconfig.print_error('Error while opening nghdl.\ + Please make sure nghdl is installed') self.msg.setWindowTitle('nghdl Error Message') - - + def open_modelEditor(self): - print "Function : Model editor" + print("Function : Model editor") self.obj_appconfig.print_info('Model editor is called') self.obj_Mainview.obj_dockarea.modelEditor() - def open_OMedit(self): """ - This function call ngspice to OM edit converter and then launch OM edit. + This function call ngspice to OM edit converter + and then launch OM edit. """ self.obj_appconfig.print_info('OM edit is called') self.projDir = self.obj_appconfig.current_project["ProjectName"] - - if self.projDir != None: + + if self.projDir is not None: if self.obj_validation.validateCirOut(self.projDir): self.projName = os.path.basename(self.projDir) - self.ngspiceNetlist = os.path.join(self.projDir,self.projName+".cir.out") - self.modelicaNetlist = os.path.join(self.projDir,self.projName+".mo") - + self.ngspiceNetlist = os.path.join( + self.projDir, self.projName + ".cir.out") + self.modelicaNetlist = os.path.join( + self.projDir, self.projName + ".mo") + """ try: - #Creating a command for Ngspice to Modelica converter - self.cmd1 = "python ../ngspicetoModelica/NgspicetoModelica.py "+self.ngspiceNetlist + # Creating a command for Ngspice to Modelica converter + self.cmd1 = " + python ../ngspicetoModelica/NgspicetoModelica.py "\ + +self.ngspiceNetlist self.obj_workThread1 = Worker.WorkerThread(self.cmd1) self.obj_workThread1.start() - - + + if self.obj_validation.validateTool("OMEdit"): - #Creating command to run OMEdit + # Creating command to run OMEdit self.cmd2 = "OMEdit "+self.modelicaNetlist self.obj_workThread2 = Worker.WorkerThread(self.cmd2) self.obj_workThread2.start() else: self.msg = QtGui.QMessageBox() - self.msgContent = "There was an error while opening OMEdit.<br/>\ - Please make sure OpenModelica is installed in your system. <br/>\ - To install it on Linux : Go to <a href=https://www.openmodelica.org/download/download-linux>OpenModelica Linux</a> and install nigthly build release.<br/>\ - To install it on Windows : Go to <a href=https://www.openmodelica.org/download/download-windows>OpenModelica Windows</a> and install latest version.<br/>" + self.msgContent = "There was an error while + opening OMEdit.<br/>\ + Please make sure OpenModelica is installed in your\ + system. <br/>\ + To install it on Linux : Go to\ + <a href=https://www.openmodelica.org/download/\ + download-linux>OpenModelica Linux</a> and \ + install nigthly build release.<br/>\ + To install it on Windows : Go to\ + <a href=https://www.openmodelica.org/download/\ + download-windows>OpenModelica Windows</a>\ + and install latest version.<br/>" self.msg.setTextFormat(QtCore.Qt.RichText) self.msg.setText(self.msgContent) self.msg.setWindowTitle("Missing OpenModelica") self.obj_appconfig.print_info(self.msgContent) self.msg.exec_() - + except Exception as e: self.msg = QtGui.QErrorMessage() - self.msg.showMessage('Unable to convert NgSpice netlist to Modelica netlist :'+str(e)) - self.msg.setWindowTitle("Ngspice to Modelica conversion error") + self.msg.showMessage( + 'Unable to convert NgSpice netlist to\ + Modelica netlist :'+str(e)) + self.msg.setWindowTitle( + "Ngspice to Modelica conversion error") self.obj_appconfig.print_error(str(e)) """ self.obj_Mainview.obj_dockarea.modelicaEditor(self.projDir) - + else: self.msg = QtGui.QErrorMessage() - self.msg.showMessage('Current project does not contain any ngspice file. Please create ngspice file with extension .cir.out') + self.msg.showMessage( + 'Current project does not contain any ngspice file.\ + Please create ngspice file with extension .cir.out') self.msg.setWindowTitle("Missing Ngspice netlist") else: self.msg = QtGui.QErrorMessage() - self.msg.showMessage('Please select the project first. You can either create new project or open existing project') + self.msg.showMessage( + 'Please select the project first.\ + You can either create new project\ + or open existing project') self.msg.setWindowTitle("Error Message") - - + def open_OMoptim(self): - print "Function : OM Optim" + print("Function : OM Optim") self.obj_appconfig.print_info('OM Optim is called') - #Check if OMOptim is installed + # Check if OMOptim is installed if self.obj_validation.validateTool("OMOptim"): - #Creating a command to run + # Creating a command to run self.cmd = "OMOptim" self.obj_workThread = Worker.WorkerThread(self.cmd) self.obj_workThread.start() @@ -363,93 +428,97 @@ class Application(QtGui.QMainWindow): self.msg = QtGui.QMessageBox() self.msgContent = "There was an error while opening OMOptim.<br/>\ Please make sure OpenModelica is installed in your system. <br/>\ - To install it on Linux : Go to <a href=https://www.openmodelica.org/download/download-linux>OpenModelica Linux</a> and install nigthly build release.<br/>\ - To install it on Windows : Go to <a href=https://www.openmodelica.org/download/download-windows>OpenModelica Windows</a> and install latest version.<br/>" + To install it on Linux : Go to <a href=https://www.openmodelica\ + .org/download/download-linux>OpenModelica Linux</a> and \ + install nigthly build release.<br/>\ + To install it on Windows : Go to <a href=https://www.openmodelica.\ + org/download/download-windows>OpenModelica Windows</a> and \ + install latest version.<br/>" self.msg.setTextFormat(QtCore.Qt.RichText) self.msg.setText(self.msgContent) self.msg.setWindowTitle("Error Message") self.obj_appconfig.print_info(self.msgContent) self.msg.exec_() + class MainView(QtGui.QWidget): """ This class initialize the Main View of Application """ + def __init__(self, *args): # call init method of superclass QtGui.QWidget.__init__(self, *args) - + self.obj_appconfig = Appconfig() - + self.leftSplit = QtGui.QSplitter() self.middleSplit = QtGui.QSplitter() - + self.mainLayout = QtGui.QVBoxLayout() - #Intermediate Widget + # Intermediate Widget self.middleContainer = QtGui.QWidget() self.middleContainerLayout = QtGui.QVBoxLayout() - - #Area to be included in MainView + + # Area to be included in MainView self.noteArea = QtGui.QTextEdit() self.noteArea.setReadOnly(True) self.obj_appconfig.noteArea['Note'] = self.noteArea - self.obj_appconfig.noteArea['Note'].append(' eSim Started......') + self.obj_appconfig.noteArea['Note'].append( + ' eSim Started......') self.obj_appconfig.noteArea['Note'].append('Project Selected : None') self.obj_appconfig.noteArea['Note'].append('\n') - - #CSS + # CSS self.noteArea.setStyleSheet(" \ - QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; } \ + QWidget { border-radius: 15px; border: 1px \ + solid gray; padding: 5px; } \ ") - + self.obj_dockarea = DockArea.DockArea() self.obj_projectExplorer = ProjectExplorer.ProjectExplorer() - - #Adding content to vertical middle Split. + + # Adding content to vertical middle Split. self.middleSplit.setOrientation(QtCore.Qt.Vertical) self.middleSplit.addWidget(self.obj_dockarea) self.middleSplit.addWidget(self.noteArea) - - #Adding middle split to Middle Container Widget + + # Adding middle split to Middle Container Widget self.middleContainerLayout.addWidget(self.middleSplit) self.middleContainer.setLayout(self.middleContainerLayout) - - #Adding content of left split + + # Adding content of left split self.leftSplit.addWidget(self.obj_projectExplorer) self.leftSplit.addWidget(self.middleContainer) - - - #Adding to main Layout + + # Adding to main Layout self.mainLayout.addWidget(self.leftSplit) - self.leftSplit.setSizes([self.width()/4.5,self.height()]) - self.middleSplit.setSizes([self.width(),self.height()/2]) + self.leftSplit.setSizes([self.width() / 4.5, self.height()]) + self.middleSplit.setSizes([self.width(), self.height() / 2]) self.setLayout(self.mainLayout) - + def main(args): """ It is main function of the module.It starts the application """ - print "Starting eSim......" + print("Starting eSim......") app = QtGui.QApplication(args) - + splash_pix = QtGui.QPixmap('../../images/splash_screen_esim.png') - splash = QtGui.QSplashScreen(splash_pix,QtCore.Qt.WindowStaysOnTopHint) + splash = QtGui.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() appView = Application() - appView.splash=splash + appView.splash = splash appView.obj_workspace.returnWhetherClickedOrNot(appView) appView.hide() - appView.obj_workspace.show() + appView.obj_workspace.show() sys.exit(app.exec_()) - - - + + # Call main function + + if __name__ == '__main__': # Create and display the splash screen main(sys.argv) - - - diff --git a/src/frontEnd/DockArea.py b/src/frontEnd/DockArea.py index 073072bf..b44a87e6 100644 --- a/src/frontEnd/DockArea.py +++ b/src/frontEnd/DockArea.py @@ -1,4 +1,4 @@ -from PyQt4 import QtGui,QtCore +from PyQt4 import QtGui, QtCore from ngspiceSimulation.pythonPlotting import plotWindow from ngspiceSimulation.NgspiceWidget import NgspiceWidget from configuration.Appconfig import Appconfig @@ -14,6 +14,7 @@ dockList = ['Welcome'] count = 1 dock = {} + class DockArea(QtGui.QMainWindow): def __init__(self): @@ -24,18 +25,19 @@ class DockArea(QtGui.QMainWindow): dock[dockName] = QtGui.QDockWidget(dockName) self.welcomeWidget = QtGui.QWidget() self.welcomeLayout = QtGui.QVBoxLayout() - self.welcomeLayout.addWidget(Welcome()) ##Call browser - - #Adding to main Layout + self.welcomeLayout.addWidget(Welcome()) # Call browser + + # Adding to main Layout self.welcomeWidget.setLayout(self.welcomeLayout) dock[dockName].setWidget(self.welcomeWidget) - #CSS + # CSS dock[dockName].setStyleSheet(" \ - QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ - ") - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock[dockName]) - - #self.tabifyDockWidget(dock['Notes'],dock['Blank']) + QWidget { border-radius: 15px; border: 1px solid gray;\ + padding: 5px; width: 200px; height: 150px; } \ + ") + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock[dockName]) + + # self.tabifyDockWidget(dock['Notes'],dock['Blank']) self.show() ''' @@ -50,10 +52,11 @@ class DockArea(QtGui.QMainWindow): dock[dockName].setWidget(self.welcome) #CSS dock[dockName].setStyleSheet(" \ - QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ - ") - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock[dockName]) - + QWidget { border-radius: 15px; border: 1px solid gray;\ + padding: 5px; width: 200px; height: 150px; } \ + ") + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock[dockName]) + #self.tabifyDockWidget(dock['Notes'],dock['Blank']) self.show() ''' @@ -68,31 +71,36 @@ class DockArea(QtGui.QMainWindow): self.testArea = QtGui.QTextEdit() self.testLayout = QtGui.QVBoxLayout() self.testLayout.addWidget(self.testArea) - - #Adding to main Layout + + # Adding to main Layout self.testWidget.setLayout(self.testLayout) - dock['Tips-'+str(count)] = QtGui.QDockWidget('Tips-'+str(count)) - dock['Tips-'+str(count)].setWidget(self.testWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['Tips-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['Tips-'+str(count)]) - + dock['Tips-' + str(count)] = QtGui.QDockWidget('Tips-' + str(count)) + dock['Tips-' + str(count)].setWidget(self.testWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['Tips-' + str(count)]) + self.tabifyDockWidget( + dock['Welcome'], dock['Tips-' + str(count)]) + """ #CSS dock['Tips-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px;\ + width: 200px; height: 150px; } \ ") """ - - dock['Tips-'+str(count)].setVisible(True) - dock['Tips-'+str(count)].setFocus() + + dock['Tips-' + str(count)].setVisible(True) + dock['Tips-' + str(count)].setFocus() """ dock['Tips-'+str(count)].setStyleSheet(" \ :hover { background-color: yellow; } \ ") """ - dock['Tips-'+str(count)].raise_() + dock['Tips-' + str(count)].raise_() - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['Tips-'+str(count)]) + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['Tips-' + str(count)]) count = count + 1 def plottingEditor(self): @@ -101,150 +109,177 @@ class DockArea(QtGui.QMainWindow): """ self.projDir = self.obj_appconfig.current_project["ProjectName"] self.projName = os.path.basename(self.projDir) - #self.project = os.path.join(self.projDir,self.projName) - - + # self.project = os.path.join(self.projDir,self.projName) + global count self.plottingWidget = QtGui.QWidget() self.plottingLayout = QtGui.QVBoxLayout() - self.plottingLayout.addWidget(plotWindow(self.projDir,self.projName)) - - #Adding to main Layout + self.plottingLayout.addWidget(plotWindow(self.projDir, self.projName)) + + # Adding to main Layout self.plottingWidget.setLayout(self.plottingLayout) - dock['Plotting-'+str(count)] = QtGui.QDockWidget('Plotting-'+str(count)) - dock['Plotting-'+str(count)].setWidget(self.plottingWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['Plotting-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['Plotting-'+str(count)]) - + dock['Plotting-' + str(count) + ] = QtGui.QDockWidget('Plotting-' + str(count)) + dock['Plotting-' + str(count)].setWidget(self.plottingWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['Plotting-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], dock['Plotting-' + str(count)]) + """ #CSS dock['Plotting-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px;\ + width: 200px; height: 150px; } \ ") """ - dock['Plotting-'+str(count)].setVisible(True) - dock['Plotting-'+str(count)].setFocus() - dock['Plotting-'+str(count)].raise_() + dock['Plotting-' + str(count)].setVisible(True) + dock['Plotting-' + str(count)].setFocus() + dock['Plotting-' + str(count)].raise_() - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['Plotting-'+str(count)]) + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['Plotting-' + str(count)]) count = count + 1 - - def ngspiceEditor(self,projDir): + + def ngspiceEditor(self, projDir): """ This function creates widget for NgSpice window """ - - + self.projDir = projDir self.projName = os.path.basename(self.projDir) - self.ngspiceNetlist = os.path.join(self.projDir,self.projName+".cir.out") - - - + self.ngspiceNetlist = os.path.join( + self.projDir, self.projName + ".cir.out") + global count self.ngspiceWidget = QtGui.QWidget() self.ngspiceLayout = QtGui.QVBoxLayout() - self.ngspiceLayout.addWidget(NgspiceWidget(self.ngspiceNetlist,self.projDir)) - - #Adding to main Layout + self.ngspiceLayout.addWidget( + NgspiceWidget( + self.ngspiceNetlist, + self.projDir)) + + # Adding to main Layout self.ngspiceWidget.setLayout(self.ngspiceLayout) - dock['NgSpice-'+str(count)] = QtGui.QDockWidget('NgSpice-'+str(count)) - dock['NgSpice-'+str(count)].setWidget(self.ngspiceWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['NgSpice-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['NgSpice-'+str(count)]) + dock['NgSpice-' + str(count) + ] = QtGui.QDockWidget('NgSpice-' + str(count)) + dock['NgSpice-' + str(count)].setWidget(self.ngspiceWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['NgSpice-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], dock['NgSpice-' + str(count)]) - #CSS - dock['NgSpice-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 0px; width: 200px; height: 150px; } \ + # CSS + dock['NgSpice-' + str(count)].setStyleSheet(" \ + .QWidget { border-radius: 15px; border: 1px solid gray; padding: 0px;\ + width: 200px; height: 150px; } \ ") - - dock['NgSpice-'+str(count)].setVisible(True) - dock['NgSpice-'+str(count)].setFocus() - dock['NgSpice-'+str(count)].raise_() - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['NgSpice-'+str(count)]) + + dock['NgSpice-' + str(count)].setVisible(True) + dock['NgSpice-' + str(count)].setFocus() + dock['NgSpice-' + str(count)].raise_() + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['NgSpice-' + str(count)]) count = count + 1 - def modelEditor(self): - print"in model editor" - global count - self.modelwidget = QtGui.QWidget() - - self.modellayout = QtGui.QVBoxLayout() - self.modellayout.addWidget(ModelEditorclass()) - - #Adding to main Layout - self.modelwidget.setLayout(self.modellayout) - - dock['Model Editor-'+str(count)] = QtGui.QDockWidget('Model Editor-'+str(count)) - dock['Model Editor-'+str(count)].setWidget(self.modelwidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['Model Editor-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['Model Editor-'+str(count)]) - - #CSS - dock['Model Editor-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + def modelEditor(self): + print("in model editor") + global count + self.modelwidget = QtGui.QWidget() + + self.modellayout = QtGui.QVBoxLayout() + self.modellayout.addWidget(ModelEditorclass()) + + # Adding to main Layout + self.modelwidget.setLayout(self.modellayout) + + dock['Model Editor-' + + str(count)] = QtGui.QDockWidget('Model Editor-' + str(count)) + dock['Model Editor-' + str(count)].setWidget(self.modelwidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['Model Editor-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], + dock['Model Editor-' + str(count)]) + + # CSS + dock['Model Editor-' + str(count)].setStyleSheet(" \ + .QWidget { border-radius: 15px; border: 1px solid gray; \ + padding: 5px; width: 200px; height: 150px; } \ ") - - dock['Model Editor-'+str(count)].setVisible(True) - dock['Model Editor-'+str(count)].setFocus() - dock['Model Editor-'+str(count)].raise_() - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['Model Editor-'+str(count)]) - count = count + 1 - - def kicadToNgspiceEditor(self,clarg1,clarg2=None): + dock['Model Editor-' + str(count)].setVisible(True) + dock['Model Editor-' + str(count)].setFocus() + dock['Model Editor-' + str(count)].raise_() + + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['Model Editor-' + str(count)]) + count = count + 1 + + def kicadToNgspiceEditor(self, clarg1, clarg2=None): global count - self.kicadToNgspiceWidget=QtGui.QWidget() - self.kicadToNgspiceLayout=QtGui.QVBoxLayout() - self.kicadToNgspiceLayout.addWidget(MainWindow(clarg1,clarg2)) - + self.kicadToNgspiceWidget = QtGui.QWidget() + self.kicadToNgspiceLayout = QtGui.QVBoxLayout() + self.kicadToNgspiceLayout.addWidget(MainWindow(clarg1, clarg2)) + self.kicadToNgspiceWidget.setLayout(self.kicadToNgspiceLayout) - dock['kicadToNgspice-'+str(count)] = QtGui.QDockWidget('kicadToNgspice-'+str(count)) - dock['kicadToNgspice-'+str(count)].setWidget(self.kicadToNgspiceWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['kicadToNgspice-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['kicadToNgspice-'+str(count)]) - - #CSS - dock['kicadToNgspice-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + dock['kicadToNgspice-' + + str(count)] = QtGui.QDockWidget('kicadToNgspice-' + str(count)) + dock['kicadToNgspice-' + + str(count)].setWidget(self.kicadToNgspiceWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['kicadToNgspice-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], + dock['kicadToNgspice-' + str(count)]) + + # CSS + dock['kicadToNgspice-' + str(count)].setStyleSheet(" \ + .QWidget { border-radius: 15px; border: 1px solid gray;\ + padding: 5px; width: 200px; height: 150px; } \ ") - - dock['kicadToNgspice-'+str(count)].setVisible(True) - dock['kicadToNgspice-'+str(count)].setFocus() - dock['kicadToNgspice-'+str(count)].raise_() - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['kicadToNgspice-'+str(count)]) + dock['kicadToNgspice-' + str(count)].setVisible(True) + dock['kicadToNgspice-' + str(count)].setFocus() + dock['kicadToNgspice-' + str(count)].raise_() + + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['kicadToNgspice-' + str(count)]) count = count + 1 - - def subcircuiteditor(self): """ This function creates a widget for different subcircuit options """ global count - self.subcktWidget=QtGui.QWidget() - self.subcktLayout=QtGui.QVBoxLayout() + self.subcktWidget = QtGui.QWidget() + self.subcktLayout = QtGui.QVBoxLayout() self.subcktLayout.addWidget(Subcircuit(self)) self.subcktWidget.setLayout(self.subcktLayout) - dock['Subcircuit-'+str(count)] = QtGui.QDockWidget('Subcircuit-'+str(count)) - dock['Subcircuit-'+str(count)].setWidget(self.subcktWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['Subcircuit-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['Subcircuit-'+str(count)]) - - #CSS - dock['Subcircuit-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + dock['Subcircuit-' + + str(count)] = QtGui.QDockWidget('Subcircuit-' + str(count)) + dock['Subcircuit-' + str(count)].setWidget(self.subcktWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['Subcircuit-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], + dock['Subcircuit-' + str(count)]) + + # CSS + dock['Subcircuit-' + str(count)].setStyleSheet(" \ + .QWidget { border-radius: 15px; border: 1px solid gray;\ + padding: 5px; width: 200px; height: 150px; } \ ") - - dock['Subcircuit-'+str(count)].setVisible(True) - dock['Subcircuit-'+str(count)].setFocus() - dock['Subcircuit-'+str(count)].raise_() - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['Subcircuit-'+str(count)]) + dock['Subcircuit-' + str(count)].setVisible(True) + dock['Subcircuit-' + str(count)].setFocus() + dock['Subcircuit-' + str(count)].raise_() + + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['Subcircuit-' + str(count)]) count = count + 1 def usermanual(self): @@ -253,25 +288,29 @@ class DockArea(QtGui.QMainWindow): """ global count - self.usermanualWidget=QtGui.QWidget() - self.usermanualLayout=QtGui.QVBoxLayout() + self.usermanualWidget = QtGui.QWidget() + self.usermanualLayout = QtGui.QVBoxLayout() self.usermanualLayout.addWidget(UserManual()) self.usermanualWidget.setLayout(self.usermanualLayout) - dock['User Manual-'+str(count)] = QtGui.QDockWidget('User Manual-'+str(count)) - dock['User Manual-'+str(count)].setWidget(self.usermanualWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['User Manual-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['User Manual-'+str(count)]) - - #CSS - dock['User Manual-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + dock['User Manual-' + + str(count)] = QtGui.QDockWidget('User Manual-' + str(count)) + dock['User Manual-' + str(count)].setWidget(self.usermanualWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['User Manual-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], + dock['User Manual-' + str(count)]) + + # CSS + dock['User Manual-' + str(count)].setStyleSheet(" \ + .QWidget { border-radius: 15px; border: 1px solid gray;\ + padding: 5px; width: 200px; height: 150px; } \ ") - - dock['User Manual-'+str(count)].setVisible(True) - dock['User Manual-'+str(count)].setFocus() - dock['User Manual-'+str(count)].raise_() - + + dock['User Manual-' + str(count)].setVisible(True) + dock['User Manual-' + str(count)].setFocus() + dock['User Manual-' + str(count)].raise_() + count = count + 1 def modelicaEditor(self, projDir): @@ -285,24 +324,29 @@ class DockArea(QtGui.QMainWindow): self.modelicaLayout.addWidget(OpenModelicaEditor(projDir)) self.modelicaWidget.setLayout(self.modelicaLayout) - dock['Modelica-'+str(count)] = QtGui.QDockWidget('Modelica-'+str(count)) - dock['Modelica-'+str(count)].setWidget(self.modelicaWidget) - self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['Modelica-'+str(count)]) - self.tabifyDockWidget(dock['Welcome'],dock['Modelica-'+str(count)]) + dock['Modelica-' + str(count) + ] = QtGui.QDockWidget('Modelica-' + str(count)) + dock['Modelica-' + str(count)].setWidget(self.modelicaWidget) + self.addDockWidget(QtCore.Qt.TopDockWidgetArea, + dock['Modelica-' + str(count)]) + self.tabifyDockWidget(dock['Welcome'], dock['Modelica-' + str(count)]) - dock['Modelica-'+str(count)].setVisible(True) - dock['Modelica-'+str(count)].setFocus() - dock['Modelica-'+str(count)].raise_() + dock['Modelica-' + str(count)].setVisible(True) + dock['Modelica-' + str(count)].setFocus() + dock['Modelica-' + str(count)].raise_() - #CSS - dock['Modelica-'+str(count)].setStyleSheet(" \ - .QWidget { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + # CSS + dock['Modelica-' + str(count)].setStyleSheet(" \ + .QWidget { border-radius: 15px; border: 1px solid gray;\ + padding: 5px; width: 200px; height: 150px; } \ ") - - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(dock['Modelica-'+str(count)]) + temp = self.obj_appconfig.current_project['ProjectName'] + self.obj_appconfig.dock_dict[temp].append( + dock['Modelica-' + str(count)]) count = count + 1 - def closeDock (self): - for dockwidget in self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']]: + def closeDock(self): + temp = self.obj_appconfig.current_project['ProjectName'] + for dockwidget in self.obj_appconfig.dock_dict[temp]: dockwidget.close() diff --git a/src/frontEnd/ProjectExplorer.py b/src/frontEnd/ProjectExplorer.py index d14a8da9..77b3f124 100644 --- a/src/frontEnd/ProjectExplorer.py +++ b/src/frontEnd/ProjectExplorer.py @@ -1,4 +1,4 @@ -from PyQt4 import QtGui,QtCore +from PyQt4 import QtGui, QtCore import os import json from configuration.Appconfig import Appconfig @@ -9,139 +9,181 @@ class ProjectExplorer(QtGui.QWidget): QtGui.QWidget.__init__(self) self.obj_appconfig = Appconfig() self.treewidget = QtGui.QTreeWidget() - self.window= QtGui.QVBoxLayout() - header = QtGui.QTreeWidgetItem(["Projects","path"]) + self.window = QtGui.QVBoxLayout() + header = QtGui.QTreeWidgetItem(["Projects", "path"]) self.treewidget.setHeaderItem(header) - self.treewidget.setColumnHidden(1,True) - - #CSS + self.treewidget.setColumnHidden(1, True) + + # CSS self.treewidget.setStyleSheet(" \ - QTreeView { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ - QTreeView::branch:has-siblings:!adjoins-item { border-image: url(../../images/vline.png) 0; } \ - QTreeView::branch:has-siblings:adjoins-item { border-image: url(../../images/branch-more.png) 0; } \ - QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: url(../../images/branch-end.png) 0; } \ + QTreeView { border-radius: 15px; border: 1px solid gray; padding: \ + 5px; width: 200px; height: 150px; } \ + QTreeView::branch:has-siblings:!adjoins-item { border-image:\ + url(../../images/vline.png) 0; } \ + QTreeView::branch:has-siblings:adjoins-item { border-image:\ + url(../../images/branch-more.png) 0; } \ + QTreeView::branch:!has-children:!has-siblings:\ + adjoins-item { border-image: url(../../images/branch-end.png) 0; } \ QTreeView::branch:has-children:!has-siblings:closed, \ - QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(../../images/branch-closed.png); } \ + QTreeView::branch:closed:has-children:has-siblings { border-image:\ + none; image: url(../../images/branch-closed.png); } \ QTreeView::branch:open:has-children:!has-siblings, \ - QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(../../images/branch-open.png); } \ + QTreeView::branch:open:has-children:has-siblings { border-image: \ + none; image: url(../../images/branch-open.png); } \ ") - - for parents, children in self.obj_appconfig.project_explorer.items(): + + for parents, children in list( + self.obj_appconfig.project_explorer.items()): os.path.join(parents) if os.path.exists(parents): - pathlist= parents.split(os.sep) - parentnode = QtGui.QTreeWidgetItem(self.treewidget, [pathlist[-1],parents]) + pathlist = parents.split(os.sep) + parentnode = QtGui.QTreeWidgetItem( + self.treewidget, [pathlist[-1], parents]) for files in children: - childnode = QtGui.QTreeWidgetItem(parentnode, [files, os.path.join(parents,files)]) + QtGui.QTreeWidgetItem( + parentnode, [files, os.path.join(parents, files)]) self.window.addWidget(self.treewidget) - + self.treewidget.doubleClicked.connect(self.openProject) self.treewidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.treewidget.customContextMenuRequested.connect(self.openMenu) self.setLayout(self.window) self.show() - + def addTreeNode(self, parents, children): os.path.join(parents) - pathlist= parents.split(os.sep) - parentnode = QtGui.QTreeWidgetItem(self.treewidget, [pathlist[-1], parents]) + pathlist = parents.split(os.sep) + parentnode = QtGui.QTreeWidgetItem( + self.treewidget, [pathlist[-1], parents]) for files in children: - childnode = QtGui.QTreeWidgetItem(parentnode, [files, os.path.join(parents,files)]) - self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']] = [] - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']] = [] - + QtGui.QTreeWidgetItem( + parentnode, [files, os.path.join(parents, files)] + ) + + ( + self.obj_appconfig. + proc_dict[self.obj_appconfig.current_project['ProjectName']] + ) = [] + ( + self.obj_appconfig. + dock_dict[self.obj_appconfig.current_project['ProjectName']] + ) = [] + def openMenu(self, position): - + indexes = self.treewidget.selectedIndexes() if len(indexes) > 0: - + level = 0 index = indexes[0] while index.parent().isValid(): index = index.parent() level += 1 - + menu = QtGui.QMenu() if level == 0: deleteproject = menu.addAction(self.tr("Remove Project")) deleteproject.triggered.connect(self.removeProject) - refreshproject= menu.addAction(self.tr("Refresh")) + refreshproject = menu.addAction(self.tr("Refresh")) refreshproject.triggered.connect(self.refreshProject) elif level == 1: openfile = menu.addAction(self.tr("Open")) openfile.triggered.connect(self.openProject) - - menu.exec_(self.treewidget.viewport().mapToGlobal(position)) - + + menu.exec_(self.treewidget.viewport().mapToGlobal(position)) + def openProject(self): - self.indexItem =self.treewidget.currentIndex() - filename= self.indexItem.data().toString() - self.filePath= self.indexItem.sibling(self.indexItem.row(), 1).data().toString() - self.obj_appconfig.print_info('The current project is ' + self.filePath) - + self.indexItem = self.treewidget.currentIndex() + filename = str(self.indexItem.data()) + self.filePath = str( + self.indexItem.sibling( + self.indexItem.row(), + 1).data()) + self.obj_appconfig.print_info( + 'The current project is ' + self.filePath) + self.textwindow = QtGui.QWidget() self.textwindow.setMinimumSize(600, 500) - self.textwindow.setGeometry(QtCore.QRect(400,150,400,400)) + self.textwindow.setGeometry(QtCore.QRect(400, 150, 400, 400)) self.textwindow.setWindowTitle(filename) - + self.text = QtGui.QTextEdit() self.save = QtGui.QPushButton('Save and Exit') self.save.setDisabled(True) self.windowgrid = QtGui.QGridLayout() - if (os.path.isfile(str(self.filePath)))== True: + # if (os.path.isfile(str(self.filePath))) == True: + if (os.path.isfile(str(self.filePath))): self.fopen = open(str(self.filePath), 'r') lines = self.fopen.read() self.text.setText(lines) - - QtCore.QObject.connect(self.text,QtCore.SIGNAL("textChanged()"), self.enable_save) - + + QtCore.QObject.connect( + self.text, + QtCore.SIGNAL("textChanged()"), + self.enable_save) + vbox_main = QtGui.QVBoxLayout(self.textwindow) vbox_main.addWidget(self.text) vbox_main.addWidget(self.save) self.save.clicked.connect(self.save_data) - #self.connect(exit,QtCore.SIGNAL('close()'), self.onQuit) - + # self.connect(exit,QtCore.SIGNAL('close()'), self.onQuit) + self.textwindow.show() else: - self.obj_appconfig.current_project["ProjectName"]= str(self.filePath) - self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']] = [] - if self.obj_appconfig.current_project['ProjectName'] not in self.obj_appconfig.dock_dict: - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']] = [] - + self.obj_appconfig.current_project["ProjectName"] = str( + self.filePath) + self.obj_appconfig.proc_dict + [self.obj_appconfig.current_project['ProjectName']] = [ + ] + if self.obj_appconfig.current_project['ProjectName'] \ + not in self.obj_appconfig.dock_dict: + self.obj_appconfig.dock_dict + [self.obj_appconfig.current_project['ProjectName']] = [ + ] + def enable_save(self): self.save.setEnabled(True) - + def save_data(self): - self.fopen=open(self.filePath, 'w') + self.fopen = open(self.filePath, 'w') self.fopen.write(self.text.toPlainText()) self.fopen.close() self.textwindow.close() - + def removeProject(self): - self.indexItem =self.treewidget.currentIndex() - filename= self.indexItem.data().toString() - self.filePath= self.indexItem.sibling(self.indexItem.row(), 1).data().toString() + self.indexItem = self.treewidget.currentIndex() + self.filePath = str( + self.indexItem.sibling( + self.indexItem.row(), + 1).data()) self.int = self.indexItem.row() self.treewidget.takeTopLevelItem(self.int) - + if self.obj_appconfig.current_project["ProjectName"] == self.filePath: - self.obj_appconfig.current_project["ProjectName"] = None - + self.obj_appconfig.current_project["ProjectName"] = None + del self.obj_appconfig.project_explorer[str(self.filePath)] - json.dump(self.obj_appconfig.project_explorer, open(self.obj_appconfig.dictPath,'w')) - + json.dump(self.obj_appconfig.project_explorer, + open(self.obj_appconfig.dictPath, 'w')) + def refreshProject(self): - self.indexItem =self.treewidget.currentIndex() - filename= self.indexItem.data().toString() - self.filePath= str(self.indexItem.sibling(self.indexItem.row(), 1).data().toString()) - filelistnew= os.listdir(os.path.join(self.filePath)) + self.indexItem = self.treewidget.currentIndex() + self.filePath = str( + self.indexItem.sibling( + self.indexItem.row(), + 1).data()) + filelistnew = os.listdir(os.path.join(self.filePath)) parentnode = self.treewidget.currentItem() count = parentnode.childCount() for i in range(count): for items in self.treewidget.selectedItems(): items.removeChild(items.child(0)) for files in filelistnew: - childnode= QtGui.QTreeWidgetItem(parentnode, [files, os.path.join(self.filePath,files)]) - - self.obj_appconfig.project_explorer[self.filePath]= filelistnew - json.dump(self.obj_appconfig.project_explorer, open(self.obj_appconfig.dictPath,'w')) + QtGui.QTreeWidgetItem( + parentnode, [ + files, os.path.join( + self.filePath, files)]) + + self.obj_appconfig.project_explorer[self.filePath] = filelistnew + json.dump(self.obj_appconfig.project_explorer, + open(self.obj_appconfig.dictPath, 'w')) diff --git a/src/frontEnd/ProjectExplorer.py.bak b/src/frontEnd/ProjectExplorer.py.bak new file mode 100644 index 00000000..8c75398e --- /dev/null +++ b/src/frontEnd/ProjectExplorer.py.bak @@ -0,0 +1,147 @@ +from PyQt4 import QtGui,QtCore +import os +import json +from configuration.Appconfig import Appconfig + + +class ProjectExplorer(QtGui.QWidget): + def __init__(self): + QtGui.QWidget.__init__(self) + self.obj_appconfig = Appconfig() + self.treewidget = QtGui.QTreeWidget() + self.window= QtGui.QVBoxLayout() + header = QtGui.QTreeWidgetItem(["Projects","path"]) + self.treewidget.setHeaderItem(header) + self.treewidget.setColumnHidden(1,True) + + #CSS + self.treewidget.setStyleSheet(" \ + QTreeView { border-radius: 15px; border: 1px solid gray; padding: 5px; width: 200px; height: 150px; } \ + QTreeView::branch:has-siblings:!adjoins-item { border-image: url(../../images/vline.png) 0; } \ + QTreeView::branch:has-siblings:adjoins-item { border-image: url(../../images/branch-more.png) 0; } \ + QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: url(../../images/branch-end.png) 0; } \ + QTreeView::branch:has-children:!has-siblings:closed, \ + QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(../../images/branch-closed.png); } \ + QTreeView::branch:open:has-children:!has-siblings, \ + QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(../../images/branch-open.png); } \ + ") + + for parents, children in list(self.obj_appconfig.project_explorer.items()): + os.path.join(parents) + if os.path.exists(parents): + pathlist= parents.split(os.sep) + parentnode = QtGui.QTreeWidgetItem(self.treewidget, [pathlist[-1],parents]) + for files in children: + childnode = QtGui.QTreeWidgetItem(parentnode, [files, os.path.join(parents,files)]) + self.window.addWidget(self.treewidget) + + self.treewidget.doubleClicked.connect(self.openProject) + self.treewidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) + self.treewidget.customContextMenuRequested.connect(self.openMenu) + self.setLayout(self.window) + self.show() + + def addTreeNode(self, parents, children): + os.path.join(parents) + pathlist= parents.split(os.sep) + parentnode = QtGui.QTreeWidgetItem(self.treewidget, [pathlist[-1], parents]) + for files in children: + childnode = QtGui.QTreeWidgetItem(parentnode, [files, os.path.join(parents,files)]) + self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']] = [] + self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']] = [] + + def openMenu(self, position): + + indexes = self.treewidget.selectedIndexes() + if len(indexes) > 0: + + level = 0 + index = indexes[0] + while index.parent().isValid(): + index = index.parent() + level += 1 + + menu = QtGui.QMenu() + if level == 0: + deleteproject = menu.addAction(self.tr("Remove Project")) + deleteproject.triggered.connect(self.removeProject) + refreshproject= menu.addAction(self.tr("Refresh")) + refreshproject.triggered.connect(self.refreshProject) + elif level == 1: + openfile = menu.addAction(self.tr("Open")) + openfile.triggered.connect(self.openProject) + + menu.exec_(self.treewidget.viewport().mapToGlobal(position)) + + def openProject(self): + self.indexItem =self.treewidget.currentIndex() + filename= self.indexItem.data().toString() + self.filePath= self.indexItem.sibling(self.indexItem.row(), 1).data().toString() + self.obj_appconfig.print_info('The current project is ' + self.filePath) + + self.textwindow = QtGui.QWidget() + self.textwindow.setMinimumSize(600, 500) + self.textwindow.setGeometry(QtCore.QRect(400,150,400,400)) + self.textwindow.setWindowTitle(filename) + + self.text = QtGui.QTextEdit() + self.save = QtGui.QPushButton('Save and Exit') + self.save.setDisabled(True) + self.windowgrid = QtGui.QGridLayout() + if (os.path.isfile(str(self.filePath)))== True: + self.fopen = open(str(self.filePath), 'r') + lines = self.fopen.read() + self.text.setText(lines) + + QtCore.QObject.connect(self.text,QtCore.SIGNAL("textChanged()"), self.enable_save) + + vbox_main = QtGui.QVBoxLayout(self.textwindow) + vbox_main.addWidget(self.text) + vbox_main.addWidget(self.save) + self.save.clicked.connect(self.save_data) + #self.connect(exit,QtCore.SIGNAL('close()'), self.onQuit) + + self.textwindow.show() + else: + self.obj_appconfig.current_project["ProjectName"]= str(self.filePath) + self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']] = [] + if self.obj_appconfig.current_project['ProjectName'] not in self.obj_appconfig.dock_dict: + self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']] = [] + + def enable_save(self): + self.save.setEnabled(True) + + def save_data(self): + self.fopen=open(self.filePath, 'w') + self.fopen.write(self.text.toPlainText()) + self.fopen.close() + self.textwindow.close() + + def removeProject(self): + self.indexItem =self.treewidget.currentIndex() + filename= self.indexItem.data().toString() + self.filePath= self.indexItem.sibling(self.indexItem.row(), 1).data().toString() + self.int = self.indexItem.row() + self.treewidget.takeTopLevelItem(self.int) + + if self.obj_appconfig.current_project["ProjectName"] == self.filePath: + self.obj_appconfig.current_project["ProjectName"] = None + + del self.obj_appconfig.project_explorer[str(self.filePath)] + json.dump(self.obj_appconfig.project_explorer, open(self.obj_appconfig.dictPath,'w')) + + def refreshProject(self): + self.indexItem =self.treewidget.currentIndex() + filename= self.indexItem.data().toString() + self.filePath= str(self.indexItem.sibling(self.indexItem.row(), 1).data().toString()) + filelistnew= os.listdir(os.path.join(self.filePath)) + parentnode = self.treewidget.currentItem() + count = parentnode.childCount() + for i in range(count): + for items in self.treewidget.selectedItems(): + items.removeChild(items.child(0)) + for files in filelistnew: + childnode= QtGui.QTreeWidgetItem(parentnode, [files, os.path.join(self.filePath,files)]) + + self.obj_appconfig.project_explorer[self.filePath]= filelistnew + json.dump(self.obj_appconfig.project_explorer, open(self.obj_appconfig.dictPath,'w')) diff --git a/src/frontEnd/Workspace.py b/src/frontEnd/Workspace.py index 7cefa6c6..7bc74deb 100644 --- a/src/frontEnd/Workspace.py +++ b/src/frontEnd/Workspace.py @@ -1,20 +1,20 @@ -#=============================================================================== +# ========================================================================= # # FILE: Workspace.py -# -# USAGE: --- -# -# DESCRIPTION: This define all configuration used in Application. -# +# +# USAGE: --- +# +# DESCRIPTION: This define all configuration used in Application. +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 05 February 2015 +# CREATED: Wednesday 05 February 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= from PyQt4 import QtCore, QtGui from configuration.Appconfig import Appconfig import time @@ -25,46 +25,46 @@ class Workspace(QtGui.QWidget): """ This class creates Workspace GUI. """ - def __init__(self,parent=None): + + def __init__(self, parent=None): super(Workspace, self).__init__() self.obj_appconfig = Appconfig() - - #Initializing Workspace directory for project + + # Initializing Workspace directory for project self.initWorkspace() - - + def initWorkspace(self): - #print "Calling workspace" - + # print "Calling workspace" + self.mainwindow = QtGui.QVBoxLayout() self.split = QtGui.QSplitter() self.split.setOrientation(QtCore.Qt.Vertical) - + self.grid = QtGui.QGridLayout() self.note = QtGui.QTextEdit(self) self.workspace_label = QtGui.QLabel(self) self.workspace_loc = QtGui.QLineEdit(self) - + self.note.append(self.obj_appconfig.workspace_text) self.workspace_label.setText("Workspace:") self.workspace_loc.setText(self.obj_appconfig.home) - - #Buttons + + # Buttons self.browsebtn = QtGui.QPushButton('Browse') self.browsebtn.clicked.connect(self.browseLocation) self.okbtn = QtGui.QPushButton('OK') self.okbtn.clicked.connect(self.createWorkspace) self.cancelbtn = QtGui.QPushButton('Cancel') self.cancelbtn.clicked.connect(self.defaultWorkspace) - #Layout - self.grid.addWidget(self.note, 0,0,1,15) - self.grid.addWidget(self.workspace_label, 2,1) - self.grid.addWidget(self.workspace_loc,2,2,2,12) - self.grid.addWidget(self.browsebtn, 2,14) - self.grid.addWidget(self.okbtn, 4,13) - self.grid.addWidget(self.cancelbtn, 4,14) - - self.setGeometry(QtCore.QRect(500,250,400,400)) + # Layout + self.grid.addWidget(self.note, 0, 0, 1, 15) + self.grid.addWidget(self.workspace_label, 2, 1) + self.grid.addWidget(self.workspace_loc, 2, 2, 2, 12) + self.grid.addWidget(self.browsebtn, 2, 14) + self.grid.addWidget(self.okbtn, 4, 13) + self.grid.addWidget(self.cancelbtn, 4, 14) + + self.setGeometry(QtCore.QRect(500, 250, 400, 400)) self.setMaximumSize(4000, 200) self.setWindowTitle("eSim") self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) @@ -72,50 +72,48 @@ class Workspace(QtGui.QWidget): self.setWindowIcon(QtGui.QIcon('../../images/logo.png')) self.setLayout(self.grid) self.show() - - + def defaultWorkspace(self): - print "Default workspace selected : "+self.obj_appconfig.default_workspace["workspace"] - self.imp_var=1 - self.obj_appconfig.print_info('Default workspace selected : ' + self.obj_appconfig.default_workspace["workspace"]) + print("Default workspace selected : " + + self.obj_appconfig.default_workspace["workspace"]) + self.imp_var = 1 + self.obj_appconfig.print_info( + 'Default workspace selected : ' + + self.obj_appconfig.default_workspace["workspace"]) self.close() var_appView.show() time.sleep(1) var_appView.splash.close() - - - def close(self, *args, **kwargs): - self.window_open_close=1 - self.close_var=1 + self.window_open_close = 1 + self.close_var = 1 return QtGui.QWidget.close(self, *args, **kwargs) - - def returnWhetherClickedOrNot(self,appView): + def returnWhetherClickedOrNot(self, appView): global var_appView - var_appView=appView + var_appView = appView - def createWorkspace(self): - print "Function : Create workspace" + print("Function : Create workspace") self.create_workspace = str(self.workspace_loc.text()) self.obj_appconfig.print_info('Workspace : ' + self.create_workspace) - #Checking if Workspace already exist or not - if os.path.isdir(self.create_workspace): - self.obj_appconfig.default_workspace["workspace"] = self.create_workspace + # Checking if Workspace already exist or not + if os.path.isdir(self.create_workspace): + self.obj_appconfig.default_workspace["workspace"] \ + = self.create_workspace else: os.mkdir(self.create_workspace) - self.obj_appconfig.default_workspace["workspace"] = self.create_workspace - self.imp_var=1 - self.close() + self.obj_appconfig.default_workspace["workspace"] \ + = self.create_workspace + self.imp_var = 1 + self.close() var_appView.show() time.sleep(1) var_appView.splash.close() - - + def browseLocation(self): - print "Function : Browse Location" - self.workspace_directory = QtGui.QFileDialog.getExistingDirectory(self, "Browse Location",os.path.expanduser("~")) + print("Function : Browse Location") + self.workspace_directory = QtGui.QFileDialog.getExistingDirectory( + self, "Browse Location", os.path.expanduser("~")) self.workspace_loc.setText(self.workspace_directory) -
\ No newline at end of file diff --git a/src/frontEnd/pathmagic.py b/src/frontEnd/pathmagic.py new file mode 100644 index 00000000..92a5e6e2 --- /dev/null +++ b/src/frontEnd/pathmagic.py @@ -0,0 +1,6 @@ +import os +import sys +# Setting PYTHONPATH +cwd = os.getcwd() +(setPath, fronEnd) = os.path.split(cwd) +sys.path.append(setPath)
\ No newline at end of file diff --git a/src/kicadtoNgspice/Analysis.py b/src/kicadtoNgspice/Analysis.py index 43fcca0d..cde39f8f 100644 --- a/src/kicadtoNgspice/Analysis.py +++ b/src/kicadtoNgspice/Analysis.py @@ -1,15 +1,17 @@ from PyQt4 import QtGui -import TrackWidget +from . import TrackWidget import os -#from xml.etree import ElementTree as ET +# from xml.etree import ElementTree as ET import json + class Analysis(QtGui.QWidget): """ This class create Analysis Tab in KicadtoNgspice Window. """ - def __init__(self,clarg1): + + def __init__(self, clarg1): self.clarg1 = clarg1 QtGui.QWidget.__init__(self) self.track_obj = TrackWidget.TrackWidget() @@ -22,24 +24,24 @@ class Analysis(QtGui.QWidget): self.dc_parameter = {} self.tran_parameter = {} self.createAnalysisWidget() - + def createAnalysisWidget(self): self.grid = QtGui.QGridLayout() self.grid.addWidget(self.createCheckBox(), 0, 0) self.grid.addWidget(self.createACgroup(), 1, 0) self.grid.addWidget(self.createDCgroup(), 2, 0) self.grid.addWidget(self.createTRANgroup(), 3, 0) - + try: kicadFile = self.clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) if os.path.isfile(os.path.join(projpath, 'analysis')): - print "Analysis file is present" - - analysisfile = open(os.path.join(projpath,'analysis')) + print("Analysis file is present") + + analysisfile = open(os.path.join(projpath, 'analysis')) content = analysisfile.readline() - print "Content of Analysis file :", content - contentlist= content.split() + print("Content of Analysis file :", content) + contentlist = content.split() if contentlist[0] == '.ac': self.checkAC.setChecked(True) @@ -56,21 +58,21 @@ class Analysis(QtGui.QWidget): elif contentlist[1] == 'oct': self.Oct.setChecked(True) self.track_obj.AC_type["ITEMS"] = "oct" - + elif contentlist[0] == '.dc': self.checkDC.setChecked(True) self.dcbox.setDisabled(False) self.acbox.setDisabled(True) self.trbox.setDisabled(True) - self.track_obj.set_CheckBox["ITEMS"] ="DC" - + self.track_obj.set_CheckBox["ITEMS"] = "DC" + elif contentlist[0] == '.tran': self.checkTRAN.setChecked(True) self.trbox.setDisabled(False) self.acbox.setDisabled(True) self.dcbox.setDisabled(True) self.track_obj.set_CheckBox["ITEMS"] = "TRAN" - + elif contentlist[0] == '.op': self.checkDC.setChecked(True) self.dcbox.setDisabled(False) @@ -79,18 +81,18 @@ class Analysis(QtGui.QWidget): self.check.setChecked(True) self.track_obj.set_CheckBox["ITEMS"] = "DC" - except: + except BaseException: self.checkTRAN.setChecked(True) - self.track_obj.set_CheckBox["ITEMS"]="TRAN" - + self.track_obj.set_CheckBox["ITEMS"] = "TRAN" + self.setLayout(self.grid) self.show() - + def createCheckBox(self): self.checkbox = QtGui.QGroupBox() self.checkbox.setTitle("Select Analysis Type") self.checkgrid = QtGui.QGridLayout() - + self.checkgroupbtn = QtGui.QButtonGroup() self.checkAC = QtGui.QCheckBox("AC") self.checkDC = QtGui.QCheckBox("DC") @@ -101,52 +103,57 @@ class Analysis(QtGui.QWidget): self.checkgroupbtn.addButton(self.checkTRAN) self.checkgroupbtn.setExclusive(True) self.checkgroupbtn.buttonClicked.connect(self.enableBox) - + self.checkgrid.addWidget(self.checkAC, 0, 0) self.checkgrid.addWidget(self.checkDC, 0, 1) self.checkgrid.addWidget(self.checkTRAN, 0, 2) self.checkbox.setLayout(self.checkgrid) - + return self.checkbox - + def enableBox(self): if self.checkAC.isChecked(): self.acbox.setDisabled(False) self.dcbox.setDisabled(True) self.trbox.setDisabled(True) self.track_obj.set_CheckBox["ITEMS"] = "AC" - + elif self.checkDC.isChecked(): self.dcbox.setDisabled(False) self.acbox.setDisabled(True) self.trbox.setDisabled(True) self.track_obj.set_CheckBox["ITEMS"] = "DC" - + elif self.checkTRAN.isChecked(): self.trbox.setDisabled(False) self.acbox.setDisabled(True) self.dcbox.setDisabled(True) self.track_obj.set_CheckBox["ITEMS"] = "TRAN" - + def createACgroup(self): kicadFile = self.clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path.basename(projpath) check = 1 try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: + except BaseException: check = 0 - print "AC Previous Values JSON is Empty" - + print("AC Previous Values JSON is Empty") + self.acbox = QtGui.QGroupBox() self.acbox.setTitle("AC Analysis") self.acbox.setDisabled(True) self.acgrid = QtGui.QGridLayout() - self.radiobuttongroup= QtGui.QButtonGroup() + self.radiobuttongroup = QtGui.QButtonGroup() self.Lin = QtGui.QRadioButton("Lin") self.Dec = QtGui.QRadioButton("Dec") self.Oct = QtGui.QRadioButton("Oct") @@ -155,13 +162,13 @@ class Analysis(QtGui.QWidget): self.radiobuttongroup.addButton(self.Oct) self.radiobuttongroup.setExclusive(True) self.Lin.setChecked(True) - self.track_obj.AC_type["ITEMS"]="lin" + self.track_obj.AC_type["ITEMS"] = "lin" self.radiobuttongroup.buttonClicked.connect(self.set_ac_type) self.acgrid.addWidget(self.Lin, 1, 1) self.acgrid.addWidget(self.Dec, 1, 2) self.acgrid.addWidget(self.Oct, 1, 3) self.acbox.setLayout(self.acgrid) - + self.scale = QtGui.QLabel("Scale") self.start_fre_lable = QtGui.QLabel("Start Frequency") self.stop_fre_lable = QtGui.QLabel("Stop Frequency") @@ -170,20 +177,20 @@ class Analysis(QtGui.QWidget): self.acgrid.addWidget(self.start_fre_lable, 2, 0) self.acgrid.addWidget(self.stop_fre_lable, 3, 0) self.acgrid.addWidget(self.no_of_points, 4, 0) - + self.count = 0 - self.ac_entry_var[self.count] = QtGui.QLineEdit()#start + self.ac_entry_var[self.count] = QtGui.QLineEdit() # start self.acgrid.addWidget(self.ac_entry_var[self.count], 2, 1) self.ac_entry_var[self.count].setMaximumWidth(150) - self.count = self.count+1 - self.ac_entry_var[self.count] = QtGui.QLineEdit()#stop + self.count = self.count + 1 + self.ac_entry_var[self.count] = QtGui.QLineEdit() # stop self.acgrid.addWidget(self.ac_entry_var[self.count], 3, 1) self.ac_entry_var[self.count].setMaximumWidth(150) - self.count = self.count+1 - self.ac_entry_var[self.count] = QtGui.QLineEdit()#no of pts + self.count = self.count + 1 + self.ac_entry_var[self.count] = QtGui.QLineEdit() # no of pts self.acgrid.addWidget(self.ac_entry_var[self.count], 4, 1) self.ac_entry_var[self.count].setMaximumWidth(150) - + self.parameter_cnt = 0 self.start_fre_combo = QtGui.QComboBox() self.start_fre_combo.addItem("Hz",) @@ -196,12 +203,13 @@ class Analysis(QtGui.QWidget): self.ac_parameter[0] = "Hz" try: - self.ac_parameter[self.parameter_cnt] = str(json_data["analysis"]["ac"]["Start Fre Combo"]) - except: + self.ac_parameter[self.parameter_cnt] = str( + json_data["analysis"]["ac"]["Start Fre Combo"]) + except BaseException: self.ac_parameter[self.parameter_cnt] = "Hz" self.start_fre_combo.activated[str].connect(self.start_combovalue) - + self.parameter_cnt = self.parameter_cnt + 1 self.stop_fre_combo = QtGui.QComboBox() self.stop_fre_combo.addItem("Hz") @@ -214,19 +222,22 @@ class Analysis(QtGui.QWidget): self.ac_parameter[1] = "Hz" try: - self.ac_parameter[self.parameter_cnt] = str(json_data["analysis"]["ac"]["Stop Fre Combo"]) - except: + self.ac_parameter[self.parameter_cnt] = str( + json_data["analysis"]["ac"]["Stop Fre Combo"]) + except BaseException: self.ac_parameter[self.parameter_cnt] = "Hz" self.stop_fre_combo.activated[str].connect(self.stop_combovalue) - + self.track_obj.AC_entry_var["ITEMS"] = self.ac_entry_var self.track_obj.AC_Parameter["ITEMS"] = self.ac_parameter - - #CSS + + # CSS self.acbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: \ + 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: \ + 0 3px 0 3px; } \ ") if check: try: @@ -245,66 +256,76 @@ class Analysis(QtGui.QWidget): else: pass - self.ac_entry_var[0].setText(json_data["analysis"]["ac"]["Start Frequency"]) - self.ac_entry_var[1].setText(json_data["analysis"]["ac"]["Stop Frequency"]) - self.ac_entry_var[2].setText(json_data["analysis"]["ac"]["No. of points"]) - index = self.start_fre_combo.findText(json_data["analysis"]["ac"]["Start Fre Combo"]) + self.ac_entry_var[0].setText( + json_data["analysis"]["ac"]["Start Frequency"]) + self.ac_entry_var[1].setText( + json_data["analysis"]["ac"]["Stop Frequency"]) + self.ac_entry_var[2].setText( + json_data["analysis"]["ac"]["No. of points"]) + index = self.start_fre_combo.findText( + json_data["analysis"]["ac"]["Start Fre Combo"]) self.start_fre_combo.setCurrentIndex(index) - index = self.stop_fre_combo.findText(json_data["analysis"]["ac"]["Stop Fre Combo"]) + index = self.stop_fre_combo.findText( + json_data["analysis"]["ac"]["Stop Fre Combo"]) self.stop_fre_combo.setCurrentIndex(index) - except: - print "AC Analysis JSON Parse Error" - + except BaseException: + print("AC Analysis JSON Parse Error") + return self.acbox - + def start_combovalue(self, text): self.ac_parameter[0] = str(text) - + def stop_combovalue(self, text): self.ac_parameter[1] = str(text) - + def set_ac_type(self): self.parameter_cnt = 0 if self.Lin.isChecked(): self.track_obj.AC_type["ITEMS"] = "lin" elif self.Dec.isChecked(): - self.track_obj.AC_type["ITEMS"] = "dec" + self.track_obj.AC_type["ITEMS"] = "dec" elif self.Oct.isChecked(): self.track_obj.AC_type["ITEMS"] = "oct" else: - pass - + pass + def createDCgroup(self): kicadFile = self.clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path.basename(projpath) check = 1 try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: + except BaseException: check = 0 - print "DC Previous Values JSON is empty" + print("DC Previous Values JSON is empty") self.dcbox = QtGui.QGroupBox() self.dcbox.setTitle("DC Analysis") self.dcbox.setDisabled(True) self.dcgrid = QtGui.QGridLayout() self.dcbox.setLayout(self.dcgrid) - + self.source_name = QtGui.QLabel('Enter Source 1', self) self.source_name.setMaximumWidth(150) self.start = QtGui.QLabel('Start', self) self.start.setMaximumWidth(150) self.increment = QtGui.QLabel('Increment', self) self.increment.setMaximumWidth(150) - self.stop = QtGui.QLabel('Stop',self) + self.stop = QtGui.QLabel('Stop', self) self.stop.setMaximumWidth(150) - + self.source_name2 = QtGui.QLabel('Enter Source 2', self) self.source_name2.setMaximumWidth(150) self.start2 = QtGui.QLabel('Start', self) @@ -313,55 +334,55 @@ class Analysis(QtGui.QWidget): self.increment2.setMaximumWidth(150) self.stop2 = QtGui.QLabel('Stop', self) self.stop2.setMaximumWidth(150) - - self.dcgrid.addWidget(self.source_name, 1, 0) + + self.dcgrid.addWidget(self.source_name, 1, 0) self.dcgrid.addWidget(self.start, 2, 0) self.dcgrid.addWidget(self.increment, 3, 0) - self.dcgrid.addWidget(self.stop, 4, 0) + self.dcgrid.addWidget(self.stop, 4, 0) - self.dcgrid.addWidget(self.source_name2, 5, 0) + self.dcgrid.addWidget(self.source_name2, 5, 0) self.dcgrid.addWidget(self.start2, 6, 0) self.dcgrid.addWidget(self.increment2, 7, 0) self.dcgrid.addWidget(self.stop2, 8, 0) - + self.count = 0 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#source + self.dc_entry_var[self.count] = QtGui.QLineEdit() # source self.dcgrid.addWidget(self.dc_entry_var[self.count], 1, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#start + self.dc_entry_var[self.count] = QtGui.QLineEdit() # start self.dcgrid.addWidget(self.dc_entry_var[self.count], 2, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#increment + self.dc_entry_var[self.count] = QtGui.QLineEdit() # increment self.dcgrid.addWidget(self.dc_entry_var[self.count], 3, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#stop + self.dc_entry_var[self.count] = QtGui.QLineEdit() # stop self.dcgrid.addWidget(self.dc_entry_var[self.count], 4, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#source + self.dc_entry_var[self.count] = QtGui.QLineEdit() # source self.dcgrid.addWidget(self.dc_entry_var[self.count], 5, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#start + self.dc_entry_var[self.count] = QtGui.QLineEdit() # start self.dcgrid.addWidget(self.dc_entry_var[self.count], 6, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#increment + self.dc_entry_var[self.count] = QtGui.QLineEdit() # increment self.dcgrid.addWidget(self.dc_entry_var[self.count], 7, 1) self.dc_entry_var[self.count].setMaximumWidth(150) self.count += 1 - self.dc_entry_var[self.count] = QtGui.QLineEdit()#stop + self.dc_entry_var[self.count] = QtGui.QLineEdit() # stop self.dcgrid.addWidget(self.dc_entry_var[self.count], 8, 1) self.dc_entry_var[self.count].setMaximumWidth(150) @@ -376,14 +397,15 @@ class Analysis(QtGui.QWidget): self.dcgrid.addWidget(self.start_combo, 2, 2) try: - self.dc_parameter[self.parameter_cnt] = str(json_data["analysis"]["dc"]["Start Combo"]) - except: + self.dc_parameter[self.parameter_cnt] = str( + json_data["analysis"]["dc"]["Start Combo"]) + except BaseException: self.dc_parameter[self.parameter_cnt] = "Volts or Amperes" self.start_combo.activated[str].connect(self.start_changecombo) self.parameter_cnt += 1 - - self.increment_combo=QtGui.QComboBox(self) + + self.increment_combo = QtGui.QComboBox(self) self.increment_combo.setMaximumWidth(150) self.increment_combo.addItem("Volts or Amperes") self.increment_combo.addItem("mV or mA") @@ -393,30 +415,32 @@ class Analysis(QtGui.QWidget): self.dcgrid.addWidget(self.increment_combo, 3, 2) try: - self.dc_parameter[self.parameter_cnt] = str(json_data["analysis"]["dc"]["Increment Combo"]) - except: + self.dc_parameter[self.parameter_cnt] = str( + json_data["analysis"]["dc"]["Increment Combo"]) + except BaseException: self.dc_parameter[self.parameter_cnt] = "Volts or Amperes" self.increment_combo.activated[str].connect(self.increment_changecombo) self.parameter_cnt += 1 - + self.stop_combo = QtGui.QComboBox(self) self.stop_combo.setMaximumWidth(150) self.stop_combo.addItem("Volts or Amperes") self.stop_combo.addItem("mV or mA") self.stop_combo.addItem("uV or uA") self.stop_combo.addItem("nV or nA") - self.stop_combo.addItem("pV or pA") + self.stop_combo.addItem("pV or pA") self.dcgrid.addWidget(self.stop_combo, 4, 2) try: - self.dc_parameter[self.parameter_cnt] = str(json_data["analysis"]["dc"]["Stop Combo"]) - except: + self.dc_parameter[self.parameter_cnt] = str( + json_data["analysis"]["dc"]["Stop Combo"]) + except BaseException: self.dc_parameter[self.parameter_cnt] = "Volts or Amperes" self.stop_combo.activated[str].connect(self.stop_changecombo) self.parameter_cnt += 1 - + self.start_combo2 = QtGui.QComboBox(self) self.start_combo2.setMaximumWidth(150) self.start_combo2.addItem('Volts or Amperes') @@ -427,8 +451,9 @@ class Analysis(QtGui.QWidget): self.dcgrid.addWidget(self.start_combo2, 6, 2) try: - self.dc_parameter[self.parameter_cnt] = str(json_data["analysis"]["dc"]["Start Combo2"]) - except: + self.dc_parameter[self.parameter_cnt] = str( + json_data["analysis"]["dc"]["Start Combo2"]) + except BaseException: self.dc_parameter[self.parameter_cnt] = "Volts or Amperes" self.start_combo2.activated[str].connect(self.start_changecombo2) @@ -444,11 +469,13 @@ class Analysis(QtGui.QWidget): self.dcgrid.addWidget(self.increment_combo2, 7, 2) try: - self.dc_parameter[self.parameter_cnt] = str(json_data["analysis"]["dc"]["Increment Combo2"]) - except: + self.dc_parameter[self.parameter_cnt] = str( + json_data["analysis"]["dc"]["Increment Combo2"]) + except BaseException: self.dc_parameter[self.parameter_cnt] = "Volts or Amperes" - self.increment_combo2.activated[str].connect(self.increment_changecombo2) + self.increment_combo2.activated[str].connect( + self.increment_changecombo2) self.parameter_cnt += 1 self.stop_combo2 = QtGui.QComboBox(self) @@ -461,73 +488,91 @@ class Analysis(QtGui.QWidget): self.dcgrid.addWidget(self.stop_combo2, 8, 2) try: - self.dc_parameter[self.parameter_cnt] = str(json_data["analysis"]["dc"]["Stop Combo2"]) - except: + self.dc_parameter[self.parameter_cnt] = str( + json_data["analysis"]["dc"]["Stop Combo2"]) + except BaseException: self.dc_parameter[self.parameter_cnt] = "Volts or Amperes" self.stop_combo2.activated[str].connect(self.stop_changecombo2) self.parameter_cnt += 1 - self.check = QtGui.QCheckBox('Operating Point Analysis',self) + self.check = QtGui.QCheckBox('Operating Point Analysis', self) try: - self.track_obj.op_check.append(str(json_data["analysis"]["dc"]["Operating Point"])) - except: + self.track_obj.op_check.append( + str(json_data["analysis"]["dc"]["Operating Point"])) + except BaseException: self.track_obj.op_check.append('0') - - #QtCore.QObject.connect(check,SIGNAL("stateChanged()"),check,SLOT("checkedSlot")) + + # QtCore.QObject.connect(check,SIGNAL("stateChanged()"),check,SLOT("checkedSlot")) self.check.stateChanged.connect(self.setflag) - #self.flagcheck = 1 - #self.flagcheck= 2 + # self.flagcheck = 1 + # self.flagcheck= 2 self.dcgrid.addWidget(self.check, 9, 1, 9, 2) self.track_obj.DC_entry_var["ITEMS"] = self.dc_entry_var self.track_obj.DC_Parameter["ITEMS"] = self.dc_parameter - - #CSS + + # CSS self.dcbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: \ + 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") if check: try: - self.dc_entry_var[0].setText(json_data["analysis"]["dc"]["Source 1"]) - self.dc_entry_var[1].setText(json_data["analysis"]["dc"]["Start"]) - self.dc_entry_var[2].setText(json_data["analysis"]["dc"]["Increment"]) - self.dc_entry_var[3].setText(json_data["analysis"]["dc"]["Stop"]) - index = self.start_combo.findText(json_data["analysis"]["dc"]["Start Combo"]) + self.dc_entry_var[0].setText( + json_data["analysis"]["dc"]["Source 1"]) + self.dc_entry_var[1].setText( + json_data["analysis"]["dc"]["Start"]) + self.dc_entry_var[2].setText( + json_data["analysis"]["dc"]["Increment"]) + self.dc_entry_var[3].setText( + json_data["analysis"]["dc"]["Stop"]) + index = self.start_combo.findText( + json_data["analysis"]["dc"]["Start Combo"]) self.start_combo.setCurrentIndex(index) - index = self.increment_combo.findText(json_data["analysis"]["dc"]["Increment Combo"]) + index = self.increment_combo.findText( + json_data["analysis"]["dc"]["Increment Combo"]) self.increment_combo.setCurrentIndex(index) - index = self.stop_combo.findText(json_data["analysis"]["dc"]["Stop Combo"]) + index = self.stop_combo.findText( + json_data["analysis"]["dc"]["Stop Combo"]) self.stop_combo.setCurrentIndex(index) - self.dc_entry_var[4].setText(json_data["analysis"]["dc"]["Source 2"]) - self.dc_entry_var[5].setText(json_data["analysis"]["dc"]["Start2"]) - self.dc_entry_var[6].setText(json_data["analysis"]["dc"]["Increment2"]) - self.dc_entry_var[7].setText(json_data["analysis"]["dc"]["Stop2"]) - index = self.start_combo2.findText(json_data["analysis"]["dc"]["Start Combo2"]) + self.dc_entry_var[4].setText( + json_data["analysis"]["dc"]["Source 2"]) + self.dc_entry_var[5].setText( + json_data["analysis"]["dc"]["Start2"]) + self.dc_entry_var[6].setText( + json_data["analysis"]["dc"]["Increment2"]) + self.dc_entry_var[7].setText( + json_data["analysis"]["dc"]["Stop2"]) + index = self.start_combo2.findText( + json_data["analysis"]["dc"]["Start Combo2"]) self.start_combo2.setCurrentIndex(index) - index = self.increment_combo2.findText(json_data["analysis"]["dc"]["Increment Combo2"]) + index = self.increment_combo2.findText( + json_data["analysis"]["dc"]["Increment Combo2"]) self.increment_combo2.setCurrentIndex(index) - index = self.stop_combo2.findText(json_data["analysis"]["dc"]["Stop Combo2"]) + index = self.stop_combo2.findText( + json_data["analysis"]["dc"]["Stop Combo2"]) self.stop_combo2.setCurrentIndex(index) if json_data["analysis"]["dc"]["Operating Point"] == 1: self.check.setChecked(True) else: self.check.setChecked(False) - except: - print "DC Analysis JSON Parse Error" - + except BaseException: + print("DC Analysis JSON Parse Error") + return self.dcbox - + def start_changecombo(self, text): self.dc_parameter[0] = str(text) - + def increment_changecombo(self, text): self.dc_parameter[1] = str(text) - + def stop_changecombo(self, text): self.dc_parameter[2] = str(text) - + def start_changecombo2(self, text): self.dc_parameter[3] = str(text) @@ -535,34 +580,39 @@ class Analysis(QtGui.QWidget): self.dc_parameter[4] = str(text) def stop_changecombo2(self, text): - self.dc_parameter[5] = str(text) + self.dc_parameter[5] = str(text) def setflag(self): if self.check.isChecked(): self.track_obj.op_check.append(1) else: - self.track_obj.op_check.append(0) - + self.track_obj.op_check.append(0) + def createTRANgroup(self): kicadFile = self.clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path .basename(projpath) check = 1 try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: + except BaseException: check = 0 - print "Transient Previous Values JSON is Empty" - + print("Transient Previous Values JSON is Empty") + self.trbox = QtGui.QGroupBox() self.trbox.setTitle("Transient Analysis") - #self.trbox.setDisabled(True) - self.trgrid = QtGui.QGridLayout() + # self.trbox.setDisabled(True) + self.trgrid = QtGui.QGridLayout() self.trbox.setLayout(self.trgrid) - + self.start = QtGui.QLabel("Start Time") self.step = QtGui.QLabel("Step Time") self.stop = QtGui.QLabel("Stop Time") @@ -570,7 +620,7 @@ class Analysis(QtGui.QWidget): self.trgrid.addWidget(self.step, 2, 0) self.trgrid.addWidget(self.stop, 3, 0) self.count = 0 - + self.tran_entry_var[self.count] = QtGui.QLineEdit() self.trgrid.addWidget(self.tran_entry_var[self.count], 1, 1) self.tran_entry_var[self.count].setMaximumWidth(150) @@ -585,7 +635,7 @@ class Analysis(QtGui.QWidget): self.trgrid.addWidget(self.tran_entry_var[self.count], 3, 1) self.tran_entry_var[self.count].setMaximumWidth(150) self.count += 1 - + self.parameter_cnt = 0 self.start_combobox = QtGui.QComboBox() self.start_combobox.addItem("Sec") @@ -596,13 +646,14 @@ class Analysis(QtGui.QWidget): self.trgrid.addWidget(self.start_combobox, 1, 3) try: - self.tran_parameter[self.parameter_cnt] = str(json_data["analysis"]["tran"]["Start Combo"]) - except: + self.tran_parameter[self.parameter_cnt] = str( + json_data["analysis"]["tran"]["Start Combo"]) + except BaseException: self.tran_parameter[self.parameter_cnt] = "Sec" self.start_combobox.activated[str].connect(self.start_combo_change) self.parameter_cnt += 1 - + self.step_combobox = QtGui.QComboBox() self.step_combobox.addItem("Sec") self.step_combobox.addItem("ms") @@ -611,13 +662,14 @@ class Analysis(QtGui.QWidget): self.step_combobox.addItem("ps") self.trgrid.addWidget(self.step_combobox, 2, 3) try: - self.tran_parameter[self.parameter_cnt] = str(json_data["analysis"]["tran"]["Step Combo"]) - except: + self.tran_parameter[self.parameter_cnt] = str( + json_data["analysis"]["tran"]["Step Combo"]) + except BaseException: self.tran_parameter[self.parameter_cnt] = "Sec" self.step_combobox.activated[str].connect(self.step_combo_change) self.parameter_cnt += 1 - + self.stop_combobox = QtGui.QComboBox() self.stop_combobox.addItem("Sec") self.stop_combobox.addItem("ms") @@ -626,43 +678,51 @@ class Analysis(QtGui.QWidget): self.stop_combobox.addItem("ps") self.trgrid.addWidget(self.stop_combobox, 3, 3) try: - self.tran_parameter[self.parameter_cnt] = str(json_data["analysis"]["tran"]["Stop Combo"]) - except: + self.tran_parameter[self.parameter_cnt] = str( + json_data["analysis"]["tran"]["Stop Combo"]) + except BaseException: self.tran_parameter[self.parameter_cnt] = "Sec" self.stop_combobox.activated[str].connect(self.stop_combo_change) self.parameter_cnt += 1 - + self.track_obj.TRAN_entry_var["ITEMS"] = self.tran_entry_var self.track_obj.TRAN_Parameter["ITEMS"] = self.tran_parameter - - #CSS + + # CSS self.trbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") if check: try: - self.tran_entry_var[0].setText(json_data["analysis"]["tran"]["Start Time"]) - self.tran_entry_var[1].setText(json_data["analysis"]["tran"]["Step Time"]) - self.tran_entry_var[2].setText(json_data["analysis"]["tran"]["Stop Time"]) - index = self.start_combobox.findText(json_data["analysis"]["tran"]["Start Combo"]) + self.tran_entry_var[0].setText( + json_data["analysis"]["tran"]["Start Time"]) + self.tran_entry_var[1].setText( + json_data["analysis"]["tran"]["Step Time"]) + self.tran_entry_var[2].setText( + json_data["analysis"]["tran"]["Stop Time"]) + index = self.start_combobox.findText( + json_data["analysis"]["tran"]["Start Combo"]) self.start_combobox.setCurrentIndex(index) - index = self.step_combobox.findText(json_data["analysis"]["tran"]["Step Combo"]) + index = self.step_combobox.findText( + json_data["analysis"]["tran"]["Step Combo"]) self.step_combobox.setCurrentIndex(index) - index = self.stop_combobox.findText(json_data["analysis"]["tran"]["Stop Combo"]) + index = self.stop_combobox.findText( + json_data["analysis"]["tran"]["Stop Combo"]) self.stop_combobox.setCurrentIndex(index) - except: - print "Transient Analysis JSON Parse Error" + except BaseException: + print("Transient Analysis JSON Parse Error") + return self.trbox - return self.trbox - def start_combo_change(self, text): self.tran_parameter[0] = str(text) - + def step_combo_change(self, text): self.tran_parameter[1] = str(text) - + def stop_combo_change(self, text): self.tran_parameter[2] = str(text) diff --git a/src/kicadtoNgspice/Convert.py b/src/kicadtoNgspice/Convert.py index 4405eff7..38234fed 100644 --- a/src/kicadtoNgspice/Convert.py +++ b/src/kicadtoNgspice/Convert.py @@ -2,29 +2,32 @@ from PyQt4 import QtGui import os import shutil -import TrackWidget +from . import TrackWidget from xml.etree import ElementTree as ET + class Convert: """ - This class has all the necessary function required to convert kicad netlist to ngspice netlist. + This class has all the necessary function required to convert + kicad netlist to ngspice netlist. """ - def __init__(self,sourcelisttrack,source_entry_var,schematicInfo,clarg1): + + def __init__(self, sourcelisttrack, source_entry_var, + schematicInfo, clarg1): self.sourcelisttrack = sourcelisttrack self.schematicInfo = schematicInfo self.entry_var = source_entry_var self.sourcelistvalue = [] - self.clarg1=clarg1 - - + self.clarg1 = clarg1 + def addSourceParameter(self): """ This function add the source details to schematicInfo """ - + self.start = 0 self.end = 0 - + for compline in self.sourcelisttrack: self.index = compline[0] self.addline = self.schematicInfo[self.index] @@ -32,91 +35,158 @@ class Convert: try: self.start = compline[2] self.end = compline[3] - vo_val = str(self.entry_var[self.start].text()) if len(str(self.entry_var[self.start].text())) > 0 else '0' - va_val = str(self.entry_var[self.start+1].text()) if len(str(self.entry_var[self.start+1].text())) > 0 else '0' - freq_val = str(self.entry_var[self.start+2].text()) if len(str(self.entry_var[self.start+2].text())) > 0 else '0' - td_val = str(self.entry_var[self.start+3].text()) if len(str(self.entry_var[self.start+3].text())) > 0 else '0' - theta_val = str(self.entry_var[self.end].text()) if len(str(self.entry_var[self.end].text())) > 0 else '0' - self.addline = self.addline.partition('(')[0] + "("+vo_val+" "+va_val+" "+freq_val+" "+td_val+" "+theta_val+")" - self.sourcelistvalue.append([self.index,self.addline]) - except: - print "Caught an exception in sine voltage source ",self.addline - + vo_val = str(self.entry_var[self.start].text()) if len( + str(self.entry_var[self.start].text())) > 0 else '0' + va_val = str( + self.entry_var[self.start + 1].text() + ) if len( + str(self.entry_var[self.start + 1].text())) \ + > 0 else '0' + freq_val = str(self.entry_var[self.start + 2].text()) \ + if len( + str(self.entry_var[self.start + 2].text())) > \ + 0 else '0' + td_val = str(self.entry_var[self.start + 3].text()) if len( + str(self.entry_var[self.start + 3].text())) > \ + 0 else '0' + theta_val = str(self.entry_var[self.end].text()) if len( + str(self.entry_var[self.end].text())) > 0 else '0' + self.addline = self.addline.partition( + '(')[0] + "(" + vo_val + " " + va_val + " " +\ + freq_val + " " + td_val + " " +\ + theta_val + ")" + self.sourcelistvalue.append([self.index, self.addline]) + except BaseException: + print( + "Caught an exception in sine voltage source ", + self.addline) + elif compline[1] == 'pulse': try: self.start = compline[2] self.end = compline[3] - v1_val = str(self.entry_var[self.start].text()) if len(str(self.entry_var[self.start].text())) > 0 else '0' - v2_val = str(self.entry_var[self.start+1].text()) if len(str(self.entry_var[self.start+1].text())) > 0 else '0' - td_val = str(self.entry_var[self.start+2].text()) if len(str(self.entry_var[self.start+2].text())) > 0 else '0' - tr_val = str(self.entry_var[self.start+3].text()) if len(str(self.entry_var[self.start+3].text())) > 0 else '0' - tf_val = str(self.entry_var[self.start+4].text()) if len(str(self.entry_var[self.start+4].text())) > 0 else '0' - pw_val = str(self.entry_var[self.start+5].text()) if len(str(self.entry_var[self.start+5].text())) > 0 else '0' - tp_val = str(self.entry_var[self.end].text()) if len(str(self.entry_var[self.end].text())) > 0 else '0' - - self.addline = self.addline.partition('(')[0] + "("+v1_val+" "+v2_val+" "+td_val+" "+tr_val+" "+tf_val+" "+pw_val+" "+tp_val+")" - self.sourcelistvalue.append([self.index,self.addline]) - except: - print "Caught an exception in pulse voltage source ",self.addline - + v1_val = str(self.entry_var[self.start].text()) if len( + str(self.entry_var[self.start].text())) > 0 else '0' + v2_val = str(self.entry_var[self.start + 1].text()) if len( + str(self.entry_var[self.start + 1].text())) > \ + 0 else '0' + td_val = str(self.entry_var[self.start + 2].text()) \ + if len( + str(self.entry_var[self.start + 2].text())) > \ + 0 else '0' + tr_val = str(self.entry_var[self.start + 3].text()) if len( + str(self.entry_var[self.start + 3].text())) > \ + 0 else '0' + tf_val = str(self.entry_var[self.start + 4].text()) if len( + str(self.entry_var[self.start + 4].text())) > \ + 0 else '0' + pw_val = str(self.entry_var[self.start + 5].text()) if len( + str(self.entry_var[self.start + 5].text())) > \ + 0 else '0' + tp_val = str(self.entry_var[self.end].text()) if len( + str(self.entry_var[self.end].text())) > 0 else '0' + + self.addline = self.addline.partition( + '(')[0] + "(" + v1_val + " " + v2_val + " " +\ + td_val + " " + tr_val + " " + tf_val + " " +\ + pw_val + " " + tp_val + ")" + self.sourcelistvalue.append([self.index, self.addline]) + except BaseException: + print( + "Caught an exception in pulse voltage source ", + self.addline) + elif compline[1] == 'pwl': try: self.start = compline[2] self.end = compline[3] - t_v_val = str(self.entry_var[self.start].text()) if len(str(self.entry_var[self.start].text())) > 0 else '0 0' - self.addline = self.addline.partition('(')[0] + "("+t_v_val+")" - self.sourcelistvalue.append([self.index,self.addline]) - except: - print "Caught an exception in pwl voltage source ",self.addline - + t_v_val = str(self.entry_var[self.start].text()) if len( + str(self.entry_var[self.start].text())) > 0 else '0 0' + self.addline = self.addline.partition( + '(')[0] + "(" + t_v_val + ")" + self.sourcelistvalue.append([self.index, self.addline]) + except BaseException: + print( + "Caught an exception in pwl voltage source ", + self.addline) + elif compline[1] == 'ac': try: self.start = compline[2] self.end = compline[3] - va_val=str(self.entry_var[self.start].text()) if len(str(self.entry_var[self.start].text())) > 0 else '0' - ph_val=str(self.entry_var[self.start+1].text()) if len(str(self.entry_var[self.start+1].text())) > 0 else '0' + va_val = str(self.entry_var[self.start].text()) if len( + str(self.entry_var[self.start].text())) > 0 else '0' + ph_val = str(self.entry_var[self.start + 1].text()) if len( + str(self.entry_var[self.start + 1].text())) > \ + 0 else '0' self.addline = ' '.join(self.addline.split()) - self.addline = self.addline.partition('ac')[0] +" "+'ac'+" "+ va_val+" "+ph_val - self.sourcelistvalue.append([self.index,self.addline]) - except: - print "Caught an exception in ac voltage source ",self.addline - + self.addline = self.addline.partition( + 'ac')[0] + " " + 'ac' + " " + va_val + " " + ph_val + self.sourcelistvalue.append([self.index, self.addline]) + except BaseException: + print( + "Caught an exception in ac voltage source ", + self.addline) + elif compline[1] == 'dc': try: self.start = compline[2] self.end = compline[3] - v1_val = str(self.entry_var[self.start].text()) if len(str(self.entry_var[self.start].text())) > 0 else '0' - self.addline = ' '.join(self.addline.split()) - self.addline = self.addline.partition('dc')[0] + " " +'dc'+ " "+v1_val - self.sourcelistvalue.append([self.index,self.addline]) - except: - print "Caught an exception in dc voltage source",self.addline - + v1_val = str(self.entry_var[self.start].text()) if len( + str(self.entry_var[self.start].text())) > 0 else '0' + self.addline = ' '.join(self.addline.split()) + self.addline = self.addline.partition( + 'dc')[0] + " " + 'dc' + " " + v1_val + self.sourcelistvalue.append([self.index, self.addline]) + except BaseException: + print( + "Caught an exception in dc voltage source", + self.addline) + elif compline[1] == 'exp': try: self.start = compline[2] self.end = compline[3] - v1_val = str(self.entry_var[self.start].text()) if len(str(self.entry_var[self.start].text())) > 0 else '0' - v2_val = str(self.entry_var[self.start+1].text()) if len(str(self.entry_var[self.start+1].text())) > 0 else '0' - td1_val = str(self.entry_var[self.start+2].text()) if len(str(self.entry_var[self.start+2].text())) > 0 else '0' - tau1_val = str(self.entry_var[self.start+3].text()) if len(str(self.entry_var[self.start+3].text())) > 0 else '0' - td2_val = str(self.entry_var[self.start+4].text()) if len(str(self.entry_var[self.start+4].text())) > 0 else '0' - tau2_val = str(self.entry_var[self.end].text()) if len(str(self.entry_var[self.end].text())) > 0 else '0' - - self.addline = self.addline.partition('(')[0] + "("+v1_val+" "+v2_val+" "+td1_val+" "+tau1_val+" "+td2_val+" "+tau2_val+")" - self.sourcelistvalue.append([self.index,self.addline]) - except: - print "Caught an exception in exp voltage source ",self.addline - - #Updating Schematic with source value + v1_val = str(self.entry_var[self.start].text()) if len( + str(self.entry_var[self.start].text())) > 0 else '0' + v2_val = str(self.entry_var[self.start + 1].text()) if len( + str(self.entry_var[self.start + 1].text())) > \ + 0 else '0' + td1_val = str(self.entry_var[self.start + 2].text()) \ + if len( + str(self.entry_var[self.start + 2].text())) > \ + 0 else '0' + tau1_val = str(self.entry_var[self.start + 3].text()) \ + if len( + str(self.entry_var[self.start + 3].text())) > \ + 0 else '0' + td2_val = str(self.entry_var[self.start + 4].text()) \ + if len( + str(self.entry_var[self.start + 4].text())) > \ + 0 else '0' + tau2_val = str(self.entry_var[self.end].text()) if len( + str(self.entry_var[self.end].text())) > 0 else '0' + + self.addline = self.addline.partition( + '(')[0] + "(" + v1_val + " " + v2_val + " " +\ + td1_val + " " + tau1_val + " " + td2_val +\ + " " + tau2_val + ")" + self.sourcelistvalue.append([self.index, self.addline]) + except BaseException: + print( + "Caught an exception in exp voltage source ", + self.addline) + + # Updating Schematic with source value for item in self.sourcelistvalue: del self.schematicInfo[item[0]] - self.schematicInfo.insert(item[0],item[1]) - + self.schematicInfo.insert(item[0], item[1]) + return self.schematicInfo - - - def analysisInsertor(self,ac_entry_var,dc_entry_var, tran_entry_var,set_checkbox,ac_parameter,dc_parameter,tran_parameter,ac_type,op_check): + + def analysisInsertor(self, ac_entry_var, dc_entry_var, tran_entry_var, + set_checkbox, ac_parameter, dc_parameter, + tran_parameter, ac_type, op_check): """ This function creates an analysis file in current project """ @@ -124,41 +194,120 @@ class Convert: self.dc_entry_var = dc_entry_var self.tran_entry_var = tran_entry_var self.set_checkbox = set_checkbox - self.ac_parameter= ac_parameter - self.dc_parameter= dc_parameter + self.ac_parameter = ac_parameter + self.dc_parameter = dc_parameter self.trans_parameter = tran_parameter - self.ac_type= ac_type + self.ac_type = ac_type self.op_check = op_check - self.no=0 - - self.variable=self.set_checkbox - self.direct= self.clarg1 - (filepath, filemname)= os.path.split(self.direct) - self.Fileopen = os.path.join(filepath, "analysis") - self.writefile= open(self.Fileopen,"w") - if self.variable== 'AC': - self.no=0 - self.writefile.write(".ac"+' ' + self.ac_type + ' '+ str(self.defaultvalue(self.ac_entry_var[self.no+2].text()))+' ' + str(self.defaultvalue(self.ac_entry_var[self.no].text())) + self.ac_parameter[self.no]+ ' ' + str(self.defaultvalue(self.ac_entry_var[self.no+1].text())) + self.ac_parameter[self.no+1] ) - - elif self.variable=='DC': + self.no = 0 + + self.variable = self.set_checkbox + self.direct = self.clarg1 + (filepath, filemname) = os.path.split(self.direct) + self.Fileopen = os.path.join(filepath, "analysis") + self.writefile = open(self.Fileopen, "w") + if self.variable == 'AC': + self.no = 0 + self.writefile.write(".ac" + + ' ' + + self.ac_type + + ' ' + + str(self.defaultvalue( + self.ac_entry_var[self.no + 2].text())) + + ' ' + + str(self.defaultvalue( + self.ac_entry_var[self.no].text())) + + self.ac_parameter[self.no] + + ' ' + + str(self.defaultvalue( + self.ac_entry_var[self.no + 1].text())) + + self.ac_parameter[self.no + + 1]) + + elif self.variable == 'DC': if self.op_check[-1] == 1: - self.no=0 + self.no = 0 self.writefile.write(".op") elif self.op_check[-1] == 0 or self.op_check[-1] == '0': - self.no=0 - self.writefile.write(".dc" +' '+ str(self.dc_entry_var[self.no].text())+ ' '+ str(self.defaultvalue(self.dc_entry_var[self.no+1].text())) + self.converttosciform(self.dc_parameter[self.no]) + ' '+ str(self.defaultvalue(self.dc_entry_var[self.no+3].text()))+ self.converttosciform(self.dc_parameter[self.no+2]) + ' '+ str(self.defaultvalue(self.dc_entry_var[self.no+2].text())) + self.converttosciform(self.dc_parameter[self.no+1])) - - if self.dc_entry_var[self.no+4].text(): - self.writefile.write(' '+ str(self.defaultvalue(self.dc_entry_var[self.no+4].text()))+ ' '+ str(self.defaultvalue(self.dc_entry_var[self.no+5].text())) + self.converttosciform(self.dc_parameter[self.no+3])+ ' '+ str(self.defaultvalue(self.dc_entry_var[self.no+7].text()))+ self.converttosciform(self.dc_parameter[self.no+5])+ ' ' + str(self.defaultvalue(self.dc_entry_var[self.no+6].text()))+ self.converttosciform(self.dc_parameter[self.no+4])) + self.no = 0 + self.writefile.write(".dc" + + ' ' + + str(self.dc_entry_var[self.no].text()) + + ' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 1].text())) + + self.converttosciform( + self.dc_parameter[self.no]) + + ' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 3].text())) + + self.converttosciform( + self.dc_parameter[self.no + + 2]) + + ' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 2].text())) + + self.converttosciform( + self.dc_parameter[self.no + + 1])) + + if self.dc_entry_var[self.no + 4].text(): + self.writefile.write(' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 4].text())) + + ' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 5].text())) + + self.converttosciform( + self.dc_parameter[self.no + + 3]) + + ' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 7].text())) + + self.converttosciform( + self.dc_parameter[self.no + + 5]) + + ' ' + + str(self.defaultvalue( + self.dc_entry_var[self.no + + 6].text())) + + self.converttosciform( + self.dc_parameter[self.no + + 4])) elif self.variable == 'TRAN': - self.no= 0 - self.writefile.write(".tran" + ' '+ str(self.defaultvalue(self.tran_entry_var[self.no+1].text())) + self.converttosciform(self.trans_parameter[self.no+1]) + ' ' + str(self.defaultvalue(self.tran_entry_var[self.no+2].text())) + self.converttosciform(self.trans_parameter[self.no+2])+' '+ str(self.defaultvalue(self.tran_entry_var[self.no].text()))+ self.converttosciform(self.trans_parameter[self.no])) + self.no = 0 + self.writefile.write(".tran" + + ' ' + + str(self.defaultvalue( + self.tran_entry_var[self.no + + 1].text())) + + self.converttosciform( + self.trans_parameter[self.no + + 1]) + + ' ' + + str(self.defaultvalue( + self.tran_entry_var[self.no + + 2].text())) + + self.converttosciform( + self.trans_parameter[self.no + + 2]) + + ' ' + + str(self.defaultvalue( + self.tran_entry_var[self.no].text())) + + self.converttosciform( + self.trans_parameter[self.no])) else: pass self.writefile.close() - + def converttosciform(self, string_obj): """ This function is used for scientific conversion. @@ -174,90 +323,115 @@ class Convert: return "e-12" else: return "e-00" - + def defaultvalue(self, value): """ - This function select default value as 0 if Analysis widget do not hold any value. + This function select default value as 0 + if Analysis widget do not hold any value. """ - self.value= value + self.value = value if self.value == '': return 0 else: return self.value - - - def addModelParameter(self,schematicInfo): + + def addModelParameter(self, schematicInfo): """ This function add the Ngspice Model details to schematicInfo """ - - #Create object of TrackWidget + + # Create object of TrackWidget self.obj_track = TrackWidget.TrackWidget() - - #List to store model line + + # List to store model line addmodelLine = [] modelParamValue = [] - + for line in self.obj_track.modelTrack: - #print "Model Track :",line + # print "Model Track :",line if line[2] == 'transfo': try: - start=line[7] - end=line[8] - num_turns=str(self.obj_track.model_entry_var[start+1].text()) - - if num_turns=="": num_turns="310" - h_array= "H_array = [ " + start = line[7] + # end = line[8] + num_turns = str( + self.obj_track.model_entry_var[start + 1].text()) + + if num_turns == "": + num_turns = "310" + h_array = "H_array = [ " b_array = "B_array = [ " - h1=str(self.obj_track.model_entry_var[start].text()) - b1=str(self.obj_track.model_entry_var[start+5].text()) - - if len(h1)!=0 and len(b1)!=0: - h_array=h_array+h1+" " - b_array=b_array+b1+" " - bh_array = h_array+" ] " + b_array+" ]" + h1 = str(self.obj_track.model_entry_var[start].text()) + b1 = str(self.obj_track.model_entry_var[start + 5].text()) + + if len(h1) != 0 and len(b1) != 0: + h_array = h_array + h1 + " " + b_array = b_array + b1 + " " + bh_array = h_array + " ] " + b_array + " ]" else: - bh_array = "H_array = [-1000 -500 -375 -250 -188 -125 -63 0 63 125 188 250 375 500 1000] B_array = [-3.13e-3 -2.63e-3 -2.33e-3 -1.93e-3 -1.5e-3 -6.25e-4 -2.5e-4 0 2.5e-4 6.25e-4 1.5e-3 1.93e-3 2.33e-3 2.63e-3 3.13e-3]" - area=str(self.obj_track.model_entry_var[start+2].text()) - length=str(self.obj_track.model_entry_var[start+3].text()) - if area=="": area="1" - if length=="":length="0.01" - num_turns2=str(self.obj_track.model_entry_var[start+4].text()) - if num_turns2=="": num_turns2="620" - addmodelLine=".model "+line[3]+"_primary lcouple (num_turns= "+num_turns+")" - modelParamValue.append([line[0],addmodelLine,"*primary lcouple"]) - addmodelLine=".model "+line[3]+"_iron_core core ("+bh_array+" area = "+area+" length ="+length +")" - modelParamValue.append([line[0],addmodelLine,"*iron core"]) - addmodelLine=".model "+line[3]+"_secondary lcouple (num_turns ="+num_turns2+ ")" - modelParamValue.append([line[0],addmodelLine,"*secondary lcouple"]) + bh_array = "H_array = [-1000 -500 -375 -250 -188 -125 \ + -63 0 63 125 188 250 375 500 \ + 1000] B_array = [-3.13e-3 -2.63e-3 -2.33e-3 -1.93e-3\ + -1.5e-3 -6.25e-4 -2.5e-4 0 2.5e-4 6.25e-4 \ + 1.5e-3 1.93e-3 2.33e-3 2.63e-3 3.13e-3]" + area = str( + self.obj_track.model_entry_var[start + 2].text()) + length = str( + self.obj_track.model_entry_var[start + 3].text()) + if area == "": + area = "1" + if length == "": + length = "0.01" + num_turns2 = str( + self.obj_track.model_entry_var[start + 4].text()) + if num_turns2 == "": + num_turns2 = "620" + addmodelLine = ".model " + \ + line[3] + \ + "_primary lcouple (num_turns= " + num_turns + ")" + modelParamValue.append( + [line[0], addmodelLine, "*primary lcouple"]) + addmodelLine = ".model " + \ + line[3] + "_iron_core core (" + bh_array + \ + " area = " + area + " length =" + length + ")" + modelParamValue.append( + [line[0], addmodelLine, "*iron core"]) + addmodelLine = ".model " + \ + line[3] + \ + "_secondary lcouple (num_turns =" + num_turns2 + ")" + modelParamValue.append( + [line[0], addmodelLine, "*secondary lcouple"]) except Exception as e: - print "Caught an exception in transfo model ",line[1] - print "Exception Message : ",str(e) - + print("Caught an exception in transfo model ", line[1]) + print("Exception Message : ", str(e)) + elif line[2] == 'ic': try: - start=line[7] - end=line[8] - for key,value in line[9].iteritems(): - initVal = str(self.obj_track.model_entry_var[value].text()) - if initVal=="":initVal="0" - node = line[1].split()[1] #Extracting node from model line - addmodelLine = ".ic v("+node+")="+initVal - modelParamValue.append([line[0],addmodelLine,line[4]]) + start = line[7] + # end = line[8] + for key, value in line[9].items(): + initVal = str( + self.obj_track.model_entry_var[value].text()) + if initVal == "": + initVal = "0" + # Extracting node from model line + node = line[1].split()[1] + addmodelLine = ".ic v(" + node + ")=" + initVal + modelParamValue.append( + [line[0], addmodelLine, line[4]]) except Exception as e: - print "Caught an exception in initial condition ",line[1] - print "Exception Message : ",str(e) - - + print("Caught an exception in initial condition ", line[1]) + print("Exception Message : ", str(e)) + else: try: start = line[7] - end = line[8] - addmodelLine=".model "+ line[3]+" "+line[2]+"(" - for key,value in line[9].iteritems(): - #print "Tags: ",key - #print "Value: ",value - #Checking for default value and accordingly assign param and default. + # end = line[8] + addmodelLine = ".model " + line[3] + " " + line[2] + "(" + for key, value in line[9].items(): + # print "Tags: ",key + # print "Value: ",value + # Checking for default value and accordingly assign + # param and default. if ':' in key: key = key.split(':') param = key[0] @@ -265,183 +439,191 @@ class Convert: else: param = key default = 0 - #Cheking if value is iterable.its for vector + # Cheking if value is iterable.its for vector if hasattr(value, '__iter__'): - addmodelLine += param+"=[" + addmodelLine += param + "=[" for lineVar in value: - if str(self.obj_track.model_entry_var[lineVar].text()) == "": + if str( + self.obj_track.model_entry_var + [lineVar].text()) == "": paramVal = default else: - paramVal = str(self.obj_track.model_entry_var[lineVar].text()) - addmodelLine += paramVal+" " + paramVal = str( + self.obj_track.model_entry_var + [lineVar].text()) + addmodelLine += paramVal + " " addmodelLine += "] " else: - if str(self.obj_track.model_entry_var[value].text()) == "": + if str( + self.obj_track.model_entry_var + [value].text()) == "": paramVal = default else: - paramVal = str(self.obj_track.model_entry_var[value].text()) - - addmodelLine += param+"="+paramVal+" " - - + paramVal = str( + self.obj_track.model_entry_var + [value].text()) + + addmodelLine += param + "=" + paramVal + " " + addmodelLine += ") " - modelParamValue.append([line[0],addmodelLine,line[4]]) + modelParamValue.append([line[0], addmodelLine, line[4]]) except Exception as e: - print "Caught an exception in model ",line[1] - print "Exception Message : ",str(e) - - - #Adding it to schematic + print("Caught an exception in model ", line[1]) + print("Exception Message : ", str(e)) + + # Adding it to schematic for item in modelParamValue: if ".ic" in item[1]: - schematicInfo.insert(0,item[1]) - schematicInfo.insert(0,item[2]) + schematicInfo.insert(0, item[1]) + schematicInfo.insert(0, item[2]) else: - schematicInfo.append(item[2]) #Adding Comment - schematicInfo.append(item[1]) #Adding model line - + schematicInfo.append(item[2]) # Adding Comment + schematicInfo.append(item[1]) # Adding model line + return schematicInfo - - def addDeviceLibrary(self,schematicInfo,kicadFile): + + def addDeviceLibrary(self, schematicInfo, kicadFile): """ This function add the library details to schematicInfo """ - - (projpath,filename) = os.path.split(kicadFile) - - + + (projpath, filename) = os.path.split(kicadFile) + deviceLibList = self.obj_track.deviceModelTrack - deviceLine = {} #Key:Index, Value:with its updated line in the form of list - includeLine = [] #All .include line list - + deviceLine = {} + # Key:Index, Value:with its updated line in the form of list + includeLine = [] # All .include line list + if not deviceLibList: - print "No Library Added in the schematic" + print("No Library Added in the schematic") pass else: for eachline in schematicInfo: words = eachline.split() if words[0] in deviceLibList: - print "Found Library line" + print("Found Library line") index = schematicInfo.index(eachline) completeLibPath = deviceLibList[words[0]] - (libpath,libname) = os.path.split(completeLibPath) - print "Library Path :",libpath - #Copying library from devicemodelLibrary to Project Path - #Special case for MOSFET + (libpath, libname) = os.path.split(completeLibPath) + print("Library Path :", libpath) + # Copying library from devicemodelLibrary to Project Path + # Special case for MOSFET if eachline[0] == 'm': - #For mosfet library name come along with MOSFET dimension information + # For mosfet library name come along with MOSFET + # dimension information tempStr = libname.split(':') libname = tempStr[0] dimension = tempStr[1] - #Replace last word with library name - #words[-1] = libname.split('.')[0] - words[-1] = self.getRefrenceName(libname,libpath) - #Appending Dimension of MOSFET + # Replace last word with library name + # words[-1] = libname.split('.')[0] + words[-1] = self.getRefrenceName(libname, libpath) + # Appending Dimension of MOSFET words.append(dimension) - deviceLine[index] = words - includeLine.append(".include "+libname) - - #src = completeLibPath.split(':')[0] # <----- Not working in Windows - - (src_path,src_lib) = os.path.split(completeLibPath) + deviceLine[index] = words + includeLine.append(".include " + libname) + + # src = completeLibPath.split(':')[0] # <----- Not + # working in Windows + + (src_path, src_lib) = os.path.split(completeLibPath) src_lib = src_lib.split(':')[0] - src = os.path.join(src_path,src_lib) + src = os.path.join(src_path, src_lib) dst = projpath shutil.copy2(src, dst) else: - #Replace last word with library name - #words[-1] = libname.split('.')[0] - words[-1] = self.getRefrenceName(libname,libpath) - deviceLine[index] = words - includeLine.append(".include "+libname) - + # Replace last word with library name + # words[-1] = libname.split('.')[0] + words[-1] = self.getRefrenceName(libname, libpath) + deviceLine[index] = words + includeLine.append(".include " + libname) + src = completeLibPath dst = projpath - shutil.copy2(src,dst) - + shutil.copy2(src, dst) + else: pass - - - #Adding device line to schematicInfo - for index,value in deviceLine.iteritems(): - #Update the device line + + # Adding device line to schematicInfo + for index, value in deviceLine.items(): + # Update the device line strLine = " ".join(str(item) for item in value) schematicInfo[index] = strLine - - #This has to be second i.e after deviceLine details - #Adding .include line to Schematic Info at the start of line + + # This has to be second i.e after deviceLine details + # Adding .include line to Schematic Info at the start of line for item in list(set(includeLine)): - schematicInfo.insert(0,item) - - + schematicInfo.insert(0, item) + return schematicInfo - - def addSubcircuit(self,schematicInfo,kicadFile): + + def addSubcircuit(self, schematicInfo, kicadFile): """ This function add the subcircuit to schematicInfo """ - - (projpath,filename) = os.path.split(kicadFile) - + + (projpath, filename) = os.path.split(kicadFile) + subList = self.obj_track.subcircuitTrack - subLine = {} #Key:Index, Value:with its updated line in the form of list - includeLine = [] #All .include line list - - if len(self.obj_track.subcircuitList) != len(self.obj_track.subcircuitTrack): + subLine = {} + # Key:Index, Value:with its updated line in the form of list + includeLine = [] # All .include line list + + if len(self.obj_track.subcircuitList) != len( + self.obj_track.subcircuitTrack): self.msg = QtGui.QErrorMessage() - self.msg.showMessage("Conversion failed. Please add all Subcircuits.") + self.msg.showMessage( + "Conversion failed. Please add all Subcircuits.") self.msg.setWindowTitle("Error Message") self.msg.show() raise Exception('All subcircuit directories need to be specified.') elif not subList: - print "No Subcircuit Added in the schematic" + print("No Subcircuit Added in the schematic") pass else: for eachline in schematicInfo: words = eachline.split() if words[0] in subList: - print "Found Subcircuit line" + print("Found Subcircuit line") index = schematicInfo.index(eachline) completeSubPath = subList[words[0]] - (subpath,subname) = os.path.split(completeSubPath) - print "Library Path :",subpath - #Copying library from devicemodelLibrary to Project Path - - #Replace last word with library name + (subpath, subname) = os.path.split(completeSubPath) + print("Library Path :", subpath) + # Copying library from devicemodelLibrary to Project Path + + # Replace last word with library name words[-1] = subname.split('.')[0] - subLine[index] = words - includeLine.append(".include "+subname+".sub") - + subLine[index] = words + includeLine.append(".include " + subname + ".sub") + src = completeSubPath dst = projpath - print os.listdir(src) + print(os.listdir(src)) for files in os.listdir(src): - if os.path.isfile(os.path.join(src,files)): + if os.path.isfile(os.path.join(src, files)): if files != "analysis": - shutil.copy2(os.path.join(src,files),dst) + shutil.copy2(os.path.join(src, files), dst) else: pass - - - #Adding subcircuit line to schematicInfo - for index,value in subLine.iteritems(): - #Update the subcircuit line + + # Adding subcircuit line to schematicInfo + for index, value in subLine.items(): + # Update the subcircuit line strLine = " ".join(str(item) for item in value) schematicInfo[index] = strLine - - #This has to be second i.e after subcircuitLine details - #Adding .include line to Schematic Info at the start of line + + # This has to be second i.e after subcircuitLine details + # Adding .include line to Schematic Info at the start of line for item in list(set(includeLine)): - schematicInfo.insert(0,item) - - return schematicInfo - - def getRefrenceName(self,libname,libpath): - libname = libname.replace('.lib','.xml') - library = os.path.join(libpath,libname) - - #Extracting Value from XML + schematicInfo.insert(0, item) + + return schematicInfo + + def getRefrenceName(self, libname, libpath): + libname = libname.replace('.lib', '.xml') + library = os.path.join(libpath, libname) + + # Extracting Value from XML libtree = ET.parse(library) for child in libtree.iter(): if child.tag == 'ref_model': @@ -449,6 +631,3 @@ class Convert: else: pass return retVal - - - diff --git a/src/kicadtoNgspice/DeviceModel.py b/src/kicadtoNgspice/DeviceModel.py index a775b8a5..909756b5 100644 --- a/src/kicadtoNgspice/DeviceModel.py +++ b/src/kicadtoNgspice/DeviceModel.py @@ -1,63 +1,72 @@ from PyQt4 import QtGui import os -#from xml.etree import ElementTree as ET +# from xml.etree import ElementTree as ET import json -import TrackWidget +from . import TrackWidget class DeviceModel(QtGui.QWidget): """ This class creates Device Library Tab in KicadtoNgspice Window - It dynamically creates the widget for device like diode,mosfet,transistor and jfet. + It dynamically creates the widget for device like diode,mosfet, + transistor and jfet. """ - + def __init__(self, schematicInfo, clarg1): - + self.clarg1 = clarg1 kicadFile = self.clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path.basename(projpath) try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: - print "Device Model Previous JSON is Empty" - - + except BaseException: + print("Device Model Previous JSON is Empty") + QtGui.QWidget.__init__(self) - - #Creating track widget object + + # Creating track widget object self.obj_trac = TrackWidget.TrackWidget() - - #Row and column count + + # Row and column count self.row = 0 - self.count = 1 #Entry count + self.count = 1 # Entry count self.entry_var = {} - - #For MOSFET + + # For MOSFET self.widthLabel = {} self.lengthLabel = {} self.multifactorLable = {} - self.devicemodel_dict_beg = {} - self.devicemodel_dict_end = {} - #List to hold information about device + self.devicemodel_dict_beg = {} + self.devicemodel_dict_end = {} + # List to hold information about device self.deviceDetail = {} - - #Set Layout + + # Set Layout self.grid = QtGui.QGridLayout() self.setLayout(self.grid) - print "Reading Device model details from Schematic" - + print("Reading Device model details from Schematic") + for eachline in schematicInfo: words = eachline.split() if eachline[0] == 'q': - print "Device Model Transistor: ",words[0] + print("Device Model Transistor: ", words[0]) self.devicemodel_dict_beg[words[0]] = self.count - transbox=QtGui.QGroupBox() - transgrid=QtGui.QGridLayout() - transbox.setTitle("Add library for Transistor "+words[0]+" : "+words[4]) + transbox = QtGui.QGroupBox() + transgrid = QtGui.QGridLayout() + transbox.setTitle( + "Add library for Transistor " + + words[0] + + " : " + + words[4]) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") global path_name @@ -65,21 +74,27 @@ class DeviceModel(QtGui.QWidget): try: for key in json_data["deviceModel"]: if key[0] == eachline[0] and key[1] == eachline[1]: - #print "DEVICE MODEL MATCHING---",child.tag[0],child.tag[1],eachline[0],eachline[1] + # print "DEVICE MODEL MATCHING---",child.tag[0],\ + # child.tag[1],eachline[0],eachline[1] try: - if os.path.exists(json_data["deviceModel"][key][0]): - self.entry_var[self.count].setText(json_data["deviceModel"][key][0]) - path_name = json_data["deviceModel"][key][0] + if os.path.exists( + json_data["deviceModel"][key][0]): + self.entry_var[self.count].setText( + json_data["deviceModel"][key][0]) + path_name = json_data + ["deviceModel"][key][0] else: self.entry_var[self.count].setText("") - except: - print "Error when set text of device model transistor" - except: + except BaseException: + print( + "Error when set text of device\ + model transistor") + except BaseException: pass transgrid.addWidget(self.entry_var[self.count], self.row, 1) self.addbtn = QtGui.QPushButton("Add") - self.addbtn.setObjectName("%d" %self.count) + self.addbtn.setObjectName("%d" % self.count) self.addbtn.clicked.connect(self.trackLibrary) self.deviceDetail[self.count] = words[0] @@ -87,53 +102,63 @@ class DeviceModel(QtGui.QWidget): pass else: self.trackLibraryWithoutButton(self.count, path_name) - + transgrid.addWidget(self.addbtn, self.row, 2) transbox.setLayout(transgrid) - - #CSS + + # CSS transbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(transbox) - - #Adding Device Details - - - #Increment row and widget count + + # Adding Device Details + + # Increment row and widget count self.row = self.row + 1 self.devicemodel_dict_end[words[0]] = self.count self.count = self.count + 1 - + elif eachline[0] == 'd': - print "Device Model Diode:",words[0] + print("Device Model Diode:", words[0]) self.devicemodel_dict_beg[words[0]] = self.count diodebox = QtGui.QGroupBox() diodegrid = QtGui.QGridLayout() - diodebox.setTitle("Add library for Diode "+words[0]+" : "+words[3]) + diodebox.setTitle( + "Add library for Diode " + + words[0] + + " : " + + words[3]) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") - #global path_name + # global path_name try: for key in json_data["deviceModel"]: if key[0] == eachline[0] and key[1] == eachline[1]: - #print "DEVICE MODEL MATCHING---",child.tag[0],child.tag[1],eachline[0],eachline[1] + # print "DEVICE MODEL MATCHING---",child.tag[0],\ + # child.tag[1],eachline[0],eachline[1] try: - if os.path.exists(json_data["deviceModel"][key][0]): - path_name = json_data["deviceModel"][key][0] - self.entry_var[self.count].setText(json_data["deviceModel"][key][0]) + if os.path.exists( + json_data["deviceModel"][key][0]): + path_name = json_data + ["deviceModel"][key][0] + self.entry_var[self.count].setText( + json_data["deviceModel"][key][0]) else: self.entry_var[self.count].setText("") - except: - print "Error when set text of device model diode" - except: + except BaseException: + print("Error when set text of device\ + model diode") + except BaseException: pass diodegrid.addWidget(self.entry_var[self.count], self.row, 1) self.addbtn = QtGui.QPushButton("Add") - self.addbtn.setObjectName("%d" %self.count) + self.addbtn.setObjectName("%d" % self.count) self.addbtn.clicked.connect(self.trackLibrary) self.deviceDetail[self.count] = words[0] @@ -144,50 +169,60 @@ class DeviceModel(QtGui.QWidget): diodegrid.addWidget(self.addbtn, self.row, 2) diodebox.setLayout(diodegrid) - - #CSS + + # CSS diodebox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(diodebox) - - #Adding Device Details - - - #Increment row and widget count + + # Adding Device Details + + # Increment row and widget count self.row = self.row + 1 self.devicemodel_dict_end[words[0]] = self.count self.count = self.count + 1 - + elif eachline[0] == 'j': - print "Device Model JFET:",words[0] + print("Device Model JFET:", words[0]) self.devicemodel_dict_beg[words[0]] = self.count jfetbox = QtGui.QGroupBox() jfetgrid = QtGui.QGridLayout() - jfetbox.setTitle("Add library for JFET "+words[0]+" : "+words[4]) + jfetbox.setTitle( + "Add library for JFET " + + words[0] + + " : " + + words[4]) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") - #global path_name + # global path_name try: for key in json_data["deviceModel"]: if key[0] == eachline[0] and key[1] == eachline[1]: - #print "DEVICE MODEL MATCHING---",child.tag[0],child.tag[1],eachline[0],eachline[1] + # print "DEVICE MODEL MATCHING---",child.tag[0],\ + # child.tag[1],eachline[0],eachline[1] try: - if os.path.exists(json_data["deviceModel"][key][0]): - self.entry_var[self.count].setText(json_data["deviceModel"][key][0]) - path_name = json_data["deviceModel"][key][0] + if os.path.exists( + json_data["deviceModel"][key][0]): + self.entry_var[self.count].setText( + json_data["deviceModel"][key][0]) + path_name = json_data + ["deviceModel"][key][0] else: self.entry_var[self.count].setText("") - except: - print "Error when set text of Device Model JFET " - except: + except BaseException: + print("Error when set text of Device\ + Model JFET ") + except BaseException: pass jfetgrid.addWidget(self.entry_var[self.count], self.row, 1) self.addbtn = QtGui.QPushButton("Add") - self.addbtn.setObjectName("%d" %self.count) + self.addbtn.setObjectName("%d" % self.count) self.addbtn.clicked.connect(self.trackLibrary) self.deviceDetail[self.count] = words[0] @@ -198,65 +233,75 @@ class DeviceModel(QtGui.QWidget): jfetgrid.addWidget(self.addbtn, self.row, 2) jfetbox.setLayout(jfetgrid) - - #CSS + + # CSS jfetbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius:\ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(jfetbox) - - #Adding Device Details - #Increment row and widget count + + # Adding Device Details + # Increment row and widget count self.row = self.row + 1 self.devicemodel_dict_end[words[0]] = self.count self.count = self.count + 1 - + elif eachline[0] == 'm': self.devicemodel_dict_beg[words[0]] = self.count mosfetbox = QtGui.QGroupBox() mosfetgrid = QtGui.QGridLayout() i = self.count beg = self.count - mosfetbox.setTitle("Add library for MOSFET "+words[0]+" : "+words[5]) + mosfetbox.setTitle( + "Add library for MOSFET " + + words[0] + + " : " + + words[5]) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") mosfetgrid.addWidget(self.entry_var[self.count], self.row, 1) self.addbtn = QtGui.QPushButton("Add") - self.addbtn.setObjectName("%d" %self.count) + self.addbtn.setObjectName("%d" % self.count) self.addbtn.clicked.connect(self.trackLibrary) mosfetgrid.addWidget(self.addbtn, self.row, 2) - - #Adding Device Details + + # Adding Device Details self.deviceDetail[self.count] = words[0] - - #Increment row and widget count + + # Increment row and widget count self.row = self.row + 1 self.count = self.count + 1 - - #Adding to get MOSFET dimension - self.widthLabel[self.count] = QtGui.QLabel("Enter width of MOSFET "+words[0]+"(default=100u):") + + # Adding to get MOSFET dimension + self.widthLabel[self.count] = QtGui.QLabel( + "Enter width of MOSFET " + words[0] + "(default=100u):") mosfetgrid.addWidget(self.widthLabel[self.count], self.row, 0) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") self.entry_var[self.count].setMaximumWidth(150) mosfetgrid.addWidget(self.entry_var[self.count], self.row, 1) self.row = self.row + 1 - self.count = self.count+1 - - self.lengthLabel[self.count] = QtGui.QLabel("Enter length of MOSFET "+words[0]+"(default=100u):") + self.count = self.count + 1 + + self.lengthLabel[self.count] = QtGui.QLabel( + "Enter length of MOSFET " + words[0] + "(default=100u):") mosfetgrid.addWidget(self.lengthLabel[self.count], self.row, 0) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") self.entry_var[self.count].setMaximumWidth(150) mosfetgrid.addWidget(self.entry_var[self.count], self.row, 1) self.row = self.row + 1 - self.count = self.count+1 - - - self.multifactorLable[self.count] = QtGui.QLabel("Enter multiplicative factor of MOSFET "+words[0]+"(default=1):") - mosfetgrid.addWidget(self.multifactorLable[self.count], self.row, 0) + self.count = self.count + 1 + + self.multifactorLable[self.count] = QtGui.QLabel( + "Enter multiplicative factor of MOSFET " + + words[0] + "(default=1):") + mosfetgrid.addWidget( + self.multifactorLable[self.count], self.row, 0) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") end = self.count @@ -264,96 +309,111 @@ class DeviceModel(QtGui.QWidget): mosfetgrid.addWidget(self.entry_var[self.count], self.row, 1) self.row = self.row + 1 self.devicemodel_dict_end[words[0]] = self.count - self.count = self.count+1 + self.count = self.count + 1 mosfetbox.setLayout(mosfetgrid) - #global path_name + # global path_name try: for key in json_data["deviceModel"]: if key[0] == eachline[0] and key[1] == eachline[1]: - #print "DEVICE MODEL MATCHING---",child.tag[0],child.tag[1],eachline[0],eachline[1] + # print "DEVICE MODEL MATCHING---",child.tag[0],\ + # child.tag[1],eachline[0],eachline[1] while i <= end: - self.entry_var[i].setText(json_data["deviceModel"][key][i-beg]) - if (i-beg) == 0: - if os.path.exists(json_data["deviceModel"][key][0]): - path_name = json_data["deviceModel"][key][0] + self.entry_var[i].setText( + json_data["deviceModel"][key][i - beg]) + if (i - beg) == 0: + if os.path.exists( + json_data["deviceModel"][key][0]): + path_name = json_data + ["deviceModel"][key][0] else: self.entry_var[i].setText("") i = i + 1 - except: + except BaseException: pass - #CSS + # CSS mosfetbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius:\ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") if self.entry_var[beg].text() == "": pass else: self.trackLibraryWithoutButton(beg, path_name) - + self.grid.addWidget(mosfetbox) - - + self.show() - - + def trackLibrary(self): """ This function is use to keep track of all Device Model widget """ - print "Calling Track Device Model Library funtion" + print("Calling Track Device Model Library funtion") sending_btn = self.sender() - #print "Object Called is ",sending_btn.objectName() + # print "Object Called is ",sending_btn.objectName() self.widgetObjCount = int(sending_btn.objectName()) - - self.libfile = str(QtGui.QFileDialog.getOpenFileName(self,"Open Library Directory","../deviceModelLibrary","*.lib")) - #print "Selected Library File :",self.libfile - - #Setting Library to Text Edit Line + + self.libfile = str( + QtGui.QFileDialog.getOpenFileName( + self, + "Open Library Directory", + "../deviceModelLibrary", + "*.lib")) + # print "Selected Library File :",self.libfile + + # Setting Library to Text Edit Line self.entry_var[self.widgetObjCount].setText(self.libfile) self.deviceName = self.deviceDetail[self.widgetObjCount] - - #Storing to track it during conversion - - + + # Storing to track it during conversion + if self.deviceName[0] == 'm': - width = str(self.entry_var[self.widgetObjCount+1].text()) - length = str(self.entry_var[self.widgetObjCount+2].text()) - multifactor = str(self.entry_var[self.widgetObjCount+3].text()) - if width == "" : width="100u" - if length == "": length="100u" - if multifactor == "": multifactor="1" - - self.obj_trac.deviceModelTrack[self.deviceName] = self.libfile+":"+"W="+width+" L="+length+" M="+multifactor - + width = str(self.entry_var[self.widgetObjCount + 1].text()) + length = str(self.entry_var[self.widgetObjCount + 2].text()) + multifactor = str(self.entry_var[self.widgetObjCount + 3].text()) + if width == "": + width = "100u" + if length == "": + length = "100u" + if multifactor == "": + multifactor = "1" + + self.obj_trac.deviceModelTrack[self.deviceName] = self.libfile + \ + ":" + "W=" + width + " L=" + length + " M=" + multifactor + else: self.obj_trac.deviceModelTrack[self.deviceName] = self.libfile - def trackLibraryWithoutButton(self,iter_value,path_value): + + def trackLibraryWithoutButton(self, iter_value, path_value): """ This function is use to keep track of all Device Model widget """ - print "Calling Track Library function Without Button" - #print "Object Called is ",sending_btn.objectName() + print("Calling Track Library function Without Button") + # print "Object Called is ",sending_btn.objectName() self.widgetObjCount = iter_value - print "self.widgetObjCount-----",self.widgetObjCount + print("self.widgetObjCount-----", self.widgetObjCount) self.libfile = path_value - #print "Selected Library File :",self.libfile + # print "Selected Library File :",self.libfile - #Setting Library to Text Edit Line + # Setting Library to Text Edit Line self.entry_var[self.widgetObjCount].setText(self.libfile) self.deviceName = self.deviceDetail[self.widgetObjCount] - #Storing to track it during conversion - + # Storing to track it during conversion if self.deviceName[0] == 'm': - width = str(self.entry_var[self.widgetObjCount+1].text()) - length = str(self.entry_var[self.widgetObjCount+2].text()) - multifactor = str(self.entry_var[self.widgetObjCount+3].text()) - if width == "" : width="100u" - if length == "": length="100u" - if multifactor == "": multifactor="1" - self.obj_trac.deviceModelTrack[self.deviceName] = self.libfile+":"+"W="+width+" L="+length+" M="+multifactor + width = str(self.entry_var[self.widgetObjCount + 1].text()) + length = str(self.entry_var[self.widgetObjCount + 2].text()) + multifactor = str(self.entry_var[self.widgetObjCount + 3].text()) + if width == "": + width = "100u" + if length == "": + length = "100u" + if multifactor == "": + multifactor = "1" + self.obj_trac.deviceModelTrack[self.deviceName] = self.libfile + \ + ":" + "W=" + width + " L=" + length + " M=" + multifactor else: self.obj_trac.deviceModelTrack[self.deviceName] = self.libfile - diff --git a/src/kicadtoNgspice/KicadtoNgspice.py b/src/kicadtoNgspice/KicadtoNgspice.py index eaa9592e..2f9b0400 100644 --- a/src/kicadtoNgspice/KicadtoNgspice.py +++ b/src/kicadtoNgspice/KicadtoNgspice.py @@ -1,191 +1,199 @@ -#=============================================================================== +# ========================================================================= # # FILE: kicadtoNgspice.py -# -# USAGE: --- -# -# DESCRIPTION: This define all configuration used in Application. -# +# +# USAGE: --- +# +# DESCRIPTION: This define all configuration used in Application. +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 04 March 2015 +# CREATED: Wednesday 04 March 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= import sys import os from PyQt4 import QtGui -from Processing import PrcocessNetlist -import Analysis -import Source -import Model -import DeviceModel -import SubcircuitTab -import Convert -import TrackWidget +from .Processing import PrcocessNetlist +from . import Analysis +from . import Source +from . import Model +from . import DeviceModel +from . import SubcircuitTab +from . import Convert +from . import TrackWidget import json -#from xml.etree import ElementTree as ET - +# from xml.etree import ElementTree as ET class MainWindow(QtGui.QWidget): """ - This class create KicadtoNgspice window. + This class create KicadtoNgspice window. And Call Convert function if convert button is pressed. - The convert function takes all the value entered by user and create a final netlist "*.cir.out". - This final netlist is compatible with NgSpice. + The convert function takes all the value entered by user and create + a final netlist "*.cir.out". + This final netlist is compatible with NgSpice. """ - def __init__(self,clarg1,clarg2=None): + + def __init__(self, clarg1, clarg2=None): QtGui.QWidget.__init__(self) - - print "==================================" - print "Kicad to Ngspice netlist converter " - print "==================================" - global kicadNetlist,schematicInfo - global infoline,optionInfo + print("==================================") + print("Kicad to Ngspice netlist converter ") + print("==================================") + global kicadNetlist, schematicInfo + global infoline, optionInfo self.kicadFile = clarg1 - self.clarg1=clarg1 - self.clarg2=clarg2 - - #Create object of track widget + self.clarg1 = clarg1 + self.clarg2 = clarg2 + + # Create object of track widget self.obj_track = TrackWidget.TrackWidget() - - #Clear Dictionary/List item of sub circuit and ngspice model - #Dictionary + + # Clear Dictionary/List item of sub circuit and ngspice model + # Dictionary self.obj_track.subcircuitList.clear() self.obj_track.subcircuitTrack.clear() self.obj_track.model_entry_var.clear() - #List - self.obj_track.modelTrack[:]=[] - - #Object of Processing + # List + self.obj_track.modelTrack[:] = [] + + # Object of Processing obj_proc = PrcocessNetlist() - + # Read the netlist kicadNetlist = obj_proc.readNetlist(self.kicadFile) - - print "Given Kicad Schematic Netlist Info :",kicadNetlist - + + print("Given Kicad Schematic Netlist Info :", kicadNetlist) + # Construct parameter information param = obj_proc.readParamInfo(kicadNetlist) - + # Replace parameter with values - netlist,infoline = obj_proc.preprocessNetlist(kicadNetlist,param) - - print "Schematic Info after processing Kicad Netlist: ",netlist - #print "INFOLINE",infoline - + netlist, infoline = obj_proc.preprocessNetlist(kicadNetlist, param) + + print("Schematic Info after processing Kicad Netlist: ", netlist) + # print "INFOLINE",infoline + # Separate option and schematic information optionInfo, schematicInfo = obj_proc.separateNetlistInfo(netlist) - - print "OPTIONINFO in the Netlist",optionInfo - - #List for storing source and its value + + print("OPTIONINFO in the Netlist", optionInfo) + + # List for storing source and its value global sourcelist, sourcelisttrack - sourcelist=[] - sourcelisttrack=[] - schematicInfo,sourcelist = obj_proc.insertSpecialSourceParam(schematicInfo,sourcelist) - - #List storing model detail - global modelList,outputOption,unknownModelList,multipleModelList,plotText - - modelList = [] + sourcelist = [] + sourcelisttrack = [] + schematicInfo, sourcelist = obj_proc.insertSpecialSourceParam( + schematicInfo, sourcelist) + + # List storing model detail + global modelList, outputOption, unknownModelList, \ + multipleModelList, plotText + + modelList = [] outputOption = [] plotText = [] - schematicInfo,outputOption,modelList,unknownModelList,multipleModelList,plotText = obj_proc.convertICintoBasicBlocks(schematicInfo,outputOption,modelList,plotText) - - print "Model available in the Schematic :",modelList + schematicInfo, outputOption, modelList, unknownModelList, + multipleModelList, plotText = obj_proc.convertICintoBasicBlocks( + schematicInfo, outputOption, modelList, plotText) - + print("Model available in the Schematic :", modelList) + + """ + Checking if any unknown model is used in schematic which is not + recognized by NgSpice. + Also if the two model of same name is present under + modelParamXML directory """ - Checking if any unknown model is used in schematic which is not recognized by NgSpice. - Also if the two model of same name is present under modelParamXML directory - """ if unknownModelList: - print "Unknown Model List is : ",unknownModelList + print("Unknown Model List is : ", unknownModelList) self.msg = QtGui.QErrorMessage() - self.content = "Your schematic contain unknown model "+', '.join(unknownModelList) + self.content = "Your schematic contain unknown model " + \ + ', '.join(unknownModelList) self.msg.showMessage(self.content) self.msg.setWindowTitle("Unknown Models") - + elif multipleModelList: self.msg = QtGui.QErrorMessage() - self.mcontent = "Look like you have duplicate model in modelParamXML directory "+', '.join(multipleModelList[0]) + self.mcontent = "Look like you have duplicate model in \ + modelParamXML directory " + \ + ', '.join(multipleModelList[0]) self.msg.showMessage(self.mcontent) self.msg.setWindowTitle("Multiple Models") - + else: self.createMainWindow() - - + def createMainWindow(self): """ This function create main window of Kicad to Ngspice converter """ - + self.vbox = QtGui.QVBoxLayout(self) - self.hbox=QtGui.QHBoxLayout(self) + self.hbox = QtGui.QHBoxLayout(self) self.hbox.addStretch(1) self.convertbtn = QtGui.QPushButton("Convert") self.convertbtn.clicked.connect(self.callConvert) self.hbox.addWidget(self.convertbtn) self.vbox.addWidget(self.createcreateConvertWidget()) self.vbox.addLayout(self.hbox) - + self.setLayout(self.vbox) self.setWindowTitle("Kicad To NgSpice Converter") self.show() - + def createcreateConvertWidget(self): global obj_analysis self.convertWindow = QtGui.QWidget() self.analysisTab = QtGui.QScrollArea() - obj_analysis=Analysis.Analysis(self.clarg1) + obj_analysis = Analysis.Analysis(self.clarg1) self.analysisTab.setWidget(obj_analysis) - #self.analysisTabLayout = QtGui.QVBoxLayout(self.analysisTab.widget()) + # self.analysisTabLayout = QtGui.QVBoxLayout(self.analysisTab.widget()) self.analysisTab.setWidgetResizable(True) global obj_source self.sourceTab = QtGui.QScrollArea() - obj_source=Source.Source(sourcelist,sourcelisttrack,self.clarg1) + obj_source = Source.Source(sourcelist, sourcelisttrack, self.clarg1) self.sourceTab.setWidget(obj_source) - #self.sourceTabLayout = QtGui.QVBoxLayout(self.sourceTab.widget()) + # self.sourceTabLayout = QtGui.QVBoxLayout(self.sourceTab.widget()) self.sourceTab.setWidgetResizable(True) global obj_model self.modelTab = QtGui.QScrollArea() - obj_model=Model.Model(schematicInfo,modelList,self.clarg1) + obj_model = Model.Model(schematicInfo, modelList, self.clarg1) self.modelTab.setWidget(obj_model) - #self.modelTabLayout = QtGui.QVBoxLayout(self.modelTab.widget()) + # self.modelTabLayout = QtGui.QVBoxLayout(self.modelTab.widget()) self.modelTab.setWidgetResizable(True) global obj_devicemodel self.deviceModelTab = QtGui.QScrollArea() - obj_devicemodel=DeviceModel.DeviceModel(schematicInfo,self.clarg1) + obj_devicemodel = DeviceModel.DeviceModel(schematicInfo, self.clarg1) self.deviceModelTab.setWidget(obj_devicemodel) self.deviceModelTab.setWidgetResizable(True) global obj_subcircuitTab self.subcircuitTab = QtGui.QScrollArea() - obj_subcircuitTab = SubcircuitTab.SubcircuitTab(schematicInfo,self.clarg1) + obj_subcircuitTab = SubcircuitTab.SubcircuitTab( + schematicInfo, self.clarg1) self.subcircuitTab.setWidget(obj_subcircuitTab) self.subcircuitTab.setWidgetResizable(True) self.tabWidget = QtGui.QTabWidget() - #self.tabWidget.TabShape(QtGui.QTabWidget.Rounded) - self.tabWidget.addTab(self.analysisTab,"Analysis") - self.tabWidget.addTab(self.sourceTab,"Source Details") - self.tabWidget.addTab(self.modelTab,"NgSpice Model") - self.tabWidget.addTab(self.deviceModelTab,"Device Modeling") - self.tabWidget.addTab(self.subcircuitTab,"Subcircuits") + # self.tabWidget.TabShape(QtGui.QTabWidget.Rounded) + self.tabWidget.addTab(self.analysisTab, "Analysis") + self.tabWidget.addTab(self.sourceTab, "Source Details") + self.tabWidget.addTab(self.modelTab, "NgSpice Model") + self.tabWidget.addTab(self.deviceModelTab, "Device Modeling") + self.tabWidget.addTab(self.subcircuitTab, "Subcircuits") self.mainLayout = QtGui.QVBoxLayout() self.mainLayout.addWidget(self.tabWidget) - #self.mainLayout.addStretch(1) + # self.mainLayout.addStretch(1) self.convertWindow.setLayout(self.mainLayout) self.convertWindow.show() - - return self.convertWindow - + + return self.convertWindow + def callConvert(self): """ Calling Convert Class Constructor @@ -194,20 +202,23 @@ class MainWindow(QtGui.QWidget): global analysisoutput global kicad store_schematicInfo = list(schematicInfo) - (projpath,filename) = os.path.split(self.kicadFile) + (projpath, filename) = os.path.split(self.kicadFile) project_name = os.path.basename(projpath) - - - fw = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'w') - json_data = {} + fw = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'w') + json_data = {} """ Writing Analysis values """ json_data["analysis"] = {} - + json_data["analysis"]["ac"] = {} if obj_analysis.Lin.isChecked(): json_data["analysis"]["ac"]["Lin"] = "true" @@ -223,44 +234,69 @@ class MainWindow(QtGui.QWidget): json_data["analysis"]["ac"]["Oct"] = "true" else: pass - - json_data["analysis"]["ac"]["Start Frequency"] = str(obj_analysis.ac_entry_var[0].text()) - json_data["analysis"]["ac"]["Stop Frequency"] = str(obj_analysis.ac_entry_var[1].text()) - json_data["analysis"]["ac"]["No. of points"] = str(obj_analysis.ac_entry_var[2].text()) - json_data["analysis"]["ac"]["Start Fre Combo"] = obj_analysis.ac_parameter[0] - json_data["analysis"]["ac"]["Stop Fre Combo"] = obj_analysis.ac_parameter[1] + + json_data["analysis"]["ac"]["Start Frequency"] = str( + obj_analysis.ac_entry_var[0].text()) + json_data["analysis"]["ac"]["Stop Frequency"] = str( + obj_analysis.ac_entry_var[1].text()) + json_data["analysis"]["ac"]["No. of points"] = str( + obj_analysis.ac_entry_var[2].text()) + json_data + ["analysis"]["ac"]["Start Fre Combo"] = obj_analysis.ac_parameter[0] + json_data + ["analysis"]["ac"]["Stop Fre Combo"] = obj_analysis.ac_parameter[1] json_data["analysis"]["dc"] = {} - json_data["analysis"]["dc"]["Source 1"] = str(obj_analysis.dc_entry_var[0].text()) - json_data["analysis"]["dc"]["Start"] = str(obj_analysis.dc_entry_var[1].text()) - json_data["analysis"]["dc"]["Increment"] = str(obj_analysis.dc_entry_var[2].text()) - json_data["analysis"]["dc"]["Stop"] = str(obj_analysis.dc_entry_var[3].text()) - json_data["analysis"]["dc"]["Operating Point"] = str(self.obj_track.op_check[-1]) - json_data["analysis"]["dc"]["Start Combo"] = obj_analysis.dc_parameter[0] - json_data["analysis"]["dc"]["Increment Combo"] = obj_analysis.dc_parameter[1] - json_data["analysis"]["dc"]["Stop Combo"] = obj_analysis.dc_parameter[2] - json_data["analysis"]["dc"]["Source 2"] = str(obj_analysis.dc_entry_var[4].text()) - json_data["analysis"]["dc"]["Start2"] = str(obj_analysis.dc_entry_var[5].text()) - json_data["analysis"]["dc"]["Increment2"] = str(obj_analysis.dc_entry_var[6].text()) - json_data["analysis"]["dc"]["Stop2"] = str(obj_analysis.dc_entry_var[7].text()) - json_data["analysis"]["dc"]["Start Combo2"] = obj_analysis.dc_parameter[3] - json_data["analysis"]["dc"]["Increment Combo2"] = obj_analysis.dc_parameter[4] - json_data["analysis"]["dc"]["Stop Combo2"] = obj_analysis.dc_parameter[5] + json_data["analysis"]["dc"]["Source 1"] = str( + obj_analysis.dc_entry_var[0].text()) + json_data["analysis"]["dc"]["Start"] = str( + obj_analysis.dc_entry_var[1].text()) + json_data["analysis"]["dc"]["Increment"] = str( + obj_analysis.dc_entry_var[2].text()) + json_data["analysis"]["dc"]["Stop"] = str( + obj_analysis.dc_entry_var[3].text()) + json_data["analysis"]["dc"]["Operating Point"] = str( + self.obj_track.op_check[-1]) + json_data + ["analysis"]["dc"]["Start Combo"] = obj_analysis.dc_parameter[0] + json_data + ["analysis"]["dc"]["Increment Combo"] = obj_analysis.dc_parameter[1] + json_data + ["analysis"]["dc"]["Stop Combo"] = obj_analysis.dc_parameter[2] + json_data["analysis"]["dc"]["Source 2"] = str( + obj_analysis.dc_entry_var[4].text()) + json_data["analysis"]["dc"]["Start2"] = str( + obj_analysis.dc_entry_var[5].text()) + json_data["analysis"]["dc"]["Increment2"] = str( + obj_analysis.dc_entry_var[6].text()) + json_data["analysis"]["dc"]["Stop2"] = str( + obj_analysis.dc_entry_var[7].text()) + json_data + ["analysis"]["dc"]["Start Combo2"] = obj_analysis.dc_parameter[3] + json_data + ["analysis"]["dc"]["Increment Combo2"] = obj_analysis.dc_parameter[4] + json_data + ["analysis"]["dc"]["Stop Combo2"] = obj_analysis.dc_parameter[5] json_data["analysis"]["tran"] = {} - json_data["analysis"]["tran"]["Start Time"] = str(obj_analysis.tran_entry_var[0].text()) - json_data["analysis"]["tran"]["Step Time"] = str(obj_analysis.tran_entry_var[1].text()) - json_data["analysis"]["tran"]["Stop Time"] = str(obj_analysis.tran_entry_var[2].text()) - json_data["analysis"]["tran"]["Start Combo"] = obj_analysis.tran_parameter[0] - json_data["analysis"]["tran"]["Step Combo"] = obj_analysis.tran_parameter[1] - json_data["analysis"]["tran"]["Stop Combo"] = obj_analysis.tran_parameter[2] - + json_data["analysis"]["tran"]["Start Time"] = str( + obj_analysis.tran_entry_var[0].text()) + json_data["analysis"]["tran"]["Step Time"] = str( + obj_analysis.tran_entry_var[1].text()) + json_data["analysis"]["tran"]["Stop Time"] = str( + obj_analysis.tran_entry_var[2].text()) + json_data + ["analysis"]["tran"]["Start Combo"] = obj_analysis.tran_parameter[0] + json_data + ["analysis"]["tran"]["Step Combo"] = obj_analysis.tran_parameter[1] + json_data + ["analysis"]["tran"]["Stop Combo"] = obj_analysis.tran_parameter[2] """ Writing Source values """ - json_data["source"] = {} + json_data["source"] = {} count = 1 for line in store_schematicInfo: @@ -269,10 +305,10 @@ class MainWindow(QtGui.QWidget): if wordv[0] == "v" or wordv[0] == "i": json_data["source"][wordv] = {} - json_data["source"][wordv]["type"] = words[len(words)-1] + json_data["source"][wordv]["type"] = words[len(words) - 1] json_data["source"][wordv]["values"] = [] - if words[len(words)-1] == "ac": + if words[len(words) - 1] == "ac": amp = {"Amplitude": str(obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(amp) @@ -281,13 +317,15 @@ class MainWindow(QtGui.QWidget): count += 1 json_data["source"][wordv]["values"].append(phase) - elif words[len(words)-1] == "dc": + elif words[len(words) - 1] == "dc": value = {"Value": str(obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(value) - elif words[len(words)-1] == "sine": - offset = {"Offset Value": str(obj_source.entry_var[count].text())} + elif words[len(words) - 1] == "sine": + offset = { + "Offset Value": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(offset) @@ -303,16 +341,22 @@ class MainWindow(QtGui.QWidget): count += 1 json_data["source"][wordv]["values"].append(delay) - damp = {"Damping Factor": str(obj_source.entry_var[count].text())} + damp = { + "Damping Factor": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(damp) - elif words[len(words)-1] == "pulse": - initial = {"Initial Value": str(obj_source.entry_var[count].text())} + elif words[len(words) - 1] == "pulse": + initial = { + "Initial Value": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(initial) - pulse = {"Pulse Value": str(obj_source.entry_var[count].text())} + pulse = { + "Pulse Value": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(pulse) @@ -328,7 +372,9 @@ class MainWindow(QtGui.QWidget): count += 1 json_data["source"][wordv]["values"].append(fall) - width = {"Pulse width": str(obj_source.entry_var[count].text())} + width = { + "Pulse width": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(width) @@ -336,21 +382,29 @@ class MainWindow(QtGui.QWidget): count += 1 json_data["source"][wordv]["values"].append(period) - elif words[len(words)-1]=="pwl": - pwl = {"Enter in pwl format": str(obj_source.entry_var[count].text())} + elif words[len(words) - 1] == "pwl": + pwl = { + "Enter in pwl format": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(pwl) - elif words[len(words)-1]=="exp": - initial = {"Initial Value": str(obj_source.entry_var[count].text())} + elif words[len(words) - 1] == "exp": + initial = { + "Initial Value": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(initial) - pulsed = {"Pulsed Value": str(obj_source.entry_var[count].text())} + pulsed = { + "Pulsed Value": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(pulsed) - rise = {"Rise Delay Time": str(obj_source.entry_var[count].text())} + rise = { + "Rise Delay Time": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(rise) @@ -358,19 +412,20 @@ class MainWindow(QtGui.QWidget): count += 1 json_data["source"][wordv]["values"].append(fall) - fallConstant = {"Fall Time Constant": str(obj_source.entry_var[count].text())} + fallConstant = { + "Fall Time Constant": str( + obj_source.entry_var[count].text())} count += 1 json_data["source"][wordv]["values"].append(fallConstant) else: pass - """ Writing Model values """ - i = 0 + i = 0 json_data["model"] = {} for line in modelList: @@ -378,269 +433,293 @@ class MainWindow(QtGui.QWidget): if rand_itr[2] == line[2] and rand_itr[3] == line[3]: start = rand_itr[7] end = rand_itr[8] - i = start - + i = start + json_data["model"][line[3]] = {} json_data["model"][line[3]]["type"] = line[2] - json_data["model"][line[3]]["values"] = [] - - for key, value in line[7].iteritems(): + json_data["model"][line[3]]["values"] = [] + + for key, value in line[7].items(): if hasattr(value, '__iter__') and i <= end: for item in value: - fields = {item: str(obj_model.obj_trac.model_entry_var[i].text())} + fields = { + item: str( + obj_model.obj_trac.model_entry_var[i].text())} json_data["model"][line[3]]["values"].append(fields) i = i + 1 - + else: - fields = {value: str(obj_model.obj_trac.model_entry_var[i].text())} + fields = { + value: str( + obj_model.obj_trac.model_entry_var[i].text())} json_data["model"][line[3]]["values"].append(fields) i = i + 1 - """ Writing Device Model values """ - json_data["deviceModel"] = {} - + json_data["deviceModel"] = {} + for device in obj_devicemodel.devicemodel_dict_beg: json_data["deviceModel"][device] = [] it = obj_devicemodel.devicemodel_dict_beg[device] end = obj_devicemodel.devicemodel_dict_end[device] while it <= end: - json_data["deviceModel"][device].append(str(obj_devicemodel.entry_var[it].text())) + json_data["deviceModel"][device].append( + str(obj_devicemodel.entry_var[it].text())) it = it + 1 - """ Writing Subcircuit values """ - json_data["subcircuit"] = {} + json_data["subcircuit"] = {} for subckt in obj_subcircuitTab.subcircuit_dict_beg: json_data["subcircuit"][subckt] = [] it = obj_subcircuitTab.subcircuit_dict_beg[subckt] end = obj_subcircuitTab.subcircuit_dict_end[subckt] while it <= end: - json_data["subcircuit"][subckt].append(str(obj_subcircuitTab.entry_var[it].text())) + json_data["subcircuit"][subckt].append( + str(obj_subcircuitTab.entry_var[it].text())) it = it + 1 write_data = json.dumps(json_data) fw.write(write_data) - - - self.obj_convert = Convert.Convert(self.obj_track.sourcelisttrack["ITEMS"], - self.obj_track.source_entry_var["ITEMS"], - store_schematicInfo,self.clarg1) - + + self.obj_convert = Convert.Convert( + self.obj_track.sourcelisttrack["ITEMS"], + self.obj_track.source_entry_var["ITEMS"], + store_schematicInfo, self.clarg1 + ) + try: - #Adding Source Value to Schematic Info + # Adding Source Value to Schematic Info store_schematicInfo = self.obj_convert.addSourceParameter() - print "Netlist After Adding Source details :",store_schematicInfo - - #Adding Model Value to store_schematicInfo - store_schematicInfo = self.obj_convert.addModelParameter(store_schematicInfo) - print "Netlist After Adding Ngspice Model :",store_schematicInfo - - #Adding Device Library to SchematicInfo - store_schematicInfo = self.obj_convert.addDeviceLibrary(store_schematicInfo,self.kicadFile) - print "Netlist After Adding Device Model Library :",store_schematicInfo - - #Adding Subcircuit Library to SchematicInfo - store_schematicInfo = self.obj_convert.addSubcircuit(store_schematicInfo, self.kicadFile) - print "Netlist After Adding subcircuits :",store_schematicInfo - - analysisoutput = self.obj_convert.analysisInsertor(self.obj_track.AC_entry_var["ITEMS"], - self.obj_track.DC_entry_var["ITEMS"], - self.obj_track.TRAN_entry_var["ITEMS"], - self.obj_track.set_CheckBox["ITEMS"], - self.obj_track.AC_Parameter["ITEMS"], - self.obj_track.DC_Parameter["ITEMS"], - self.obj_track.TRAN_Parameter["ITEMS"], - self.obj_track.AC_type["ITEMS"], - self.obj_track.op_check) - - print "Analysis OutPut ",analysisoutput - - #Calling netlist file generation function - self.createNetlistFile(store_schematicInfo,plotText) - - self.msg = "The Kicad to Ngspice Conversion completed successfully!" - QtGui.QMessageBox.information(self, "Information", self.msg, QtGui.QMessageBox.Ok) - + print("Netlist After Adding Source details :", store_schematicInfo) + + # Adding Model Value to store_schematicInfo + store_schematicInfo = self.obj_convert.addModelParameter( + store_schematicInfo) + print("Netlist After Adding Ngspice Model :", store_schematicInfo) + + # Adding Device Library to SchematicInfo + store_schematicInfo = self.obj_convert.addDeviceLibrary( + store_schematicInfo, self.kicadFile) + print( + "Netlist After Adding Device Model Library :", + store_schematicInfo) + + # Adding Subcircuit Library to SchematicInfo + store_schematicInfo = self.obj_convert.addSubcircuit( + store_schematicInfo, self.kicadFile) + print("Netlist After Adding subcircuits :", store_schematicInfo) + + analysisoutput = self.obj_convert.analysisInsertor( + self.obj_track.AC_entry_var["ITEMS"], + self.obj_track.DC_entry_var["ITEMS"], + self.obj_track.TRAN_entry_var["ITEMS"], + self.obj_track.set_CheckBox["ITEMS"], + self.obj_track.AC_Parameter["ITEMS"], + self.obj_track.DC_Parameter["ITEMS"], + self.obj_track.TRAN_Parameter["ITEMS"], + self.obj_track.AC_type["ITEMS"], + self.obj_track.op_check + ) + + print("Analysis OutPut ", analysisoutput) + + # Calling netlist file generation function + self.createNetlistFile(store_schematicInfo, plotText) + + self.msg = "The Kicad to Ngspice Conversion completed\ + successfully!" + QtGui.QMessageBox.information( + self, "Information", self.msg, QtGui.QMessageBox.Ok) + except Exception as e: - print "Exception Message: ",e - print "There was error while converting kicad to ngspice" + print("Exception Message: ", e) + print("There was error while converting kicad to ngspice") self.close() - + # Generate .sub file from .cir.out file if it is a subcircuit subPath = os.path.splitext(self.kicadFile)[0] - + if self.clarg2 == "sub": self.createSubFile(subPath) - - def createNetlistFile(self,store_schematicInfo,plotText): - print "Creating Final netlist" - #print "INFOLINE",infoline - #print "OPTIONINFO",optionInfo - #print "Device MODEL LIST ",devicemodelList - #print "SUBCKT ",subcktList - #print "OUTPUTOPTION",outputOption - #print "KicadfIle",kicadFile - store_optionInfo = list(optionInfo) #To avoid writing optionInfo twice in final netlist - - #checking if analysis files is present - (projpath,filename) = os.path.split(self.kicadFile) - analysisFileLoc = os.path.join(projpath,"analysis") - #print "Analysis File Location",analysisFileLoc + + def createNetlistFile(self, store_schematicInfo, plotText): + print("Creating Final netlist") + # print "INFOLINE",infoline + # print "OPTIONINFO",optionInfo + # print "Device MODEL LIST ",devicemodelList + # print "SUBCKT ",subcktList + # print "OUTPUTOPTION",outputOption + # print "KicadfIle",kicadFile + # To avoid writing optionInfo twice in final netlist + store_optionInfo = list(optionInfo) + + # checking if analysis files is present + (projpath, filename) = os.path.split(self.kicadFile) + analysisFileLoc = os.path.join(projpath, "analysis") + # print "Analysis File Location",analysisFileLoc if os.path.exists(analysisFileLoc): try: f = open(analysisFileLoc) - #Read data + # Read data data = f.read() # Close the file f.close() - except : - print "Error While opening Project Analysis file. Please check it" + except BaseException: + print("Error While opening Project Analysis file.\ + Please check it") sys.exit() else: - print analysisFileLoc + " does not exist" + print(analysisFileLoc + " does not exist") sys.exit() - - #Adding analysis file info to optionInfo - analysisData=data.splitlines() + + # Adding analysis file info to optionInfo + analysisData = data.splitlines() for eachline in analysisData: - eachline=eachline.strip() - if len(eachline)>1: - if eachline[0]=='.': + eachline = eachline.strip() + if len(eachline) > 1: + if eachline[0] == '.': store_optionInfo.append(eachline) else: pass - - #print "Option Info",optionInfo + + # print "Option Info",optionInfo analysisOption = [] - initialCondOption=[] - simulatorOption =[] - #includeOption=[] #Don't know why to use it - #model = [] #Don't know why to use it - + initialCondOption = [] + simulatorOption = [] + # includeOption=[] # Don't know why to use it + # model = [] # Don't know why to use it + for eachline in store_optionInfo: - words=eachline.split() - option=words[0] - if (option=='.ac' or option=='.dc' or option=='.disto' or option=='.noise' or - option=='.op' or option=='.pz' or option=='.sens' or option=='.tf' or - option=='.tran'): - analysisOption.append(eachline+'\n') - - elif (option=='.save' or option=='.print' or option=='.plot' or option=='.four'): - eachline=eachline.strip('.') - outputOption.append(eachline+'\n') - elif (option=='.nodeset' or option=='.ic'): - initialCondOption.append(eachline+'\n') - elif option=='.option': - simulatorOption.append(eachline+'\n') - #elif (option=='.include' or option=='.lib'): + words = eachline.split() + option = words[0] + if (option == '.ac' or option == '.dc' or option == + '.disto' or option == '.noise' or + option == '.op' or option == '.pz' or option == + '.sens' or option == '.tf' or + option == '.tran'): + analysisOption.append(eachline + '\n') + + elif (option == '.save' or option == '.print' or option == + '.plot' or option == '.four'): + eachline = eachline.strip('.') + outputOption.append(eachline + '\n') + elif (option == '.nodeset' or option == '.ic'): + initialCondOption.append(eachline + '\n') + elif option == '.option': + simulatorOption.append(eachline + '\n') + # elif (option=='.include' or option=='.lib'): # includeOption.append(eachline+'\n') - #elif (option=='.model'): + # elif (option=='.model'): # model.append(eachline+'\n') - elif option=='.end': - continue; - - - #Start creating final netlist cir.out file - outfile = self.kicadFile+".out" - out=open(outfile,"w") + elif option == '.end': + continue + + # Start creating final netlist cir.out file + outfile = self.kicadFile + ".out" + out = open(outfile, "w") out.writelines(infoline) out.writelines('\n') - sections=[simulatorOption, initialCondOption, store_schematicInfo, analysisOption] - + sections = [ + simulatorOption, + initialCondOption, + store_schematicInfo, + analysisOption] + for section in sections: if len(section) == 0: continue else: for line in section: - out.writelines('\n') + out.writelines('\n') out.writelines(line) - + out.writelines('\n* Control Statements \n') out.writelines('.control\n') out.writelines('run\n') - #out.writelines(outputOption) + # out.writelines(outputOption) out.writelines('print allv > plot_data_v.txt\n') out.writelines('print alli > plot_data_i.txt\n') for item in plotText: - out.writelines(item+'\n') + out.writelines(item + '\n') out.writelines('.endc\n') out.writelines('.end\n') out.close() - - - - def createSubFile(self,subPath): + + def createSubFile(self, subPath): self.project = subPath self.projName = os.path.basename(self.project) - if os.path.exists(self.project+".cir.out"): + if os.path.exists(self.project + ".cir.out"): try: - f = open(self.project+".cir.out") - except : + f = open(self.project + ".cir.out") + except BaseException: print("Error in opening .cir.out file.") else: - print self.projName + ".cir.out does not exist. Please create a spice netlist." - + print( + self.projName + + ".cir.out does not exist. Please create a spice netlist.") + # Read the data from file - data=f.read() + data = f.read() # Close the file - + f.close() - newNetlist=[] - netlist=iter(data.splitlines()) + newNetlist = [] + netlist = iter(data.splitlines()) for eachline in netlist: - eachline=eachline.strip() - if len(eachline)<1: + eachline = eachline.strip() + if len(eachline) < 1: continue - words=eachline.split() + words = eachline.split() if eachline[2] == 'u': - if words[len(words)-1] == "port": - subcktInfo = ".subckt "+self.projName+" " - for i in range(2,len(words)-1): - subcktInfo+=words[i]+" " + if words[len(words) - 1] == "port": + subcktInfo = ".subckt " + self.projName + " " + for i in range(2, len(words) - 1): + subcktInfo += words[i] + " " continue - if words[0] == ".end" or words[0] == ".ac" or words[0] == ".dc" or words[0] == ".tran" or words[0] == '.disto' or words[0] == '.noise' or words[0] == '.op' or words[0] == '.pz' or words[0] == '.sens' or words[0] == '.tf': + if( + words[0] == ".end" or + words[0] == ".ac" or + words[0] == ".dc" or + words[0] == ".tran" or + words[0] == '.disto' or + words[0] == '.noise' or + words[0] == '.op' or + words[0] == '.pz' or + words[0] == '.sens' or + words[0] == '.tf' + ): continue elif words[0] == ".control": while words[0] != ".endc": - eachline=netlist.next() - eachline=eachline.strip() - if len(eachline)<1: + eachline = next(netlist) + eachline = eachline.strip() + if len(eachline) < 1: continue - words=eachline.split() + words = eachline.split() else: newNetlist.append(eachline) - - outfile=self.project+".sub" - out=open(outfile,"w") + + outfile = self.project + ".sub" + out = open(outfile, "w") out.writelines("* Subcircuit " + self.projName) out.writelines('\n') out.writelines(subcktInfo) out.writelines('\n') - - for i in range(len(newNetlist),0,-1): - newNetlist.insert(i,'\n') - + + for i in range(len(newNetlist), 0, -1): + newNetlist.insert(i, '\n') + out.writelines(newNetlist) - out.writelines('\n') - + out.writelines('\n') + out.writelines('.ends ' + self.projName) - print "The subcircuit has been written in "+self.projName+".sub" - - - - - - - - - + print("The subcircuit has been written in " + self.projName + ".sub") diff --git a/src/kicadtoNgspice/Model.py b/src/kicadtoNgspice/Model.py index 11d65c03..7ae41791 100644 --- a/src/kicadtoNgspice/Model.py +++ b/src/kicadtoNgspice/Model.py @@ -1,79 +1,91 @@ from PyQt4 import QtGui import json -import TrackWidget -#from xml.etree import ElementTree as ET +from . import TrackWidget +# from xml.etree import ElementTree as ET import os class Model(QtGui.QWidget): """ - This class creates Model Tab of KicadtoNgspice window. + This class creates Model Tab of KicadtoNgspice window. The widgets are created dynamically in the Model Tab. """ - - def __init__(self,schematicInfo,modelList,clarg1): - + + def __init__(self, schematicInfo, modelList, clarg1): + QtGui.QWidget.__init__(self) - - #Processing for getting previous values + + # Processing for getting previous values kicadFile = clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path.basename(projpath) try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: - print "Model Previous Values JSON is Empty" - - - - #Creating track widget object + except BaseException: + print("Model Previous Values JSON is Empty") + + # Creating track widget object self.obj_trac = TrackWidget.TrackWidget() - - #for increasing row and counting/tracking line edit widget + + # for increasing row and counting/tracking line edit widget self.nextrow = 0 self.nextcount = 0 - - #for storing line edit details position details + + # for storing line edit details position details self.start = 0 self.end = 0 - - #Creating GUI dynamically for Model tab + + # Creating GUI dynamically for Model tab self.grid = QtGui.QGridLayout() self.setLayout(self.grid) - + for line in modelList: - #print "ModelList Item:",line - #Adding title label for model - #Key: Tag name,Value:Entry widget number - tag_dict = {} + # print "ModelList Item:",line + # Adding title label for model + # Key: Tag name,Value:Entry widget number + tag_dict = {} modelbox = QtGui.QGroupBox() modelgrid = QtGui.QGridLayout() modelbox.setTitle(line[5]) self.start = self.nextcount - #line[7] is parameter dictionary holding parameter tags. + # line[7] is parameter dictionary holding parameter tags. i = 0 - for key,value in line[7].iteritems(): - #print "Key : ",key - #print "Value : ",value - #Check if value is iterable + for key, value in line[7].items(): + # print "Key : ",key + # print "Value : ",value + # Check if value is iterable if hasattr(value, '__iter__'): - #For tag having vector value + # For tag having vector value temp_tag = [] for item in value: paramLabel = QtGui.QLabel(item) modelgrid.addWidget(paramLabel, self.nextrow, 0) - self.obj_trac.model_entry_var[self.nextcount] = QtGui.QLineEdit() - modelgrid.addWidget(self.obj_trac.model_entry_var[self.nextcount], self.nextrow, 1) + self.obj_trac.model_entry_var + [self.nextcount] = QtGui.QLineEdit( + ) + modelgrid.addWidget( + self.obj_trac.model_entry_var + [self.nextcount], self.nextrow, 1) try: for mod in json_data["model"]: - if json_data["model"][mod]["type"] == line[2] and mod == line[3]: - self.obj_trac.model_entry_var[self.nextcount].setText(str(json_data["model"][mod]["values"][i].values()[0])) + if json_data["model"][mod]["type"] ==\ + line[2] and mod == line[3]: + self.obj_trac.model_entry_var + [self.nextcount].setText( + str(list( + json_data["model"][mod]["values"] + [i].values())[0])) i = i + 1 - except: + except BaseException: pass temp_tag.append(self.nextcount) @@ -84,35 +96,46 @@ class Model(QtGui.QWidget): else: paramLabel = QtGui.QLabel(value) modelgrid.addWidget(paramLabel, self.nextrow, 0) - self.obj_trac.model_entry_var[self.nextcount] = QtGui.QLineEdit() - modelgrid.addWidget(self.obj_trac.model_entry_var[self.nextcount], self.nextrow, 1) + self.obj_trac.model_entry_var + [self.nextcount] = QtGui.QLineEdit( + ) + modelgrid.addWidget( + self.obj_trac.model_entry_var + [self.nextcount], self.nextrow, 1) try: for mod in json_data["model"]: - if json_data["model"][mod]["type"] == line[2] and mod == line[3]: - self.obj_trac.model_entry_var[self.nextcount].setText(str(json_data["model"][mod]["values"][i].values()[0])) + if json_data["model"][mod]["type"] ==\ + line[2] and mod == line[3]: + self.obj_trac.model_entry_var + [self.nextcount].setText( + str(list(json_data + ["model"][mod]["values"] + [i].values())[0])) i = i + 1 - except: - pass + except BaseException: + pass tag_dict[key] = self.nextcount self.nextcount = self.nextcount + 1 self.nextrow = self.nextrow + 1 self.end = self.nextcount - 1 - #print "End",self.end + # print "End",self.end modelbox.setLayout(modelgrid) - - #CSS + + # CSS modelbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(modelbox) - + ''' - Listing all + Listing all line[0] = index line[1] = compLine line[2] = modelname #Change from compType to modelname @@ -120,22 +143,30 @@ class Model(QtGui.QWidget): line[4] = comment line[5] = title line[6] = type i.e analog or digital - Now adding start,end and tag_dict which will be line[7],line[8] and line[9] respectively + Now adding start,end and tag_dict which will be line[7], + line[8] and line[9] respectively ''' - - #This keeps the track of Model Tab Widget - lst = [line[0], line[1], line[2], line[3], line[4], line[5], line[6], self.start, self.end, tag_dict] + + # This keeps the track of Model Tab Widget + lst = [ + line[0], + line[1], + line[2], + line[3], + line[4], + line[5], + line[6], + self.start, + self.end, + tag_dict] check = 0 for itr in self.obj_trac.modelTrack: if itr == lst: - check = 1 - - if check == 0: + check = 1 + + if check == 0: self.obj_trac.modelTrack.append(lst) - - #print "The tag dictionary : ",tag_dict - - - + + # print "The tag dictionary : ",tag_dict + self.show() - diff --git a/src/kicadtoNgspice/Processing.py b/src/kicadtoNgspice/Processing.py index 09544f19..63847761 100644 --- a/src/kicadtoNgspice/Processing.py +++ b/src/kicadtoNgspice/Processing.py @@ -3,378 +3,449 @@ import os from xml.etree import ElementTree as ET - class PrcocessNetlist: """ - This class include all the function required for pre-proccessing of netlist + This class include all the function required for pre-proccessing of netlist before converting to Ngspice Netlist. """ modelxmlDIR = '../modelParamXML' + def __init__(self): pass - - def readNetlist(self,filename): + + def readNetlist(self, filename): f = open(filename) - data=f.read() + data = f.read() f.close() return data.splitlines() - def readParamInfo(self,kicadNetlis): + def readParamInfo(self, kicadNetlis): """Read Parameter information and store it into dictionary""" - param={} + param = {} for eachline in kicadNetlis: - print eachline - eachline=eachline.strip() - if len(eachline)>1: - words=eachline.split() - option=words[0].lower() - if option=='.param': + print(eachline) + eachline = eachline.strip() + if len(eachline) > 1: + words = eachline.split() + option = words[0].lower() + if option == '.param': for i in range(1, len(words), 1): - paramList=words[i].split('=') - param[paramList[0]]=paramList[1] + paramList = words[i].split('=') + param[paramList[0]] = paramList[1] return param - - def preprocessNetlist(self,kicadNetlis,param): + + def preprocessNetlist(self, kicadNetlis, param): """Preprocess netlist (replace parameters)""" - netlist=[] + netlist = [] for eachline in kicadNetlis: - # Remove leading and trailing blanks spaces from line - eachline=eachline.strip() + # Remove leading and trailing blanks spaces from line + eachline = eachline.strip() # Remove special character $ - eachline=eachline.replace('$','') + eachline = eachline.replace('$', '') # Replace parameter with values for subParam in eachline.split(): if '}' in subParam: - key=subParam.split()[0] - key=key.strip('{') - key=key.strip('}') + key = subParam.split()[0] + key = key.strip('{') + key = key.strip('}') if key in param: - eachline=eachline.replace('{'+key+'}',param[key]) + eachline = eachline.replace( + '{' + key + '}', param[key]) else: - print "Parameter " + key +" does not exists" - value=raw_input('Enter parameter value: ') - eachline=eachline.replace('{'+key+'}',value) - #Convert netlist into lower case letter - eachline=eachline.lower() + print("Parameter " + key + " does not exists") + value = input('Enter parameter value: ') + eachline = eachline.replace('{' + key + '}', value) + # Convert netlist into lower case letter + eachline = eachline.lower() # Construct netlist - if len(eachline)>1: - if eachline[0]=='+': - netlist.append(netlist.pop()+eachline.replace('+',' ')) + if len(eachline) > 1: + if eachline[0] == '+': + netlist.append(netlist.pop() + eachline.replace('+', ' ')) else: netlist.append(eachline) - #Copy information line - infoline=netlist[0] + # Copy information line + infoline = netlist[0] netlist.remove(netlist[0]) - return netlist,infoline - - def separateNetlistInfo(self,netlist): - optionInfo=[] - schematicInfo=[] + return netlist, infoline + + def separateNetlistInfo(self, netlist): + optionInfo = [] + schematicInfo = [] for eachline in netlist: - if eachline[0]=='*': + if eachline[0] == '*': continue - elif eachline[0]=='.': + elif eachline[0] == '.': optionInfo.append(eachline) else: schematicInfo.append(eachline) - return optionInfo,schematicInfo - - - def insertSpecialSourceParam(self,schematicInfo,sourcelist): - #Inser Special source parameter - schematicInfo1=[] - - print "Reading schematic info for source details" - + return optionInfo, schematicInfo + + def insertSpecialSourceParam(self, schematicInfo, sourcelist): + # Inser Special source parameter + schematicInfo1 = [] + + print("Reading schematic info for source details") + for compline in schematicInfo: - words=compline.split() - compName=words[0] + words = compline.split() + compName = words[0] # Ask for parameters of source - if compName[0]=='v' or compName[0]=='i': + if compName[0] == 'v' or compName[0] == 'i': # Find the index component from circuit - index=schematicInfo.index(compline) - if words[3]=="pulse": - Title="Add parameters for pulse source "+compName - v1=' Enter initial value(Volts/Amps): ' - v2=' Enter pulsed value(Volts/Amps): ' - td=' Enter delay time (seconds): ' - tr=' Enter rise time (seconds): ' - tf=' Enter fall time (seconds): ' - pw=' Enter pulse width (seconds): ' - tp=' Enter period (seconds): ' - sourcelist.append([index,compline,words[3],Title,v1,v2,td,tr,tf,pw,tp]) - - elif words[3]=="sine": - Title="Add parameters for sine source "+compName - vo=' Enter offset value (Volts/Amps): ' - va=' Enter amplitude (Volts/Amps): ' - freq=' Enter frequency (Hz): ' - td=' Enter delay time (seconds): ' - theta=' Enter damping factor (1/seconds): ' - sourcelist.append([index,compline,words[3],Title,vo,va,freq,td,theta]) - - elif words[3]=="pwl": - Title="Add parameters for pwl source "+compName - t_v=' Enter in pwl format without bracket i.e t1 v1 t2 v2.... ' - sourcelist.append([index,compline,words[3],Title,t_v]) - - elif words[3]=="ac": - Title="Add parameters for ac source "+compName - v_a=' Enter amplitude (Volts/Amps): ' - p_a =' Enter Phase Shift: ' - sourcelist.append([index,compline,words[3],Title,v_a,p_a]) - - elif words[3]=="exp": - Title="Add parameters for exponential source "+compName - v1=' Enter initial value(Volts/Amps): ' - v2=' Enter pulsed value(Volts/Amps): ' - td1=' Enter rise delay time (seconds): ' - tau1=' Enter rise time constant (seconds): ' - td2=' Enter fall time (seconds): ' - tau2=' Enter fall time constant (seconds): ' - sourcelist.append([index,compline,words[3],Title,v1,v2,td1,tau1,td2,tau2]) - - elif words[3]=="dc": - Title="Add parameters for DC source "+compName - v1=' Enter value(Volts/Amps): ' - v2=' Enter zero frequency: ' - sourcelist.append([index,compline,words[3],Title,v1,v2]) - - elif compName[0]=='h' or compName[0]=='f': + index = schematicInfo.index(compline) + if words[3] == "pulse": + Title = "Add parameters for pulse source " + compName + v1 = ' Enter initial value(Volts/Amps): ' + v2 = ' Enter pulsed value(Volts/Amps): ' + td = ' Enter delay time (seconds): ' + tr = ' Enter rise time (seconds): ' + tf = ' Enter fall time (seconds): ' + pw = ' Enter pulse width (seconds): ' + tp = ' Enter period (seconds): ' + sourcelist.append( + [index, compline, words[3], + Title, v1, v2, td, tr, tf, pw, tp]) + + elif words[3] == "sine": + Title = "Add parameters for sine source " + compName + vo = ' Enter offset value (Volts/Amps): ' + va = ' Enter amplitude (Volts/Amps): ' + freq = ' Enter frequency (Hz): ' + td = ' Enter delay time (seconds): ' + theta = ' Enter damping factor (1/seconds): ' + sourcelist.append( + [index, compline, words[3], + Title, vo, va, freq, td, theta]) + + elif words[3] == "pwl": + Title = "Add parameters for pwl source " + compName + t_v = ' Enter in pwl format without bracket\ + i.e t1 v1 t2 v2.... ' + sourcelist.append([index, compline, words[3], Title, t_v]) + + elif words[3] == "ac": + Title = "Add parameters for ac source " + compName + v_a = ' Enter amplitude (Volts/Amps): ' + p_a = ' Enter Phase Shift: ' + sourcelist.append( + [index, compline, words[3], Title, v_a, p_a]) + + elif words[3] == "exp": + Title = "Add parameters for exponential source " + compName + v1 = ' Enter initial value(Volts/Amps): ' + v2 = ' Enter pulsed value(Volts/Amps): ' + td1 = ' Enter rise delay time (seconds): ' + tau1 = ' Enter rise time constant (seconds): ' + td2 = ' Enter fall time (seconds): ' + tau2 = ' Enter fall time constant (seconds): ' + sourcelist.append( + [index, compline, words[3], + Title, v1, v2, td1, tau1, td2, tau2]) + + elif words[3] == "dc": + Title = "Add parameters for DC source " + compName + v1 = ' Enter value(Volts/Amps): ' + v2 = ' Enter zero frequency: ' + sourcelist.append( + [index, compline, words[3], Title, v1, v2]) + + elif compName[0] == 'h' or compName[0] == 'f': # Find the index component from the circuit - index=schematicInfo.index(compline) + index = schematicInfo.index(compline) schematicInfo.remove(compline) - schematicInfo.insert(index,"* "+compName) - schematicInfo1.append("V"+compName+" "+words[3]+" "+words[4]+" 0") - schematicInfo1.append(compName+" "+words[1]+" "+words[2]+" "+"V"+compName+" "+words[5]) - - schematicInfo=schematicInfo+schematicInfo1 - print "Source List : ",sourcelist - #print schematicInfo - return schematicInfo,sourcelist - - - def convertICintoBasicBlocks(self,schematicInfo,outputOption,modelList,plotText): - print "Reading Schematic info for Model" - #Insert details of Ngspice model + schematicInfo.insert(index, "* " + compName) + schematicInfo1.append( + "V" + compName + " " + words[3] + " " + words[4] + " 0") + schematicInfo1.append( + compName + + " " + + words[1] + + " " + + words[2] + + " " + + "V" + + compName + + " " + + words[5]) + + schematicInfo = schematicInfo + schematicInfo1 + print("Source List : ", sourcelist) + # print schematicInfo + return schematicInfo, sourcelist + + def convertICintoBasicBlocks( + self, schematicInfo, outputOption, modelList, plotText): + print("Reading Schematic info for Model") + # Insert details of Ngspice model unknownModelList = [] multipleModelList = [] - plotList = ['plot_v1','plot_v2','plot_i2','plot_log','plot_db','plot_phase'] - interMediateNodeCount=1 + plotList = [ + 'plot_v1', + 'plot_v2', + 'plot_i2', + 'plot_log', + 'plot_db', + 'plot_phase'] + interMediateNodeCount = 1 k = 1 for compline in schematicInfo: words = compline.split() compName = words[0] - #print "Compline----------------->",compline - #print "compName-------------->",compName - # Find the IC from schematic - if compName[0]=='u' or compName[0] == 'U': + # print "Compline----------------->",compline + # print "compName-------------->",compName + # Find the IC from schematic + if compName[0] == 'u' or compName[0] == 'U': # Find the component from the circuit - index=schematicInfo.index(compline) - compType=words[len(words)-1]; + index = schematicInfo.index(compline) + compType = words[len(words) - 1] schematicInfo.remove(compline) paramDict = {} - #e.g compLine : u1 1 2 gain - #compType : gain - #compName : u1 - #print "Compline",compline - #print "CompType",compType - #print "Words",words - #print "compName",compName - #Looking if model file is present - if compType != "port" and compType != "ic" and compType not in plotList and compType != 'transfo': - xmlfile = compType+".xml" #XML Model File - count = 0 #Check if model of same name is present + # e.g compLine : u1 1 2 gain + # compType : gain + # compName : u1 + # print "Compline",compline + # print "CompType",compType + # print "Words",words + # print "compName",compName + # Looking if model file is present + if compType != "port" and compType != "ic" and \ + compType not in plotList and \ + compType != 'transfo': + xmlfile = compType + ".xml" # XML Model File + count = 0 # Check if model of same name is present modelPath = [] - all_dir = [x[0] for x in os.walk(PrcocessNetlist.modelxmlDIR)] + all_dir = [x[0] + for x in os.walk(PrcocessNetlist.modelxmlDIR)] for each_dir in all_dir: all_file = os.listdir(each_dir) if xmlfile in all_file: count += 1 - modelPath.append(os.path.join(each_dir,xmlfile)) - + modelPath.append(os.path.join(each_dir, xmlfile)) + if count > 1: multipleModelList.append(modelPath) elif count == 0: unknownModelList.append(compType) elif count == 1: try: - print "Start Parsing Previous Values XML for ngspice model :",modelPath + print( + "Start Parsing Previous Values XML\ + for ngspice model :", modelPath) tree = ET.parse(modelPath[0]) - - root = tree.getroot() - #Getting number of nodes for model and title + + # Getting number of nodes for model and title for child in tree.iter(): if child.tag == 'node_number': num_of_nodes = int(child.text) elif child.tag == 'title': - title = child.text+" "+compName + title = child.text + " " + compName elif child.tag == 'name': modelname = child.text elif child.tag == 'type': - #Checking for Analog and Digital + # Checking for Analog and Digital type = child.text elif child.tag == 'split': splitDetail = child.text - - + for param in tree.findall('param'): for item in param: - #print "Tags ",item.tag - #print "Value",item.text + # print "Tags ",item.tag + # print "Value",item.text if 'vector'in item.attrib: - #print "Tag having vector attribute",item.tag,item.attrib['vector'] + # print "Tag having vector attribute",\ + # item.tag,item.attrib['vector'] temp_count = 1 temp_list = [] - for i in range(0,int(item.attrib['vector'])): - temp_list.append(item.text+" "+str(temp_count)) + for i in range(0, int( + item.attrib['vector'])): + temp_list.append( + item.text + " " + str( + temp_count)) temp_count += 1 if 'default' in item.attrib: - paramDict[item.tag+":"+item.attrib['default']] = temp_list + paramDict[item.tag + ":" + + item.attrib['default']] \ + = temp_list else: paramDict[item.tag] = item.text - + else: if 'default' in item.attrib: - paramDict[item.tag+":"+item.attrib['default']] = item.text + paramDict[item.tag + ":" + + item.attrib['default']]\ + = item.text else: paramDict[item.tag] = item.text - - - #print "Number of Nodes : ",num_of_nodes - #print "Title : ",title - #print "Parameters",paramDict - #Creating line for adding model line in schematic + + # print "Number of Nodes : ",num_of_nodes + # print "Title : ",title + # print "Parameters",paramDict + # Creating line for adding model line in schematic if splitDetail == 'None': - modelLine = "a"+str(k)+" " - for i in range(1,num_of_nodes+1): - modelLine += words[i]+" " + modelLine = "a" + str(k) + " " + for i in range(1, num_of_nodes + 1): + modelLine += words[i] + " " modelLine += compName - + else: - print "Split Details :",splitDetail - modelLine = "a"+str(k)+" " + print("Split Details :", splitDetail) + modelLine = "a" + str(k) + " " vectorDetail = splitDetail.split(':') - #print "Vector Details",vectorDetail - pos = 1 #Node position + # print "Vector Details",vectorDetail + pos = 1 # Node position for item in vectorDetail: try: if item.split("-")[1] == 'V': - #print "Vector" + # print "Vector" if compType == "aswitch": modelLine += "(" - for i in range(0,int(item.split("-")[0])): - modelLine += words[pos]+" " + for i in range(0, int( + item.split("-")[0])): + modelLine += words[pos] +\ + " " pos += 1 modelLine += ") " else: modelLine += "[" - for i in range(0,int(item.split("-")[0])): - modelLine += words[pos]+" " + for i in range(0, int( + item.split("-")[0])): + modelLine += words[pos] + \ + " " pos += 1 - modelLine += "] " + modelLine += "] " elif item.split("-")[1] == 'NV': - #print "Non Vector" - for i in range(0,int(item.split("-")[0])): - modelLine += words[pos]+" " + # print "Non Vector" + for i in range(0, int( + item.split("-")[0])): + modelLine += words[pos] + " " pos += 1 - - except: - print "There is error while processing Vector Details" + + except BaseException: + print( + "There is error while processing\ + Vector Details") sys.exit(2) - modelLine += compName - - #print "Final Model Line :",modelLine + modelLine += compName + + # print "Final Model Line :",modelLine try: schematicInfo.append(modelLine) - k=k+1 + k = k + 1 except Exception as e: - print "Error while appending ModelLine ",modelLine - print "Exception Message : ",str(e) - #Insert comment at remove line - schematicInfo.insert(index,"* "+compline) - comment = "* Schematic Name: "+compType+", NgSpice Name: "+modelname - #Here instead of adding compType(use for XML), added modelName(Unique Model Name) - modelList.append([index,compline,modelname,compName,comment,title,type,paramDict]) + print( + "Error while appending \ + ModelLine ", modelLine) + print("Exception Message : ", str(e)) + # Insert comment at remove line + schematicInfo.insert(index, "* " + compline) + comment = "* Schematic Name:\ + " + compType + ", NgSpice Name: " + modelname + # Here instead of adding compType(use for XML), + # added modelName(Unique Model Name) + modelList.append( + [index, compline, modelname, compName, + comment, title, type, paramDict]) except Exception as e: - print "Unable to parse the model, Please check your your XML file" - print "Exception Message : ",str(e) + print( + "Unable to parse the model, \ + Please check your your XML file") + print("Exception Message : ", str(e)) sys.exit(2) elif compType == "ic": - schematicInfo.insert(index,"* "+compline) + schematicInfo.insert(index, "* " + compline) modelname = "ic" - comment = "* "+compline - title = "Initial Condition for "+compName - type = "NA" #Its is not model - text = "Enter initial voltage at node for "+compline + comment = "* " + compline + title = "Initial Condition for " + compName + type = "NA" # Its is not model + text = "Enter initial voltage at node for " + compline paramDict[title] = text - modelList.append([index,compline,modelname,compName,comment,title,type,paramDict]) - + modelList.append( + [index, compline, modelname, compName, + comment, title, type, paramDict]) + elif compType in plotList: - schematicInfo.insert(index,"* "+compline) + schematicInfo.insert(index, "* " + compline) if compType == 'plot_v1': words = compline.split() - plotText.append("plot v("+words[1]+")") + plotText.append("plot v(" + words[1] + ")") elif compType == 'plot_v2': words = compline.split() - plotText.append("plot v("+words[1]+","+words[2]+")") + plotText.append( + "plot v(" + words[1] + "," + words[2] + ")") elif compType == 'plot_i2': words = compline.split() - #Adding zero voltage source to netlist - schematicInfo.append("v_"+words[0]+" "+words[1]+" "+words[2]+" "+"0") - plotText.append("plot i(v_"+words[0]+")") + # Adding zero voltage source to netlist + schematicInfo.append( + "v_" + words[0] + " " + + words[1] + " " + words[2] + " " + "0") + plotText.append("plot i(v_" + words[0] + ")") elif compType == 'plot_log': words = compline.split() - plotText.append("plot log("+words[1]+")") + plotText.append("plot log(" + words[1] + ")") elif compType == 'plot_db': words = compline.split() - plotText.append("plot db("+words[1]+")") + plotText.append("plot db(" + words[1] + ")") elif compType == 'plot_phase': words = compline.split() - plotText.append("plot phase("+words[1]+")") - + plotText.append("plot phase(" + words[1] + ")") + elif compType == 'transfo': - schematicInfo.insert(index,"* "+compline) - - #For Primary Couple - modelLine = "a"+str(k)+" ("+words[1]+" "+words[2]+") (interNode_"+str(interMediateNodeCount)+" "+words[3]+") " - modelLine += compName+"_primary" + schematicInfo.insert(index, "* " + compline) + + # For Primary Couple + modelLine = "a" + str(k) + + " (" + words[1] + " " + words[2] + ") (interNode_" + str( + interMediateNodeCount) + " " + words[3] + ") " + modelLine += compName + "_primary" schematicInfo.append(modelLine) - k=k+1 - #For iron core - modelLine = "a"+str(k)+" ("+words[4]+" "+words[2]+") (interNode_"+str(interMediateNodeCount+1)+" "+words[3]+") " - modelLine += compName+"_secondary" + k = k + 1 + # For iron core + modelLine = "a" + str(k) + " (" + words[4] + " " + words[2] + ") \ + (interNode_" + str( + interMediateNodeCount + 1) + " " + words[3] + ") " + modelLine += compName + "_secondary" schematicInfo.append(modelLine) - k=k+1 - #For Secondary Couple - modelLine = "a"+str(k)+" (interNode_"+str(interMediateNodeCount)+" interNode_"+str(interMediateNodeCount+1)+") " - modelLine += compName+"_iron_core" + k = k + 1 + # For Secondary Couple + modelLine = "a" + str(k) + " (interNode_" + str( + interMediateNodeCount) + " interNode_" + \ + str(interMediateNodeCount + 1) + ") " + modelLine += compName + "_iron_core" schematicInfo.append(modelLine) - k=k+1 + k = k + 1 interMediateNodeCount += 2 - + modelname = "transfo" - comment = "* "+compline - title = "Transformer details for model "+compName - type = "NA" #It is model but do not load from xml and lib file + comment = "* " + compline + title = "Transformer details for model " + compName + type = "NA" + # It is model but do not load from xml and lib file paramDict['h1_array'] = "Enter the H1 array " - paramDict['primary_turns'] = "Enter the primary number of turns (default=310) " + paramDict['primary_turns'] = "Enter the primary number \ + of turns (default=310) " paramDict['area'] = "Enter iron core area (default=1)" - paramDict['secondar_turns'] = "Enter the secondary number of turns (default=620)" - paramDict['length'] = "Enter iron core length (default=0.01)" + paramDict['secondar_turns'] = "Enter the secondary number\ + of turns (default=620)" + paramDict['length'] = "Enter iron core length \ + (default=0.01)" paramDict['b1_array'] = "Enter the B1 array " - - - modelList.append([index,compline,modelname,compName,comment,title,type,paramDict]) - + + modelList.append( + [index, compline, modelname, compName, + comment, title, type, paramDict]) + else: - schematicInfo.insert(index,"* "+compline) - - print "UnknownModelList Used in the Schematic",unknownModelList - print "Multiple Model XML file with same name ",multipleModelList - print "Model List Details : ",modelList - - return schematicInfo,outputOption,modelList,unknownModelList,multipleModelList,plotText - - - + schematicInfo.insert(index, "* " + compline) + + print( + "UnknownModelList Used in the Schematic", + unknownModelList) + print( + "Multiple Model XML file with same name ", + multipleModelList) + print("Model List Details : ", modelList) + + return ( + schematicInfo, outputOption, modelList, unknownModelList, + multipleModelList, plotText + ) diff --git a/src/kicadtoNgspice/Source.py b/src/kicadtoNgspice/Source.py index d66cfa81..8649ce93 100644 --- a/src/kicadtoNgspice/Source.py +++ b/src/kicadtoNgspice/Source.py @@ -1,56 +1,61 @@ import os from PyQt4 import QtGui -import TrackWidget -#from xml.etree import ElementTree as ET +from . import TrackWidget +# from xml.etree import ElementTree as ET import json + class Source(QtGui.QWidget): """ This class create Source Tab of KicadtoNgSpice Window. """ - - def __init__(self,sourcelist,sourcelisttrack,clarg1): + + def __init__(self, sourcelist, sourcelisttrack, clarg1): QtGui.QWidget.__init__(self) - self.obj_track = TrackWidget.TrackWidget() - #Variable + self.obj_track = TrackWidget.TrackWidget() + # Variable self.count = 1 - self.clarg1=clarg1 + self.clarg1 = clarg1 self.start = 0 self.end = 0 self.row = 0 self.entry_var = {} - #self.font = QtGui.QFont("Times",20,QtGui.QFont.Bold,True) - - #Creating Source Widget - self.createSourceWidget(sourcelist,sourcelisttrack) - - - - def createSourceWidget(self,sourcelist,sourcelisttrack): + # self.font = QtGui.QFont("Times",20,QtGui.QFont.Bold,True) + + # Creating Source Widget + self.createSourceWidget(sourcelist, sourcelisttrack) + + def createSourceWidget(self, sourcelist, sourcelisttrack): """ - This function dynamically create source widget in the Source tab of KicadtoNgSpice window + This function dynamically create source widget in the + Source tab of KicadtoNgSpice window """ kicadFile = self.clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path.basename(projpath) try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: - print "Source Previous Values JSON is Empty" - + except BaseException: + print("Source Previous Values JSON is Empty") + self.grid = QtGui.QGridLayout() self.setLayout(self.grid) - + if sourcelist: for line in sourcelist: - #print "Voltage source line index: ",line[0] - print "SourceList line: ",line - track_id=line[0] - #print "track_id is ",track_id + # print "Voltage source line index: ",line[0] + print("SourceList line: ", line) + track_id = line[0] + # print "track_id is ",track_id if line[2] == 'ac': acbox = QtGui.QGroupBox() acbox.setTitle(line[3]) @@ -69,7 +74,8 @@ class Source(QtGui.QWidget): self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setMaximumWidth(150) - acgrid.addWidget(self.entry_var[self.count], self.row + 1, 1) + acgrid.addWidget( + self.entry_var[self.count], self.row + 1, 1) self.entry_var[self.count].setText("") self.count += 1 @@ -77,30 +83,41 @@ class Source(QtGui.QWidget): for key in json_data["source"]: templist1 = line[1] templist2 = templist1.split(' ') - - if key==templist2[0] and json_data["source"][key]["type"]==line[2]: - self.entry_var[self.count-2].setText(str(json_data["source"][key]["values"][0]["Amplitude"])) - self.entry_var[self.count-1].setText(str(json_data["source"][key]["values"][1]["Phase"])) - except: + if key == templist2[0] and \ + json_data["source"][key]["type"]\ + == line[2]: + self.entry_var[self.count - 2].setText( + str( + json_data + ["source"][key]["values"][0] + ["Amplitude"])) + self.entry_var[self.count - 1].setText( + str( + json_data["source"][key] + ["values"][1]["Phase"])) + + except BaseException: pass - #Value Need to check previuouse value - #self.entry_var[self.count].setText("") + # Value Need to check previuouse value + # self.entry_var[self.count].setText("") self.row = self.row + 1 self.end = self.count + 1 self.count = self.count + 1 acbox.setLayout(acgrid) - - #CSS + + # CSS acbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius:\ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(acbox) - sourcelisttrack.append([track_id, 'ac', self.start, self.end]) - - + sourcelisttrack.append( + [track_id, 'ac', self.start, self.end]) + elif line[2] == 'dc': dcbox = QtGui.QGroupBox() dcbox.setTitle(line[3]) @@ -119,65 +136,82 @@ class Source(QtGui.QWidget): templist1 = line[1] templist2 = templist1.split(' ') - if key == templist2[0] and json_data["source"][key]["type"] == line[2]: - self.entry_var[self.count].setText(str(json_data["source"][key]["values"][0]["Value"])) + if key == templist2[0] and \ + json_data["source"][key]["type"]\ + == line[2]: + self.entry_var[self.count].setText( + str( + json_data["source"][key] + ["values"][0]["Value"])) - except: + except BaseException: pass - + self.row = self.row + 1 self.end = self.count self.count = self.count + 1 dcbox.setLayout(dcgrid) - - #CSS + + # CSS dcbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius:\ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(dcbox) - sourcelisttrack.append([track_id, 'dc', self.start, self.end]) - + sourcelisttrack.append( + [track_id, 'dc', self.start, self.end]) + elif line[2] == 'sine': sinebox = QtGui.QGroupBox() sinebox.setTitle(line[3]) sinegrid = QtGui.QGridLayout() - self.row = self.row+1 + self.row = self.row + 1 self.start = self.count - + for it in range(4, 9): label = QtGui.QLabel(line[it]) sinegrid.addWidget(label, self.row, 0) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setMaximumWidth(150) - sinegrid.addWidget(self.entry_var[self.count], self.row, 1) + sinegrid.addWidget( + self.entry_var[self.count], self.row, 1) self.entry_var[self.count].setText("") try: for key in json_data["source"]: templist1 = line[1] templist2 = templist1.split(' ') - if key == templist2[0] and json_data["source"][key]["type"] == line[2]: - self.entry_var[self.count].setText(str(json_data["source"][key]["values"][it-4].values()[0])) - except: + if key == templist2[0] and \ + json_data["source"][key]["type"]\ + == line[2]: + self.entry_var[self.count].setText( + str( + list(json_data["source"] + [key]["values"] + [it - 4].values())[0])) + except BaseException: pass - - + self.row = self.row + 1 - self.count = self.count + 1 + self.count = self.count + 1 self.end = self.count - 1 sinebox.setLayout(sinegrid) - - #CSS + + # CSS sinebox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(sinebox) - sourcelisttrack.append([track_id, 'sine', self.start, self.end]) - + sourcelisttrack.append( + [track_id, 'sine', self.start, self.end]) + elif line[2] == 'pulse': pulsebox = QtGui.QGroupBox() pulsebox.setTitle(line[3]) @@ -189,33 +223,42 @@ class Source(QtGui.QWidget): pulsegrid.addWidget(label, self.row, 0) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setMaximumWidth(150) - pulsegrid.addWidget(self.entry_var[self.count], self.row, 1) + pulsegrid.addWidget( + self.entry_var[self.count], self.row, 1) self.entry_var[self.count].setText("") - + try: for key in json_data["source"]: templist1 = line[1] templist2 = templist1.split(' ') - if key == templist2[0] and json_data["source"][key]["type"] == line[2]: - self.entry_var[self.count].setText(str(json_data["source"][key]["values"][it-4].values()[0])) - except: + if key == templist2[0] and \ + json_data["source"][key]["type"]\ + == line[2]: + self.entry_var[self.count].setText( + str(list( + json_data["source"][key] + ["values"][it - 4].values())[0])) + except BaseException: pass - + self.row = self.row + 1 self.count = self.count + 1 self.end = self.count - 1 pulsebox.setLayout(pulsegrid) - - #CSS + + # CSS pulsebox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(pulsebox) - sourcelisttrack.append([track_id, 'pulse', self.start, self.end]) - + sourcelisttrack.append( + [track_id, 'pulse', self.start, self.end]) + elif line[2] == 'pwl': pwlbox = QtGui.QGroupBox() pwlbox.setTitle(line[3]) @@ -227,81 +270,90 @@ class Source(QtGui.QWidget): self.entry_var[self.count].setMaximumWidth(150) pwlgrid.addWidget(self.entry_var[self.count], self.row, 1) self.entry_var[self.count].setText("") - + try: for key in json_data["source"]: templist1 = line[1] templist2 = templist1.split(' ') - if key == templist2[0] and json_data["source"][key]["type"] == line[2]: - self.entry_var[self.count].setText(str(json_data["source"][key]["values"][0]["Enter in pwl format"])) - except: + if key == templist2[0] and \ + json_data["source"][key]["type"] \ + == line[2]: + self.entry_var[self.count].setText( + str(json_data["source"][key] + ["values"][0]["Enter in pwl format"])) + except BaseException: pass - - + self.row = self.row + 1 self.end = self.count self.count = self.count + 1 pwlbox.setLayout(pwlgrid) - - #CSS + + # CSS pwlbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius: \ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(pwlbox) - sourcelisttrack.append([track_id, 'pwl', self.start, self.end]) - + sourcelisttrack.append( + [track_id, 'pwl', self.start, self.end]) + elif line[2] == 'exp': expbox = QtGui.QGroupBox() expbox.setTitle(line[3]) expgrid = QtGui.QGridLayout() self.start = self.count - for it in range(4,10): + for it in range(4, 10): label = QtGui.QLabel(line[it]) expgrid.addWidget(label, self.row, 0) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setMaximumWidth(150) - expgrid.addWidget(self.entry_var[self.count], self.row, 1) + expgrid.addWidget( + self.entry_var[self.count], self.row, 1) self.entry_var[self.count].setText("") - + try: for key in json_data["source"]: templist1 = line[1] templist2 = templist1.split(' ') - if key == templist2[0] and json_data["source"][key]["type"] == line[2]: - self.entry_var[self.count].setText(str(json_data["source"][key]["values"][it-4].values()[0])) - except: + if key == templist2[0] and \ + json_data["source"][key]["type"]\ + == line[2]: + self.entry_var[self.count].setText( + str( + list( + json_data["source"][key] + ["values"][it - 4].values())[0] + ) + ) + except BaseException: pass - - + self.row = self.row + 1 self.count = self.count + 1 self.end = self.count - 1 expbox.setLayout(expgrid) - - #CSS + + # CSS expbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius:\ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left: \ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(expbox) - sourcelisttrack.append([track_id, 'exp', self.start, self.end]) - + sourcelisttrack.append( + [track_id, 'exp', self.start, self.end]) + else: - print "No source is present in your circuit" - - - #This is used to keep the track of dynamically created widget + print("No source is present in your circuit") + + # This is used to keep the track of dynamically created widget self.obj_track.sourcelisttrack["ITEMS"] = sourcelisttrack self.obj_track.source_entry_var["ITEMS"] = self.entry_var self.show() - - - - - - - diff --git a/src/kicadtoNgspice/SubcircuitTab.py b/src/kicadtoNgspice/SubcircuitTab.py index aba2a145..b9c6402b 100644 --- a/src/kicadtoNgspice/SubcircuitTab.py +++ b/src/kicadtoNgspice/SubcircuitTab.py @@ -1,60 +1,66 @@ from PyQt4 import QtGui import json -import TrackWidget +from . import TrackWidget from projManagement import Validation import os -#from xml.etree import ElementTree as ET +# from xml.etree import ElementTree as ET + class SubcircuitTab(QtGui.QWidget): """ This class creates Subcircuit Tab in KicadtoNgspice Window It dynamically creates the widget for subcircuits. """ - + def __init__(self, schematicInfo, clarg1): kicadFile = clarg1 - (projpath,filename) = os.path.split(kicadFile) + (projpath, filename) = os.path.split(kicadFile) project_name = os.path.basename(projpath) try: - f = open(os.path.join(projpath,project_name+"_Previous_Values.json"),'r') + f = open( + os.path.join( + projpath, + project_name + + "_Previous_Values.json"), + 'r') data = f.read() json_data = json.loads(data) - except: - print "Subcircuit Previous values JSON is Empty" + except BaseException: + print("Subcircuit Previous values JSON is Empty") QtGui.QWidget.__init__(self) - - #Creating track widget object + + # Creating track widget object self.obj_trac = TrackWidget.TrackWidget() - - #Creating validation object + + # Creating validation object self.obj_validation = Validation.Validation() - #Row and column count + # Row and column count self.row = 0 - self.count = 1 #Entry count + self.count = 1 # Entry count self.entry_var = {} - self.subcircuit_dict_beg = {} - self.subcircuit_dict_end = {} - #List to hold information about subcircuit + self.subcircuit_dict_beg = {} + self.subcircuit_dict_end = {} + # List to hold information about subcircuit self.subDetail = {} - - #Stores the number of ports in each subcircuit + + # Stores the number of ports in each subcircuit self.numPorts = [] - - #Set Layout + + # Set Layout self.grid = QtGui.QGridLayout() self.setLayout(self.grid) - + for eachline in schematicInfo: words = eachline.split() if eachline[0] == 'x': - print "Subcircuit : Words",words[0] - self.obj_trac.subcircuitList[project_name+words[0]] = words + print(("Subcircuit : Words", words[0])) + self.obj_trac.subcircuitList[project_name + words[0]] = words self.subcircuit_dict_beg[words[0]] = self.count subbox = QtGui.QGroupBox() subgrid = QtGui.QGridLayout() - subbox.setTitle("Add subcircuit for "+words[len(words)-1]) + subbox.setTitle("Add subcircuit for " + words[len(words) - 1]) self.entry_var[self.count] = QtGui.QLineEdit() self.entry_var[self.count].setText("") @@ -62,42 +68,48 @@ class SubcircuitTab(QtGui.QWidget): try: for key in json_data["subcircuit"]: if key[0] == eachline[0] and key[1] == eachline[1]: - #print "Subcircuit MATCHING---",child.tag[0], child.tag[1], eachline[0], eachline[1] + # print "Subcircuit MATCHING---",child.tag[0], \ + # child.tag[1], eachline[0], eachline[1] try: - if os.path.exists(json_data["subcircuit"][key][0]): - self.entry_var[self.count].setText(json_data["subcircuit"][key][0]) + if os.path.exists( + json_data["subcircuit"][key][0]): + self.entry_var[self.count].setText( + json_data["subcircuit"][key][0]) path_name = json_data["subcircuit"][key][0] else: self.entry_var[self.count].setText("") - except: - print "Error when set text of subcircuit" - except: - print "Error before subcircuit" - + except BaseException: + print("Error when set text of subcircuit") + except BaseException: + print("Error before subcircuit") subgrid.addWidget(self.entry_var[self.count], self.row, 1) self.addbtn = QtGui.QPushButton("Add") - self.addbtn.setObjectName("%d" %self.count) - #Send the number of ports specified with the given subcircuit for verification. - #eg. If the line is 'x1 4 0 3 ua741', there are 3 ports(4, 0 and 3). - self.numPorts.append(len(words)-2) - print "Number of ports of sub circuit : ",self.numPorts + self.addbtn.setObjectName("%d" % self.count) + # Send the number of ports specified with the given\ + # subcircuit for verification. + # eg. If the line is 'x1 4 0 3 ua741', there are 3 ports(4, 0 + # and 3). + self.numPorts.append(len(words) - 2) + print(("Number of ports of sub circuit : ", self.numPorts)) self.addbtn.clicked.connect(self.trackSubcircuit) subgrid.addWidget(self.addbtn, self.row, 2) subbox.setLayout(subgrid) - - #CSS + + # CSS subbox.setStyleSheet(" \ - QGroupBox { border: 1px solid gray; border-radius: 9px; margin-top: 0.5em; } \ - QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px; } \ + QGroupBox { border: 1px solid gray; border-radius:\ + 9px; margin-top: 0.5em; } \ + QGroupBox::title { subcontrol-origin: margin; left:\ + 10px; padding: 0 3px 0 3px; } \ ") - + self.grid.addWidget(subbox) - - #Adding Subcircuit Details + + # Adding Subcircuit Details self.subDetail[self.count] = words[0] - - #Increment row and widget count + + # Increment row and widget count if self.entry_var[self.count].text() == "": pass @@ -107,60 +119,71 @@ class SubcircuitTab(QtGui.QWidget): self.subcircuit_dict_end[words[0]] = self.count self.row = self.row + 1 self.count = self.count + 1 - + self.show() - - + def trackSubcircuit(self): """ This function is use to keep track of all Subcircuit widget """ sending_btn = self.sender() - #print "Object Called is ",sending_btn.objectName() + # print "Object Called is ",sending_btn.objectName() self.widgetObjCount = int(sending_btn.objectName()) - - self.subfile = str(QtGui.QFileDialog.getExistingDirectory(self,"Open Subcircuit","../SubcircuitLibrary")) - self.reply = self.obj_validation.validateSub(self.subfile,self.numPorts[self.widgetObjCount - 1]) + + self.subfile = str( + QtGui.QFileDialog.getExistingDirectory( + self, + "Open Subcircuit", + "../SubcircuitLibrary")) + self.reply = self.obj_validation.validateSub( + self.subfile, self.numPorts[self.widgetObjCount - 1]) if self.reply == "True": - #Setting Library to Text Edit Line + # Setting Library to Text Edit Line self.entry_var[self.widgetObjCount].setText(self.subfile) self.subName = self.subDetail[self.widgetObjCount] - - #Storing to track it during conversion - + + # Storing to track it during conversion + self.obj_trac.subcircuitTrack[self.subName] = self.subfile elif self.reply == "PORT": self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage("Please select a Subcircuit with correct number of ports.") + self.msg.showMessage( + "Please select a Subcircuit with correct number of ports.") self.msg.setWindowTitle("Error Message") self.msg.show() elif self.reply == "DIREC": self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage("Please select a valid Subcircuit directory (Containing '.sub' file).") + self.msg.showMessage( + "Please select a valid Subcircuit directory \ + (Containing '.sub' file).") self.msg.setWindowTitle("Error Message") self.msg.show() - def trackSubcircuitWithoutButton(self,iter_value,path_value): - + def trackSubcircuitWithoutButton(self, iter_value, path_value): + self.widgetObjCount = iter_value - + self.subfile = path_value - self.reply = self.obj_validation.validateSub(self.subfile,self.numPorts[self.widgetObjCount - 1]) + self.reply = self.obj_validation.validateSub( + self.subfile, self.numPorts[self.widgetObjCount - 1]) if self.reply == "True": - #Setting Library to Text Edit Line + # Setting Library to Text Edit Line self.entry_var[self.widgetObjCount].setText(self.subfile) self.subName = self.subDetail[self.widgetObjCount] - - #Storing to track it during conversion - + + # Storing to track it during conversion + self.obj_trac.subcircuitTrack[self.subName] = self.subfile elif self.reply == "PORT": self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage("Please select a Subcircuit with correct number of ports.") + self.msg.showMessage( + "Please select a Subcircuit with correct number of ports.") self.msg.setWindowTitle("Error Message") self.msg.show() elif self.reply == "DIREC": self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage("Please select a valid Subcircuit directory (Containing '.sub' file).") + self.msg.showMessage( + "Please select a valid Subcircuit directory \ + (Containing '.sub' file).") self.msg.setWindowTitle("Error Message") self.msg.show()
\ No newline at end of file diff --git a/src/kicadtoNgspice/TrackWidget.py b/src/kicadtoNgspice/TrackWidget.py index 56e84ce3..dcf85dca 100644 --- a/src/kicadtoNgspice/TrackWidget.py +++ b/src/kicadtoNgspice/TrackWidget.py @@ -2,28 +2,28 @@ class TrackWidget: """ This Class track the dynamically created widget of KicadtoNgSpice Window. """ - #Track widget list for Source details - sourcelisttrack = {"ITEMS":"None"} - source_entry_var = {"ITEMS":"None"} - - #Track widget for analysis inserter details - AC_entry_var = {"ITEMS":"None"} - AC_Parameter = {"ITEMS":"None"} - DC_entry_var = {"ITEMS":"None"} - DC_Parameter = {"ITEMS":"None"} - TRAN_entry_var = {"ITEMS":"None"} - TRAN_Parameter = {"ITEMS":"None"} - set_CheckBox = {"ITEMS":"None"} - AC_type = {"ITEMS":"None"} + # Track widget list for Source details + sourcelisttrack = {"ITEMS": "None"} + source_entry_var = {"ITEMS": "None"} + + # Track widget for analysis inserter details + AC_entry_var = {"ITEMS": "None"} + AC_Parameter = {"ITEMS": "None"} + DC_entry_var = {"ITEMS": "None"} + DC_Parameter = {"ITEMS": "None"} + TRAN_entry_var = {"ITEMS": "None"} + TRAN_Parameter = {"ITEMS": "None"} + set_CheckBox = {"ITEMS": "None"} + AC_type = {"ITEMS": "None"} op_check = [] - #Track widget for Model detail + # Track widget for Model detail modelTrack = [] model_entry_var = {} - - #Track Widget for Device Model detail + + # Track Widget for Device Model detail deviceModelTrack = {} - - #Track Widget for Subcircuits where directory has been selected + + # Track Widget for Subcircuits where directory has been selected subcircuitTrack = {} - #Track subcircuits which are specified in .cir file - subcircuitList = {}
\ No newline at end of file + # Track subcircuits which are specified in .cir file + subcircuitList = {} diff --git a/src/modelEditor/ModelEditor.py b/src/modelEditor/ModelEditor.py index 9ad7c662..573e506c 100644 --- a/src/modelEditor/ModelEditor.py +++ b/src/modelEditor/ModelEditor.py @@ -10,10 +10,10 @@ class ModelEditorclass(QtGui.QWidget): QtGui.QWidget.__init__(self) self.savepathtest = '../deviceModelLibrary' self.obj_appconfig = Appconfig() - self.newflag=0 + self.newflag = 0 self.layout = QtGui.QVBoxLayout() - self.splitter= QtGui.QSplitter() - self.grid= QtGui.QGridLayout() + self.splitter = QtGui.QSplitter() + self.grid = QtGui.QGridLayout() self.splitter.setOrientation(QtCore.Qt.Vertical) self.modeltable = QtGui.QTableWidget() @@ -35,15 +35,16 @@ class ModelEditorclass(QtGui.QWidget): self.addbtn.setHidden(True) self.addbtn.clicked.connect(self.addparameters) self.uploadbtn = QtGui.QPushButton('Upload') - self.uploadbtn.setToolTip('<b>Uploading external .lib file to eSim</b>') + self.uploadbtn.setToolTip( + '<b>Uploading external .lib file to eSim</b>') self.uploadbtn.clicked.connect(self.converttoxml) - self.grid.addWidget(self.newbtn, 1,2) - self.grid.addWidget(self.editbtn, 1,3) - self.grid.addWidget(self.savebtn, 1,4) - self.grid.addWidget(self.uploadbtn, 1,5) - self.grid.addWidget(self.removebtn, 8,4) - self.grid.addWidget(self.addbtn, 5,4) - + self.grid.addWidget(self.newbtn, 1, 2) + self.grid.addWidget(self.editbtn, 1, 3) + self.grid.addWidget(self.savebtn, 1, 4) + self.grid.addWidget(self.uploadbtn, 1, 5) + self.grid.addWidget(self.removebtn, 8, 4) + self.grid.addWidget(self.addbtn, 5, 4) + self.radiobtnbox = QtGui.QButtonGroup() self.diode = QtGui.QRadioButton('Diode') self.diode.setDisabled(True) @@ -70,32 +71,34 @@ class ModelEditorclass(QtGui.QWidget): self.igbt.clicked.connect(self.igbt_click) self.radiobtnbox.addButton(self.magnetic) self.magnetic.clicked.connect(self.magnetic_click) - - self.types= QtGui.QComboBox() + + self.types = QtGui.QComboBox() self.types.setHidden(True) - - self.grid.addWidget(self.types,2,2,2,3) - self.grid.addWidget(self.diode, 3,1) - self.grid.addWidget(self.bjt,4,1) - self.grid.addWidget(self.mos,5,1) - self.grid.addWidget(self.jfet,6,1) - self.grid.addWidget(self.igbt,7,1) - self.grid.addWidget(self.magnetic,8,1) + + self.grid.addWidget(self.types, 2, 2, 2, 3) + self.grid.addWidget(self.diode, 3, 1) + self.grid.addWidget(self.bjt, 4, 1) + self.grid.addWidget(self.mos, 5, 1) + self.grid.addWidget(self.jfet, 6, 1) + self.grid.addWidget(self.igbt, 7, 1) + self.grid.addWidget(self.magnetic, 8, 1) self.setLayout(self.grid) self.show() '''To create New Model file ''' + def opennew(self): self.addbtn.setHidden(True) try: self.removebtn.setHidden(True) self.modeltable.setHidden(True) - except: + except BaseException: pass os.chdir(self.savepathtest) - text, ok = QtGui.QInputDialog.getText(self, 'New Model','Enter Model Name:') + text, ok = QtGui.QInputDialog.getText( + self, 'New Model', 'Enter Model Name:') if ok: - self.newflag=1 + self.newflag = 1 self.diode.setDisabled(False) self.bjt.setDisabled(False) self.mos.setDisabled(False) @@ -155,23 +158,24 @@ class ModelEditorclass(QtGui.QWidget): def magnetic_click(self): self.openfiletype('Magnetic Core') self.types.setHidden(True) - - def setfiletype(self,text): + + def setfiletype(self, text): self.filetype = str(text) self.openfiletype(self.filetype) - - def openfiletype(self,filetype): + + def openfiletype(self, filetype): ''' - Select the path of the file to be opened depending upon selected file type + Select the path of the file to be opened \ + depending upon selected file type ''' self.path = '../deviceModelLibrary/Templates' if self.diode.isChecked(): if filetype == 'Diode': - path = os.path.join(self.path,'D.xml') + path = os.path.join(self.path, 'D.xml') self.createtable(path) if self.bjt.isChecked(): if filetype == 'NPN': - path = os.path.join(self.path,'NPN.xml') + path = os.path.join(self.path, 'NPN.xml') self.createtable(path) elif filetype == 'PNP': path = os.path.join(self.path, 'PNP.xml') @@ -213,12 +217,12 @@ class ModelEditorclass(QtGui.QWidget): if filetype == 'Magnetic Core': path = os.path.join(self.path, 'CORE.xml') self.createtable(path) - else : + else: pass def openedit(self): os.chdir(self.savepathtest) - self.newflag=0 + self.newflag = 0 self.addbtn.setHidden(True) self.types.setHidden(True) self.diode.setDisabled(True) @@ -228,10 +232,15 @@ class ModelEditorclass(QtGui.QWidget): self.bjt.setDisabled(True) self.magnetic.setDisabled(True) try: - self.editfile=str(QtGui.QFileDialog.getOpenFileName(self,"Open Library Directory","../deviceModelLibrary","*.lib")) + self.editfile = str( + QtGui.QFileDialog.getOpenFileName( + self, + "Open Library Directory", + "../deviceModelLibrary", + "*.lib")) self.createtable(self.editfile) - except: - print"No File selected for edit" + except BaseException: + print("No File selected for edit") pass def createtable(self, modelfile): @@ -247,34 +256,35 @@ class ModelEditorclass(QtGui.QWidget): self.modeltable.resizeColumnsToContents() self.modeltable.setColumnCount(2) self.modeltable.resizeRowsToContents() - self.modeltable.resize(200,200) - self.grid.addWidget(self.modeltable, 3,2,8,2) + self.modeltable.resize(200, 200) + self.grid.addWidget(self.modeltable, 3, 2, 8, 2) filepath, filename = os.path.split(self.modelfile) - base, ext= os.path.splitext(filename) - self.modelfile = os.path.join(filepath, base+'.xml') - print"Model File used for creating table : ",self.modelfile + base, ext = os.path.splitext(filename) + self.modelfile = os.path.join(filepath, base + '.xml') + print("Model File used for creating table : ", self.modelfile) self.tree = ET.parse(self.modelfile) - self.root= self.tree.getroot() + self.root = self.tree.getroot() for elem in self.tree.iter(tag='ref_model'): self.ref_model = elem.text for elem in self.tree.iter(tag='model_name'): self.model_name = elem.text - row=0 + row = 0 for params in self.tree.findall('param'): for paramlist in params: - self.modeldict[paramlist.tag]= paramlist.text - row= row+1 + self.modeldict[paramlist.tag] = paramlist.text + row = row + 1 self.modeltable.setRowCount(row) - count =0 - for tags, values in self.modeldict.items(): - self.modeltable.setItem(count,0, QTableWidgetItem(tags)) + count = 0 + for tags, values in list(self.modeldict.items()): + self.modeltable.setItem(count, 0, QTableWidgetItem(tags)) try: valueitem = QTableWidgetItem(values) - except: + except BaseException: pass - self.modeltable.setItem(count,1, valueitem) - count= count +1 - self.modeltable.setHorizontalHeaderLabels(QtCore.QString("Parameters;Values").split(";")) + self.modeltable.setItem(count, 1, valueitem) + count = count + 1 + self.modeltable.setHorizontalHeaderLabels( + QtCore.QString("Parameters;Values").split(";")) self.modeltable.show() self.modeltable.itemChanged.connect(self.edit_modeltable) @@ -282,47 +292,47 @@ class ModelEditorclass(QtGui.QWidget): self.savebtn.setDisabled(False) try: indexitem = self.modeltable.currentItem() - name = str(indexitem.data(0).toString()) + name = str(indexitem.data(0)) rowno = indexitem.row() - para = self.modeltable.item(rowno,0) - val = str(para.data(0).toString()) - self.modeldict[val]= name - except: + para = self.modeltable.item(rowno, 0) + val = str(para.data(0)) + self.modeldict[val] = name + except BaseException: pass - - def addparameters(self): ''' This function is used to add new parameter in the table ''' - text1, ok = QtGui.QInputDialog.getText(self, 'Parameter','Enter Parameter') + text1, ok = QtGui.QInputDialog.getText( + self, 'Parameter', 'Enter Parameter') if ok: - if text1 in self.modeldict.keys(): + if text1 in list(self.modeldict.keys()): self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage("The paramaeter " + text1 + " is already in the list") + self.msg.showMessage( + "The paramaeter " + text1 + " is already in the list") self.msg.setWindowTitle("Error Message") return - text2, ok = QtGui.QInputDialog.getText(self, 'Value','Enter Value') - if ok : + text2, ok = QtGui.QInputDialog.getText( + self, 'Value', 'Enter Value') + if ok: currentRowCount = self.modeltable.rowCount() self.modeltable.insertRow(currentRowCount) - self.modeltable.setItem(currentRowCount, 0, QTableWidgetItem(text1)) - self.modeltable.setItem(currentRowCount, 1, QTableWidgetItem(text2)) - self.modeldict[str(text1)]= str(text2) + self.modeltable.setItem( + currentRowCount, 0, QTableWidgetItem(text1)) + self.modeltable.setItem( + currentRowCount, 1, QTableWidgetItem(text2)) + self.modeldict[str(text1)] = str(text2) else: pass else: pass - - def savemodelfile(self): - if self.newflag== 1: + if self.newflag == 1: self.createXML(self.model_name) else: self.savethefile(self.editfile) - - - def createXML(self,model_name): + + def createXML(self, model_name): ''' This function creates .xml and .lib files from the model table ''' @@ -330,7 +340,7 @@ class ModelEditorclass(QtGui.QWidget): ET.SubElement(root, "model_name").text = model_name ET.SubElement(root, "ref_model").text = self.modelname param = ET.SubElement(root, "param") - for tags, text in self.modeldict.items(): + for tags, text in list(self.modeldict.items()): ET.SubElement(param, tags).text = text tree = ET.ElementTree(root) defaultcwd = os.getcwd() @@ -338,93 +348,163 @@ class ModelEditorclass(QtGui.QWidget): if self.diode.isChecked(): savepath = os.path.join(self.savepath, 'Diode') os.chdir(savepath) - txtfile = open(self.modelname+'.lib', 'w') - txtfile.write('.MODEL ' + self.modelname +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - txtfile.write('+ ' + tags + '=' + text +'\n') + txtfile = open(self.modelname + '.lib', 'w') + txtfile.write( + '.MODEL ' + + self.modelname + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + txtfile.write('+ ' + tags + '=' + text + '\n') txtfile.write(')') - tree.write(self.modelname +".xml") - self.obj_appconfig.print_info('New ' + self.modelname + ' ' + self.model_name + ' library created at ' + os.getcwd()) + tree.write(self.modelname + ".xml") + self.obj_appconfig.print_info( + 'New ' + + self.modelname + + ' ' + + self.model_name + + ' library created at ' + + os.getcwd()) if self.mos.isChecked(): savepath = os.path.join(self.savepath, 'MOS') os.chdir(savepath) - txtfile = open(self.modelname+'.lib', 'w') - txtfile.write('.MODEL ' + self.modelname +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - txtfile.write('+ ' + tags + '=' + text +'\n') + txtfile = open(self.modelname + '.lib', 'w') + txtfile.write( + '.MODEL ' + + self.modelname + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + txtfile.write('+ ' + tags + '=' + text + '\n') txtfile.write(')') - tree.write(self.modelname +".xml") - self.obj_appconfig.print_info('New ' + self.modelname + ' ' + self.model_name + ' library created at ' + os.getcwd()) + tree.write(self.modelname + ".xml") + self.obj_appconfig.print_info( + 'New ' + + self.modelname + + ' ' + + self.model_name + + ' library created at ' + + os.getcwd()) if self.jfet.isChecked(): savepath = os.path.join(self.savepath, 'JFET') os.chdir(savepath) - txtfile = open(self.modelname+'.lib', 'w') - txtfile.write('.MODEL ' + self.modelname +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - txtfile.write('+ ' + tags + '=' + text +'\n') + txtfile = open(self.modelname + '.lib', 'w') + txtfile.write( + '.MODEL ' + + self.modelname + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + txtfile.write('+ ' + tags + '=' + text + '\n') txtfile.write(')') - tree.write(self.modelname +".xml") - self.obj_appconfig.print_info('New ' + self.modelname + ' ' + self.model_name + ' library created at ' + os.getcwd()) + tree.write(self.modelname + ".xml") + self.obj_appconfig.print_info( + 'New ' + + self.modelname + + ' ' + + self.model_name + + ' library created at ' + + os.getcwd()) if self.igbt.isChecked(): savepath = os.path.join(self.savepath, 'IGBT') os.chdir(savepath) - txtfile = open(self.modelname+'.lib', 'w') - txtfile.write('.MODEL ' + self.modelname +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - txtfile.write('+ ' + tags + '=' + text +'\n') + txtfile = open(self.modelname + '.lib', 'w') + txtfile.write( + '.MODEL ' + + self.modelname + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + txtfile.write('+ ' + tags + '=' + text + '\n') txtfile.write(')') - tree.write(self.modelname +".xml") - self.obj_appconfig.print_info('New ' + self.modelname + ' ' + self.model_name + ' library created at ' + os.getcwd()) + tree.write(self.modelname + ".xml") + self.obj_appconfig.print_info( + 'New ' + + self.modelname + + ' ' + + self.model_name + + ' library created at ' + + os.getcwd()) if self.magnetic.isChecked(): savepath = os.path.join(self.savepath, 'Misc') os.chdir(savepath) - txtfile = open(self.modelname+'.lib', 'w') - txtfile.write('.MODEL ' + self.modelname +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - txtfile.write('+ ' + tags + '=' + text +'\n') + txtfile = open(self.modelname + '.lib', 'w') + txtfile.write( + '.MODEL ' + + self.modelname + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + txtfile.write('+ ' + tags + '=' + text + '\n') txtfile.write(')') - tree.write(self.modelname +".xml") - self.obj_appconfig.print_info('New ' + self.modelname + ' ' + self.model_name + ' library created at ' + os.getcwd()) + tree.write(self.modelname + ".xml") + self.obj_appconfig.print_info( + 'New ' + + self.modelname + + ' ' + + self.model_name + + ' library created at ' + + os.getcwd()) if self.bjt.isChecked(): savepath = os.path.join(self.savepath, 'Transistor') os.chdir(savepath) - txtfile = open(self.modelname+'.lib', 'w') - txtfile.write('.MODEL ' + self.modelname +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - txtfile.write('+ ' + tags + '=' + text +'\n') + txtfile = open(self.modelname + '.lib', 'w') + txtfile.write( + '.MODEL ' + + self.modelname + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + txtfile.write('+ ' + tags + '=' + text + '\n') txtfile.write(')') - tree.write(self.modelname +".xml") - self.obj_appconfig.print_info('New ' + self.modelname + ' ' + self.model_name + ' library created at ' + os.getcwd()) + tree.write(self.modelname + ".xml") + self.obj_appconfig.print_info( + 'New ' + + self.modelname + + ' ' + + self.model_name + + ' library created at ' + + os.getcwd()) txtfile.close() os.chdir(defaultcwd) - - - def validation(self,text): + + def validation(self, text): ''' This function checks if the file with the name already exists ''' - newfilename = text+'.xml' - + newfilename = text + '.xml' + all_dir = [x[0] for x in os.walk(self.savepathtest)] for each_dir in all_dir: all_files = os.listdir(each_dir) if newfilename in all_files: self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('The file with name ' + text+ ' already exists.') + self.msg.showMessage( + 'The file with name ' + text + ' already exists.') self.msg.setWindowTitle("Error Message") - - def savethefile(self,editfile): + def savethefile(self, editfile): ''' This function save the editing in the model table ''' xmlpath, file = os.path.split(editfile) filename = os.path.splitext(file)[0] - libpath = os.path.join(xmlpath,filename+'.lib') + libpath = os.path.join(xmlpath, filename + '.lib') libfile = open(libpath, 'w') - libfile.write('.MODEL ' + self.ref_model +' ' + self.model_name + '(\n' ) - for tags, text in self.modeldict.items(): - libfile.write('+ ' + tags + '=' + text +'\n') + libfile.write( + '.MODEL ' + + self.ref_model + + ' ' + + self.model_name + + '(\n') + for tags, text in list(self.modeldict.items()): + libfile.write('+ ' + tags + '=' + text + '\n') libfile.write(')') libfile.close() @@ -432,19 +512,18 @@ class ModelEditorclass(QtGui.QWidget): ET.SubElement(root, "model_name").text = self.model_name ET.SubElement(root, "ref_model").text = self.ref_model param = ET.SubElement(root, "param") - for tags, text in self.modeldict.items(): + for tags, text in list(self.modeldict.items()): ET.SubElement(param, tags).text = text tree = ET.ElementTree(root) - - tree.write(os.path.join(xmlpath,filename +".xml")) - + + tree.write(os.path.join(xmlpath, filename + ".xml")) + self.obj_appconfig.print_info('Updated library ' + libpath) def removeparameter(self): self.savebtn.setDisabled(False) index = self.modeltable.currentIndex() - param = index.data().toString() - remove_item = self.modeltable.item(index.row(),0).text() + remove_item = self.modeltable.item(index.row(), 0).text() self.modeltable.removeRow(index.row()) del self.modeldict[str(remove_item)] @@ -455,26 +534,31 @@ class ModelEditorclass(QtGui.QWidget): self.modeltable.setHidden(True) model_dict = {} stringof = [] - self.libfile = str(QtGui.QFileDialog.getOpenFileName(self,"Open Library Directory","../deviceModelLibrary","*.lib")) + self.libfile = str( + QtGui.QFileDialog.getOpenFileName( + self, + "Open Library Directory", + "../deviceModelLibrary", + "*.lib")) libopen = open(self.libfile) filedata = libopen.read().split() - modelcount=0 + modelcount = 0 for words in filedata: - modelcount= modelcount +1 + modelcount = modelcount + 1 if words.lower() == '.model': break ref_model = filedata[modelcount] - model_name = filedata[modelcount+1] + model_name = filedata[modelcount + 1] model_name = list(model_name) - modelnamecnt= 0 - flag= 0 + modelnamecnt = 0 + flag = 0 for chars in model_name: - modelnamecnt = modelnamecnt +1 + modelnamecnt = modelnamecnt + 1 if chars == '(': flag = 1 break - if flag == 1 : - model_name = ''.join(model_name[0:modelnamecnt-1]) + if flag == 1: + model_name = ''.join(model_name[0:modelnamecnt - 1]) else: model_name = ''.join(model_name) @@ -487,21 +571,21 @@ class ModelEditorclass(QtGui.QWidget): count = 0 for chars in stringof: - count = count +1 + count = count + 1 if chars == '(': break - count1=0 + count1 = 0 for chars in stringof: - count1 = count1 +1 + count1 = count1 + 1 if chars == ')': break - stringof = stringof[count:count1-1] - stopcount=[] - listofname = [] + stringof = stringof[count:count1 - 1] + stopcount = [] + listofname = [] stopcount.append(0) count = 0 for chars in stringof: - count = count +1 + count = count + 1 if chars == '=': stopcount.append(count) stopcount.append(count) @@ -509,40 +593,52 @@ class ModelEditorclass(QtGui.QWidget): i = 0 for no in stopcount: try: - listofname.append(''.join(stringof[int(stopcount[i]):int(stopcount[i+1])])) - i = i +1 - except: + listofname.append( + ''.join(stringof[int(stopcount[i]):int(stopcount[i + 1])])) + i = i + 1 + except BaseException: pass - listoflist =[] - listofname2 = [el.replace('\t', '').replace('\n', ' ').replace('+', '').replace(')', '').replace('=', '') for el in listofname] - listofname=[] + listoflist = [] + listofname2 = [ + el.replace( + '\t', + '').replace( + '\n', + ' ').replace( + '+', + '').replace( + ')', + '').replace( + '=', + '') for el in listofname] + listofname = [] for item in listofname2: listofname.append(item.rstrip().lstrip()) for values in listofname: valuelist = values.split(' ') listoflist.append(valuelist) for i in range(1, len(listoflist)): - model_dict[listoflist[0][0]]=listoflist[1][0] + model_dict[listoflist[0][0]] = listoflist[1][0] try: - model_dict[listoflist[i][-1]]= listoflist[i+1][0] - except: + model_dict[listoflist[i][-1]] = listoflist[i + 1][0] + except BaseException: pass root = ET.Element("library") ET.SubElement(root, "model_name").text = model_name ET.SubElement(root, "ref_model").text = ref_model param = ET.SubElement(root, "param") - for tags, text in model_dict.items(): + for tags, text in list(model_dict.items()): ET.SubElement(param, tags).text = text tree = ET.ElementTree(root) defaultcwd = os.getcwd() - savepath = os.path.join(self.savepathtest, 'User Libraries') - savefilepath= os.path.join(savepath, model_name +".xml") + savepath = os.path.join(self.savepathtest, 'User Libraries') os.chdir(savepath) - text, ok1 = QtGui.QInputDialog.getText(self, 'Model Name','Enter Model Library Name') + text, ok1 = QtGui.QInputDialog.getText( + self, 'Model Name', 'Enter Model Library Name') if ok1: - tree.write(text+".xml") - fileopen = open(text+".lib",'w') + tree.write(text + ".xml") + fileopen = open(text + ".lib", 'w') f = open(self.libfile) fileopen.write(f.read()) f.close() diff --git a/src/ngspiceSimulation/NgspiceWidget.py b/src/ngspiceSimulation/NgspiceWidget.py index 310cbe3c..52427681 100644 --- a/src/ngspiceSimulation/NgspiceWidget.py +++ b/src/ngspiceSimulation/NgspiceWidget.py @@ -1,37 +1,42 @@ -from PyQt4 import QtGui,QtCore +from PyQt4 import QtGui, QtCore from configuration.Appconfig import Appconfig import platform import os + class NgspiceWidget(QtGui.QWidget): """ This Class creates NgSpice Window """ - def __init__(self,command,projPath): + + def __init__(self, command, projPath): QtGui.QWidget.__init__(self) self.obj_appconfig = Appconfig() self.process = QtCore.QProcess(self) self.terminal = QtGui.QWidget(self) self.layout = QtGui.QVBoxLayout(self) self.layout.addWidget(self.terminal) - - print "Argument to ngspice command : ",command - + + print("Argument to ngspice command : ", command) + if platform.system() == 'Linux': - self.command = "cd "+projPath+";ngspice "+command - #Creating argument for process - #self.args = ['-into', str(self.terminal.winId()),'-hold','-e', self.command] - self.args = ['-hold','-e', self.command] + self.command = "cd " + projPath + ";ngspice " + command + # Creating argument for process + # self.args = ['-into', str(self.terminal.winId()),\ + # '-hold','-e', self.command] + self.args = ['-hold', '-e', self.command] self.process.start('xterm', self.args) self.obj_appconfig.process_obj.append(self.process) - self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']].append(self.process.pid()) - + ( + self.obj_appconfig.proc_dict + [self.obj_appconfig.current_project['ProjectName']].append( + self.process.pid()) + ) + elif platform.system() == 'Windows': - tempdir= os.getcwd() + tempdir = os.getcwd() projPath = self.obj_appconfig.current_project["ProjectName"] os.chdir(projPath) - self.command = "ngspice "+command + self.command = "ngspice " + command self.process.start(self.command) os.chdir(tempdir) - - diff --git a/src/ngspiceSimulation/NgspiceWidget.py.bak b/src/ngspiceSimulation/NgspiceWidget.py.bak new file mode 100644 index 00000000..27101eb3 --- /dev/null +++ b/src/ngspiceSimulation/NgspiceWidget.py.bak @@ -0,0 +1,37 @@ +from PyQt4 import QtGui,QtCore +from configuration.Appconfig import Appconfig +import platform +import os + +class NgspiceWidget(QtGui.QWidget): + """ + This Class creates NgSpice Window + """ + def __init__(self,command,projPath): + QtGui.QWidget.__init__(self) + self.obj_appconfig = Appconfig() + self.process = QtCore.QProcess(self) + self.terminal = QtGui.QWidget(self) + self.layout = QtGui.QVBoxLayout(self) + self.layout.addWidget(self.terminal) + + print("Argument to ngspice command : ",command) + + if platform.system() == 'Linux': + self.command = "cd "+projPath+";ngspice "+command + #Creating argument for process + #self.args = ['-into', str(self.terminal.winId()),'-hold','-e', self.command] + self.args = ['-hold','-e', self.command] + self.process.start('xterm', self.args) + self.obj_appconfig.process_obj.append(self.process) + self.obj_appconfig.proc_dict[self.obj_appconfig.current_project['ProjectName']].append(self.process.pid()) + + elif platform.system() == 'Windows': + tempdir= os.getcwd() + projPath = self.obj_appconfig.current_project["ProjectName"] + os.chdir(projPath) + self.command = "ngspice "+command + self.process.start(self.command) + os.chdir(tempdir) + + diff --git a/src/ngspiceSimulation/pythonPlotting.py b/src/ngspiceSimulation/pythonPlotting.py index 295c0a1d..9e9db8f6 100644 --- a/src/ngspiceSimulation/pythonPlotting.py +++ b/src/ngspiceSimulation/pythonPlotting.py @@ -1,139 +1,152 @@ -from __future__ import division # Used for decimal division eg 2/3=0.66 and not '0' 6/2=3.0 and 6//2=3 + # Used for decimal division eg 2/3=0.66 and not '0' 6/2=3.0 and 6//2=3 import os from PyQt4 import QtGui, QtCore -from decimal import Decimal,getcontext -from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar +from decimal import Decimal, getcontext +from matplotlib.backends.backend_qt4agg\ + import FigureCanvasQTAgg as FigureCanvas +from matplotlib.backends.backend_qt4agg\ + import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure from configuration.Appconfig import Appconfig import numpy as np + class plotWindow(QtGui.QMainWindow): - def __init__(self,fpath,projectName): + def __init__(self, fpath, projectName): QtGui.QMainWindow.__init__(self) self.fpath = fpath self.projectName = projectName self.obj_appconfig = Appconfig() - print "Complete Project Path : ",self.fpath - print "Project Name : ",self.projectName - self.obj_appconfig.print_info('Ngspice simulation is called : ' + self.fpath) - self.obj_appconfig.print_info('PythonPlotting is called : ' + self.fpath) + print("Complete Project Path : ", self.fpath) + print("Project Name : ", self.projectName) + self.obj_appconfig.print_info( + 'Ngspice simulation is called : ' + self.fpath) + self.obj_appconfig.print_info( + 'PythonPlotting is called : ' + self.fpath) self.combo = [] self.combo1 = [] self.combo1_rev = [] - #Creating Frame - self.createMainFrame() - + # Creating Frame + self.createMainFrame() + def createMainFrame(self): self.mainFrame = QtGui.QWidget() self.dpi = 100 self.fig = Figure((7.0, 7.0), dpi=self.dpi) - #Creating Canvas which will figure + # Creating Canvas which will figure self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.mainFrame) self.axes = self.fig.add_subplot(111) self.navToolBar = NavigationToolbar(self.canvas, self.mainFrame) - - #LeftVbox hold navigation tool bar and canvas + + # LeftVbox hold navigation tool bar and canvas self.left_vbox = QtGui.QVBoxLayout() self.left_vbox.addWidget(self.navToolBar) self.left_vbox.addWidget(self.canvas) - #right VBOX is main Layout which hold right grid(bottom part) and top grid(top part) + # right VBOX is main Layout which hold right grid(bottom part) and top + # grid(top part) self.right_vbox = QtGui.QVBoxLayout() self.right_grid = QtGui.QGridLayout() self.top_grid = QtGui.QGridLayout() - - #Get DataExtraction Details + + # Get DataExtraction Details self.obj_dataext = DataExtraction() self.plotType = self.obj_dataext.openFile(self.fpath) self.obj_dataext.computeAxes() self.a = self.obj_dataext.numVals() - - self.chkbox=[] - - ########### Generating list of colors : - self.full_colors = ['r','b','g','y','c','m','k']#,(0.4,0.5,0.2),(0.1,0.4,0.9),(0.4,0.9,0.2),(0.9,0.4,0.9)] + + self.chkbox = [] + + # Generating list of colors : + # ,(0.4,0.5,0.2),(0.1,0.4,0.9),(0.4,0.9,0.2),(0.9,0.4,0.9)] + self.full_colors = ['r', 'b', 'g', 'y', 'c', 'm', 'k'] self.color = [] - for i in range(0,self.a[0]-1): - if i%7 == 0: + for i in range(0, self.a[0] - 1): + if i % 7 == 0: self.color.append(self.full_colors[0]) - elif (i-1)%7 == 0: + elif (i - 1) % 7 == 0: self.color.append(self.full_colors[1]) - elif (i-2)%7 == 0: + elif (i - 2) % 7 == 0: self.color.append(self.full_colors[2]) - elif (i-3)%7 == 0: + elif (i - 3) % 7 == 0: self.color.append(self.full_colors[3]) - elif (i-4)%7 == 0: + elif (i - 4) % 7 == 0: self.color.append(self.full_colors[4]) - elif (i-5)%7 == 0: + elif (i - 5) % 7 == 0: self.color.append(self.full_colors[5]) - elif (i-6)%7 == 0: + elif (i - 6) % 7 == 0: self.color.append(self.full_colors[6]) - ###########Color generation ends here - - - #Total number of voltage source + # Color generation ends here + + # Total number of voltage source self.volts_length = self.a[1] self.analysisType = QtGui.QLabel() - self.top_grid.addWidget(self.analysisType,0,0) + self.top_grid.addWidget(self.analysisType, 0, 0) self.listNode = QtGui.QLabel() - self.top_grid.addWidget(self.listNode,1,0) + self.top_grid.addWidget(self.listNode, 1, 0) self.listBranch = QtGui.QLabel() - self.top_grid.addWidget(self.listBranch,self.a[1]+2,0) - for i in range(0,self.a[1]):#a[0]-1 + self.top_grid.addWidget(self.listBranch, self.a[1] + 2, 0) + for i in range(0, self.a[1]): # a[0]-1 self.chkbox.append(QtGui.QCheckBox(self.obj_dataext.NBList[i])) self.chkbox[i].setStyleSheet('color') - self.chkbox[i].setToolTip('<b>Check To Plot</b>' ) - self.top_grid.addWidget(self.chkbox[i],i+2,0) + self.chkbox[i].setToolTip('<b>Check To Plot</b>') + self.top_grid.addWidget(self.chkbox[i], i + 2, 0) self.colorLab = QtGui.QLabel() self.colorLab.setText('____') - self.colorLab.setStyleSheet(self.colorName(self.color[i])+'; font-weight = bold;') - self.top_grid.addWidget(self.colorLab,i+2,1) + self.colorLab.setStyleSheet( + self.colorName( + self.color[i]) + + '; font-weight = bold;') + self.top_grid.addWidget(self.colorLab, i + 2, 1) - for i in range(self.a[1],self.a[0]-1):#a[0]-1 + for i in range(self.a[1], self.a[0] - 1): # a[0]-1 self.chkbox.append(QtGui.QCheckBox(self.obj_dataext.NBList[i])) - self.chkbox[i].setToolTip('<b>Check To Plot</b>' ) - self.top_grid.addWidget(self.chkbox[i],i+3,0) + self.chkbox[i].setToolTip('<b>Check To Plot</b>') + self.top_grid.addWidget(self.chkbox[i], i + 3, 0) self.colorLab = QtGui.QLabel() self.colorLab.setText('____') - self.colorLab.setStyleSheet(self.colorName(self.color[i])+'; font-weight = bold;') - self.top_grid.addWidget(self.colorLab,i+3,1) - + self.colorLab.setStyleSheet( + self.colorName( + self.color[i]) + + '; font-weight = bold;') + self.top_grid.addWidget(self.colorLab, i + 3, 1) + self.clear = QtGui.QPushButton("Clear") self.warnning = QtGui.QLabel() self.funcName = QtGui.QLabel() self.funcExample = QtGui.QLabel() self.plotbtn = QtGui.QPushButton("Plot") - self.plotbtn.setToolTip('<b>Press</b> to Plot' ) + self.plotbtn.setToolTip('<b>Press</b> to Plot') self.multimeterbtn = QtGui.QPushButton("Multimeter") - self.multimeterbtn.setToolTip('<b>RMS</b> value of the current and voltage is displayed' ) + self.multimeterbtn.setToolTip( + '<b>RMS</b> value of the current and voltage is displayed') self.text = QtGui.QLineEdit() self.funcLabel = QtGui.QLabel() self.palette1 = QtGui.QPalette() self.palette2 = QtGui.QPalette() self.plotfuncbtn = QtGui.QPushButton("Plot Function") - self.plotfuncbtn.setToolTip('<b>Press</b> to Plot the function' ) + self.plotfuncbtn.setToolTip('<b>Press</b> to Plot the function') - self.palette1.setColor(QtGui.QPalette.Foreground,QtCore.Qt.blue) - self.palette2.setColor(QtGui.QPalette.Foreground,QtCore.Qt.red) + self.palette1.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue) + self.palette2.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red) self.funcName.setPalette(self.palette1) self.funcExample.setPalette(self.palette2) self.right_vbox.addLayout(self.top_grid) self.right_vbox.addWidget(self.plotbtn) self.right_vbox.addWidget(self.multimeterbtn) - - self.right_grid.addWidget(self.funcLabel,1,0) - self.right_grid.addWidget(self.text,1,1) - self.right_grid.addWidget(self.plotfuncbtn,2,1) - self.right_grid.addWidget(self.clear,2,0) - self.right_grid.addWidget(self.warnning,3,0) - self.right_grid.addWidget(self.funcName,4,0) - self.right_grid.addWidget(self.funcExample,4,1) + + self.right_grid.addWidget(self.funcLabel, 1, 0) + self.right_grid.addWidget(self.text, 1, 1) + self.right_grid.addWidget(self.plotfuncbtn, 2, 1) + self.right_grid.addWidget(self.clear, 2, 0) + self.right_grid.addWidget(self.warnning, 3, 0) + self.right_grid.addWidget(self.funcName, 4, 0) + self.right_grid.addWidget(self.funcExample, 4, 1) self.right_vbox.addLayout(self.right_grid) self.hbox = QtGui.QHBoxLayout() @@ -141,7 +154,7 @@ class plotWindow(QtGui.QMainWindow): self.hbox.addLayout(self.right_vbox) self.widget = QtGui.QWidget() - self.widget.setLayout(self.hbox)#finalvbox + self.widget.setLayout(self.hbox) # finalvbox self.scrollArea = QtGui.QScrollArea() self.scrollArea.setWidgetResizable(True) self.scrollArea.setWidget(self.widget) @@ -153,32 +166,55 @@ class plotWindow(QtGui.QMainWindow): self.showMaximized() self.listNode.setText("<font color='indigo'>List of Nodes:</font>") - self.listBranch.setText("<font color='indigo'>List of Branches:</font>") + self.listBranch.setText( + "<font color='indigo'>List of Branches:</font>") self.funcLabel.setText("<font color='indigo'>Function:</font>") - self.funcName.setText("<font color='indigo'>Standard functions</font>\ - <br><br>Addition:<br>Subtraction:<br>Multiplication:<br>Division:<br>Comparison:") - self.funcExample.setText("\n\nNode1 + Node2\nNode1 - Node2\nNode1 * Node2\nNode1 / Node2\nNode1 vs Node2") - - #Connecting to plot and clear function - self.connect(self.clear,QtCore.SIGNAL('clicked()'),self.pushedClear) - self.connect(self.plotfuncbtn,QtCore.SIGNAL('clicked()'), self.pushedPlotFunc) - self.connect(self.multimeterbtn,QtCore.SIGNAL('clicked()'), self.multiMeter) - + self.funcName.setText( + "<font color='indigo'>Standard functions</font>\ + <br><br>Addition:<br>Subtraction:<br>\ + Multiplication:<br>Division:<br>Comparison:" + ) + self.funcExample.setText( + "\n\nNode1 + Node2\nNode1 - Node2\nNode1 * Node2\nNode1 / Node2\ + \nNode1 vs Node2") - if self.plotType[0]==0: + # Connecting to plot and clear function + self.connect(self.clear, QtCore.SIGNAL('clicked()'), self.pushedClear) + self.connect( + self.plotfuncbtn, + QtCore.SIGNAL('clicked()'), + self.pushedPlotFunc) + self.connect( + self.multimeterbtn, + QtCore.SIGNAL('clicked()'), + self.multiMeter) + + if self.plotType[0] == 0: self.analysisType.setText("<b>AC Analysis</b>") - if self.plotType[1]==1: - self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'), self.onPush_decade) + if self.plotType[1] == 1: + self.connect( + self.plotbtn, + QtCore.SIGNAL('clicked()'), + self.onPush_decade) else: - self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'), self.onPush_ac) + self.connect( + self.plotbtn, + QtCore.SIGNAL('clicked()'), + self.onPush_ac) - elif self.plotType[0]==1: + elif self.plotType[0] == 1: self.analysisType.setText("<b>Transient Analysis</b>") - self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'), self.onPush_trans) + self.connect( + self.plotbtn, + QtCore.SIGNAL('clicked()'), + self.onPush_trans) else: self.analysisType.setText("<b>DC Analysis</b>") - self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'), self.onPush_dc) + self.connect( + self.plotbtn, + QtCore.SIGNAL('clicked()'), + self.onPush_dc) self.setCentralWidget(self.mainFrame) @@ -191,8 +227,8 @@ class plotWindow(QtGui.QMainWindow): def pushedPlotFunc(self): self.parts = str(self.text.text()) self.parts = self.parts.split(" ") - - if self.parts[len(self.parts)-1] == '': + + if self.parts[len(self.parts) - 1] == '': self.parts = self.parts[0:-1] self.values = self.parts @@ -203,40 +239,50 @@ class plotWindow(QtGui.QMainWindow): if len(self.parts) <= 2: self.warnning.setText("Too few arguments!\nRefer syntax below!") - QtGui.QMessageBox.about(self, "Warning!!", "Too Few Arguments/SYNTAX Error!\n Refer Examples") + QtGui.QMessageBox.about( + self, "Warning!!", "Too Few Arguments/SYNTAX Error!\ + \n Refer Examples") else: self.warnning.setText("") - - a = [] - finalResult = [] - p = 0 - + + a = [] + finalResult = [] + # p = 0 + for i in range(len(self.parts)): - #print "I",i - if i%2 == 0: - #print "I'm in:" + # print "I",i + if i % 2 == 0: + # print "I'm in:" for j in range(len(self.obj_dataext.NBList)): - if self.parts[i]==self.obj_dataext.NBList[j]: - #print "I got you:",self.parts[i] + if self.parts[i] == self.obj_dataext.NBList[j]: + # print "I got you:",self.parts[i] a.append(j) - - if len(a) != len(self.parts)//2 + 1: - QtGui.QMessageBox.about(self, "Warning!!", "One of the operands doesn't belong to the above list of Nodes!!") - + + if len(a) != len(self.parts) // 2 + 1: + QtGui.QMessageBox.about( + self, + "Warning!!", + "One of the operands doesn't belong to\ + the above list of Nodes!!") + for i in a: self.comboAll.append(self.obj_dataext.y[i]) - - + for i in range(len(a)): if a[i] == len(self.obj_dataext.NBList): - QtGui.QMessageBox.about(self, "Warning!!", "One of the operands doesn't belong to the above list!!") - self.warnning.setText("<font color='red'>To Err Is Human!<br>One of the operands doesn't belong to the above list!!</font>") - + QtGui.QMessageBox.about( + self, "Warning!!", "One of the operands doesn't belong\ + to the above list!!") + self.warnning.setText( + "<font color='red'>To Err Is Human!<br>One of the operands\ + doesn't belong to the above list!!</font>") + if self.parts[1] == 'vs': if len(self.parts) > 3: self.warnning.setText("Enter two operands only!!") - QtGui.QMessageBox.about(self, "Warning!!", "Recheck the expression syntax!") + QtGui.QMessageBox.about( + self, "Warning!!", "Recheck the expression syntax!") else: self.axes.cla() @@ -244,9 +290,13 @@ class plotWindow(QtGui.QMainWindow): for i in range(len(self.obj_dataext.y[a[0]])): self.combo.append(self.obj_dataext.y[a[0]][i]) self.combo1.append(self.obj_dataext.y[a[1]][i]) - - self.axes.plot(self.combo,self.combo1,c=self.color[1],label=str(2))#_rev - + + self.axes.plot( + self.combo, + self.combo1, + c=self.color[1], + label=str(2)) # _rev + if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') self.axes.set_xlabel('Voltage(V)-->') @@ -255,36 +305,50 @@ class plotWindow(QtGui.QMainWindow): self.axes.set_ylabel('Current(I)-->') elif max(a) >= self.volts_length and min(a) < self.volts_length: - QtGui.QMessageBox.about(self, "Warning!!", "Do not combine Voltage and Current!!") + QtGui.QMessageBox.about( + self, "Warning!!", "Do not combine Voltage and Current!!") else: for j in range(len(self.comboAll[0])): for i in range(len(self.values)): - if i%2==0: - self.values[i] = str(self.comboAll[i//2][j]) + if i % 2 == 0: + self.values[i] = str(self.comboAll[i // 2][j]) re = " ".join(self.values[:]) try: finalResult.append(eval(re)) except ArithmeticError: - QtGui.QMessageBox.about(self, "Warning!!", "Dividing by zero!!") - - if self.plotType2[0]==0: - #self.setWindowTitle('AC Analysis') - if self.plotType2[1]==1: - self.axes.semilogx(self.obj_dataext.x,finalResult,c=self.color[0],label=str(1)) + QtGui.QMessageBox.about( + self, "Warning!!", "Dividing by zero!!") + + if self.plotType2[0] == 0: + # self.setWindowTitle('AC Analysis') + if self.plotType2[1] == 1: + self.axes.semilogx( + self.obj_dataext.x, + finalResult, + c=self.color[0], + label=str(1)) else: - self.axes.plot(self.obj_dataext.x,finalResult,c=self.color[0],label=str(1)) - + self.axes.plot( + self.obj_dataext.x, + finalResult, + c=self.color[0], + label=str(1)) + self.axes.set_xlabel('freq-->') if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') - - elif self.plotType2[0]==1: - #self.setWindowTitle('Transient Analysis') - self.axes.plot(self.obj_dataext.x,finalResult,c=self.color[0],label=str(1)) + + elif self.plotType2[0] == 1: + # self.setWindowTitle('Transient Analysis') + self.axes.plot( + self.obj_dataext.x, + finalResult, + c=self.color[0], + label=str(1)) self.axes.set_xlabel('time-->') if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') @@ -292,33 +356,36 @@ class plotWindow(QtGui.QMainWindow): self.axes.set_ylabel('Current(I)-->') else: - #self.setWindowTitle('DC Analysis') - self.axes.plot(self.obj_dataext.x,finalResult,c=self.color[0],label=str(1)) + # self.setWindowTitle('DC Analysis') + self.axes.plot( + self.obj_dataext.x, + finalResult, + c=self.color[0], + label=str(1)) self.axes.set_xlabel('I/P Voltage-->') if max(a) < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') else: self.axes.set_ylabel('Current(I)-->') - - self.axes.grid(True) self.canvas.draw() self.combo = [] self.combo1 = [] self.combo1_rev = [] - - - - def onPush_decade(self): - #print "Calling on push Decade" + # print "Calling on push Decade" boxCheck = 0 self.axes.cla() - for i,j in zip(self.chkbox,range(len(self.chkbox))): + for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 - self.axes.semilogx(self.obj_dataext.x,self.obj_dataext.y[j],c=self.color[j],label=str(j+1)) + self.axes.semilogx( + self.obj_dataext.x, + self.obj_dataext.y[j], + c=self.color[j], + label=str( + j + 1)) self.axes.set_xlabel('freq-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') @@ -327,17 +394,22 @@ class plotWindow(QtGui.QMainWindow): self.axes.grid(True) if boxCheck == 0: - QtGui.QMessageBox.about(self, "Warning!!","Please select at least one Node OR Branch") + QtGui.QMessageBox.about( + self, "Warning!!", "Please select at least one Node OR Branch") self.canvas.draw() - def onPush_ac(self): self.axes.cla() boxCheck = 0 - for i,j in zip(self.chkbox,range(len(self.chkbox))): + for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 - self.axes.plot(self.obj_dataext.x,self.obj_dataext.y[j],c=self.color[j],label=str(j+1)) + self.axes.plot( + self.obj_dataext.x, + self.obj_dataext.y[j], + c=self.color[j], + label=str( + j + 1)) self.axes.set_xlabel('freq-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') @@ -345,16 +417,22 @@ class plotWindow(QtGui.QMainWindow): self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: - QtGui.QMessageBox.about(self, "Warning!!","Please select at least one Node OR Branch") + QtGui.QMessageBox.about( + self, "Warning!!", "Please select at least one Node OR Branch") self.canvas.draw() def onPush_trans(self): self.axes.cla() boxCheck = 0 - for i,j in zip(self.chkbox,range(len(self.chkbox))): + for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 - self.axes.plot(self.obj_dataext.x,self.obj_dataext.y[j],c=self.color[j],label=str(j+1)) + self.axes.plot( + self.obj_dataext.x, + self.obj_dataext.y[j], + c=self.color[j], + label=str( + j + 1)) self.axes.set_xlabel('time-->') if j < self.volts_length: self.axes.set_ylabel('Voltage(V)-->') @@ -362,17 +440,22 @@ class plotWindow(QtGui.QMainWindow): self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: - QtGui.QMessageBox.about(self, "Warning!!","Please select at least one Node OR Branch") + QtGui.QMessageBox.about( + self, "Warning!!", "Please select at least one Node OR Branch") self.canvas.draw() - - + def onPush_dc(self): boxCheck = 0 - self.axes.cla() - for i,j in zip(self.chkbox,range(len(self.chkbox))): + self.axes.cla() + for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): boxCheck += 1 - self.axes.plot(self.obj_dataext.x,self.obj_dataext.y[j],c=self.color[j],label=str(j+1)) + self.axes.plot( + self.obj_dataext.x, + self.obj_dataext.y[j], + c=self.color[j], + label=str( + j + 1)) self.axes.set_xlabel('Voltage Sweep(V)-->') if j < self.volts_length: @@ -381,75 +464,82 @@ class plotWindow(QtGui.QMainWindow): self.axes.set_ylabel('Current(I)-->') self.axes.grid(True) if boxCheck == 0: - QtGui.QMessageBox.about(self,"Warning!!", "Please select atleast one Node OR Branch") - self.canvas.draw() - - def colorName(self,letter): + QtGui.QMessageBox.about( + self, "Warning!!", "Please select atleast one Node OR Branch") + self.canvas.draw() + + def colorName(self, letter): return { - 'r':'color:red', - 'b':'color:blue', - 'g':'color:green', - 'y':'color:yellow', - 'c':'color:cyan', - 'm':'color:magenta', - 'k':'color:black' + 'r': 'color:red', + 'b': 'color:blue', + 'g': 'color:green', + 'y': 'color:yellow', + 'c': 'color:cyan', + 'm': 'color:magenta', + 'k': 'color:black' }[letter] def multiMeter(self): - print "Function : MultiMeter" + print("Function : MultiMeter") self.obj = {} boxCheck = 0 loc_x = 300 loc_y = 300 - - for i,j in zip(self.chkbox,range(len(self.chkbox))): + + for i, j in zip(self.chkbox, list(range(len(self.chkbox)))): if i.isChecked(): - print "Check box",self.obj_dataext.NBList[j] + print("Check box", self.obj_dataext.NBList[j]) boxCheck += 1 if self.obj_dataext.NBList[j] in self.obj_dataext.NBIList: voltFlag = False else: voltFlag = True - #Initializing Multimeter - self.obj[j] = MultimeterWidgetClass(self.obj_dataext.NBList[j],self.getRMSValue(self.obj_dataext.y[j]),loc_x,loc_y,voltFlag) + # Initializing Multimeter + self.obj[j] = MultimeterWidgetClass( + self.obj_dataext.NBList[j], self.getRMSValue( + self.obj_dataext.y[j]), loc_x, loc_y, voltFlag) loc_x += 50 loc_y += 50 - ## Adding object of multimeter to dictionary - self.obj_appconfig.dock_dict[self.obj_appconfig.current_project['ProjectName']].append(self.obj[j]) - + # Adding object of multimeter to dictionary + ( + self.obj_appconfig.dock_dict + [self.obj_appconfig.current_project['ProjectName']].append( + self.obj[j]) + ) + if boxCheck == 0: - QtGui.QMessageBox.about(self, "Warning!!","Please select at least one Node OR Branch") - - - def getRMSValue(self,dataPoints): + QtGui.QMessageBox.about( + self, "Warning!!", "Please select at least one Node OR Branch") + + def getRMSValue(self, dataPoints): getcontext().prec = 5 return np.sqrt(np.mean(np.square(dataPoints))) - + + class MultimeterWidgetClass(QtGui.QWidget): - def __init__(self,node_branch,rmsValue,loc_x,loc_y,voltFlag): + def __init__(self, node_branch, rmsValue, loc_x, loc_y, voltFlag): QtGui.QWidget.__init__(self) self.multimeter = QtGui.QWidget(self) if voltFlag: self.node_branchLabel = QtGui.QLabel("Node") - self.rmsValue = QtGui.QLabel(str(rmsValue)+" Volts") + self.rmsValue = QtGui.QLabel(str(rmsValue) + " Volts") else: self.node_branchLabel = QtGui.QLabel("Branch") - self.rmsValue = QtGui.QLabel(str(rmsValue)+" Amp") - + self.rmsValue = QtGui.QLabel(str(rmsValue) + " Amp") + self.rmsLabel = QtGui.QLabel("RMS Value") self.nodeBranchValue = QtGui.QLabel(str(node_branch)) - - + self.layout = QtGui.QGridLayout(self) - self.layout.addWidget(self.node_branchLabel,0,0) - self.layout.addWidget(self.rmsLabel,0,1) - self.layout.addWidget(self.nodeBranchValue,1,0) - self.layout.addWidget(self.rmsValue,1,1) - + self.layout.addWidget(self.node_branchLabel, 0, 0) + self.layout.addWidget(self.rmsLabel, 0, 1) + self.layout.addWidget(self.nodeBranchValue, 1, 0) + self.layout.addWidget(self.rmsValue, 1, 1) + self.multimeter.setLayout(self.layout) - self.setGeometry(loc_x,loc_y,200,100) - self.setGeometry(loc_x,loc_y,300,100) + self.setGeometry(loc_x, loc_y, 200, 100) + self.setGeometry(loc_x, loc_y, 300, 100) self.setWindowTitle("MultiMeter") self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.show() @@ -458,121 +548,120 @@ class MultimeterWidgetClass(QtGui.QWidget): class DataExtraction: def __init__(self): self.obj_appconfig = Appconfig() - self.data=[] #consists of all the columns of data belonging to nodes and branches - self.y=[] #stores y-axis data - self.x=[] #stores x-axis data - - - def numberFinder(self,fpath): - #Opening ANalysis file - with open(os.path.join(fpath,"analysis")) as f3: + self.data = [] + # consists of all the columns of data belonging to nodes and branches + self.y = [] # stores y-axis data + self.x = [] # stores x-axis data + + def numberFinder(self, fpath): + # Opening ANalysis file + with open(os.path.join(fpath, "analysis")) as f3: self.analysisInfo = f3.read() self.analysisInfo = self.analysisInfo.split(" ") - - - #Reading data file for voltage - with open(os.path.join(fpath,"plot_data_v.txt")) as f2: + + # Reading data file for voltage + with open(os.path.join(fpath, "plot_data_v.txt")) as f2: self.voltData = f2.read() self.voltData = self.voltData.split("\n") - - #Initializing variable - #'p' gives no. of lines of data for each node/branch + + # Initializing variable + # 'p' gives no. of lines of data for each node/branch # 'l' gives the no of partitions for a single voltage node - #'vnumber' gives total number of voltage - #'inumber' gives total number of current - + # 'vnumber' gives total number of voltage + # 'inumber' gives total number of current + p = l = vnumber = inumber = 0 - #print "VoltsData : ",self.voltData - - #Finding totla number of voltage node + # print "VoltsData : ",self.voltData + + # Finding totla number of voltage node for i in self.voltData[3:]: - #it has possible names of voltage nodes in NgSpice - if "Index" in i:#"V(" in i or "x1" in i or "u3" in i: - vnumber+=1 - - #print "Voltage Number :",vnumber - - #Reading Current Source Data - with open (os.path.join(fpath,"plot_data_i.txt")) as f1: + # it has possible names of voltage nodes in NgSpice + if "Index" in i: # "V(" in i or "x1" in i or "u3" in i: + vnumber += 1 + + # print "Voltage Number :",vnumber + + # Reading Current Source Data + with open(os.path.join(fpath, "plot_data_i.txt")) as f1: self.currentData = f1.read() - self.currentData = self.currentData.split("\n") - - #print "CurrentData : ",self.currentData - - #Finding Number of Branch + self.currentData = self.currentData.split("\n") + + # print "CurrentData : ",self.currentData + + # Finding Number of Branch for i in self.currentData[3:]: if "#branch" in i: - inumber+=1 - - #print "Current Number :",inumber - - self.dec = 0 - - #For AC - if self.analysisInfo[0][-3:]==".ac": + inumber += 1 + + # print "Current Number :",inumber + + self.dec = 0 + + # For AC + if self.analysisInfo[0][-3:] == ".ac": self.analysisType = 0 if "dec" in self.analysisInfo: self.dec = 1 for i in self.voltData[3:]: - p+=1 #'p' gives no. of lines of data for each node/branch + p += 1 # 'p' gives no. of lines of data for each node/branch if "Index" in i: - l+=1 # 'l' gives the no of partitions for a single voltage node - #print "l:",l - if "AC" in i: #DC for dc files and AC for ac ones + l += 1 + # 'l' gives the no of partitions for a single voltage node + # print "l:",l + if "AC" in i: # DC for dc files and AC for ac ones break elif ".tran" in self.analysisInfo: self.analysisType = 1 for i in self.voltData[3:]: - p+=1 - if "Index" in i: - l+=1 # 'l' gives the no of partitions for a single voltage node - #print "l:",l - if "Transient" in i: #DC for dc files and AC for ac ones + p += 1 + if "Index" in i: + l += 1 + # 'l' gives the no of partitions for a single voltage node + # print "l:",l + if "Transient" in i: # DC for dc files and AC for ac ones break - # For DC: else: self.analysisType = 2 for i in self.voltData[3:]: - p+=1 - if "Index" in i: - l+=1 # 'l' gives the no of partitions for a single voltage node - #print "l:",l - if "DC" in i: #DC for dc files and AC for ac ones + p += 1 + if "Index" in i: + l += 1 + # 'l' gives the no of partitions for a single voltage node + # print "l:",l + if "DC" in i: # DC for dc files and AC for ac ones break + # print "VoltNumber",vnumber + # print "CurrentNumber",inumber + vnumber = vnumber // l # vnumber gives the no of voltage nodes + inumber = inumber // l # inumber gives the no of branches + + # print "VoltNumber",vnumber + # print "CurrentNumber",inumber + + p = [p, vnumber, self.analysisType, self.dec, inumber] - - #print "VoltNumber",vnumber - #print "CurrentNumber",inumber - vnumber = vnumber//l #vnumber gives the no of voltage nodes - inumber = inumber//l #inumber gives the no of branches - - #print "VoltNumber",vnumber - #print "CurrentNumber",inumber - - p=[p,vnumber,self.analysisType,self.dec,inumber] - return p - - def openFile(self,fpath): + + def openFile(self, fpath): try: - with open (os.path.join(fpath,"plot_data_i.txt")) as f2: + with open(os.path.join(fpath, "plot_data_i.txt")) as f2: alli = f2.read() alli = alli.split("\n") self.NBIList = [] - with open (os.path.join(fpath,"plot_data_v.txt")) as f1: + with open(os.path.join(fpath, "plot_data_v.txt")) as f1: allv = f1.read() except Exception as e: - print "Exception Message : ",str(e) + print("Exception Message : ", str(e)) self.obj_appconfig.print_error('Exception Message :' + str(e)) self.msg = QtGui.QErrorMessage(None) self.msg.showMessage('Unable to open plot data files.') @@ -580,154 +669,145 @@ class DataExtraction: try: for l in alli[3].split(" "): - if len(l)>0: + if len(l) > 0: self.NBIList.append(l) self.NBIList = self.NBIList[2:] len_NBIList = len(self.NBIList) - #print "NBILIST : ",self.NBIList + # print "NBILIST : ",self.NBIList except Exception as e: - print "Exception Message : ",str(e) + print("Exception Message : ", str(e)) self.obj_appconfig.print_error('Exception Message :' + str(e)) self.msg = QtGui.QErrorMessage(None) self.msg.showMessage('Error in Analysis File.') self.msg.setWindowTitle("Error Message:openFile") - - d = self.numberFinder(fpath) d1 = int(d[0] + 1) d2 = int(d[1]) d3 = d[2] d4 = d[4] - - dec = [d3,d[3]] - #print "No. of Nodes:", d2 + + dec = [d3, d[3]] + # print "No. of Nodes:", d2 self.NBList = [] - allv=allv.split("\n") + allv = allv.split("\n") for l in allv[3].split(" "): - if len(l)>0: + if len(l) > 0: self.NBList.append(l) - self.NBList=self.NBList[2:] + self.NBList = self.NBList[2:] len_NBList = len(self.NBList) - print "NBLIST",self.NBList - - ivals=[] + print("NBLIST", self.NBList) + + ivals = [] inum = len(allv[5].split("\t")) inum_i = len(alli[5].split("\t")) - - - + full_data = [] # Creating list of data: - if d3 < 3 : - for i in range(1,d2): - for l in allv[3+i*d1].split(" "): - if len(l)>0: + if d3 < 3: + for i in range(1, d2): + for l in allv[3 + i * d1].split(" "): + if len(l) > 0: self.NBList.append(l) self.NBList.pop(len_NBList) self.NBList.pop(len_NBList) len_NBList = len(self.NBList) - - for n in range(1,d4): - for l in alli[3+n*d1].split(" "): - if len(l)>0: + + for n in range(1, d4): + for l in alli[3 + n * d1].split(" "): + if len(l) > 0: self.NBIList.append(l) self.NBIList.pop(len_NBIList) self.NBIList.pop(len_NBIList) len_NBIList = len(self.NBIList) - - p=0 + + p = 0 k = 0 - m=0 - - for i in alli[5:d1-1]: - if len(i.split("\t"))==inum_i: - j2=i.split("\t") - #print j2 + m = 0 + + for i in alli[5:d1 - 1]: + if len(i.split("\t")) == inum_i: + j2 = i.split("\t") + # print j2 j2.pop(0) j2.pop(0) j2.pop() - if d3 == 0: #not in trans + if d3 == 0: # not in trans j2.pop() - #print j2 - - for l in range(1,d4): - j3 = alli[5+l*d1+k].split("\t") + # print j2 + + for l in range(1, d4): + j3 = alli[5 + l * d1 + k].split("\t") j3.pop(0) j3.pop(0) - if d3==0: - j3.pop() #not required for dc + if d3 == 0: + j3.pop() # not required for dc j3.pop() j2 = j2 + j3 - #print j2 - + # print j2 full_data.append(j2) - - k+=1 - - #print "FULL DATA :",full_data - - for i in allv[5:d1-1]: - if len(i.split("\t"))==inum: - j=i.split("\t") + k += 1 + + # print "FULL DATA :",full_data + + for i in allv[5:d1 - 1]: + if len(i.split("\t")) == inum: + j = i.split("\t") j.pop() - if d3==0: + if d3 == 0: j.pop() - for l in range(1,d2): - j1 = allv[5+l*d1+p].split("\t") + for l in range(1, d2): + j1 = allv[5 + l * d1 + p].split("\t") j1.pop(0) j1.pop(0) - if d3==0: - j1.pop() #not required for dc - if self.NBList[len(self.NBList)-1] == 'v-sweep': + if d3 == 0: + j1.pop() # not required for dc + if self.NBList[len(self.NBList) - 1] == 'v-sweep': self.NBList.pop() j1.pop() j1.pop() j = j + j1 j = j + full_data[m] - #print j - m+=1 - #print j[:20] + # print j + m += 1 + # print j[:20] j = "\t".join(j[1:]) - j = j.replace(",","") + j = j.replace(",", "") ivals.append(j) - - p+=1 - + + p += 1 + self.data = ivals - - #print "volts:",self.butnames + + # print "volts:",self.butnames self.volts_length = len(self.NBList) self.NBList = self.NBList + self.NBIList - - - print dec + + print(dec) return dec - - + def numVals(self): a = self.volts_length # No of voltage nodes b = len(self.data[0].split("\t")) - #print "numvals:",b - return [b,a] - + # print "numvals:",b + return [b, a] def computeAxes(self): nums = len(self.data[0].split("\t")) - #print "i'm nums:",nums - self.y=[] - var=self.data[0].split("\t") - for i in range(1,nums): + # print "i'm nums:",nums + self.y = [] + var = self.data[0].split("\t") + for i in range(1, nums): self.y.append([Decimal(var[i])]) for i in self.data[1:]: - temp=i.split("\t") - for j in range(1,nums): - self.y[j-1].append(Decimal(temp[j])) + temp = i.split("\t") + for j in range(1, nums): + self.y[j - 1].append(Decimal(temp[j])) for i in self.data: - temp=i.split("\t") + temp = i.split("\t") self.x.append(Decimal(temp[0])) diff --git a/src/ngspicetoModelica/ModelicaUI.py b/src/ngspicetoModelica/ModelicaUI.py index e4079562..daef6e76 100644 --- a/src/ngspicetoModelica/ModelicaUI.py +++ b/src/ngspicetoModelica/ModelicaUI.py @@ -1,5 +1,4 @@ import os -import sys from subprocess import Popen, PIPE, STDOUT from PyQt4 import QtGui, QtCore from configuration.Appconfig import Appconfig @@ -8,6 +7,7 @@ from projManagement.Validation import Validation BROWSE_LOCATION = '/home' + class OpenModelicaEditor(QtGui.QWidget): def __init__(self, dir=None): @@ -16,8 +16,10 @@ class OpenModelicaEditor(QtGui.QWidget): self.obj_appconfig = Appconfig() self.projDir = dir self.projName = os.path.basename(self.projDir) - self.ngspiceNetlist = os.path.join(self.projDir,self.projName+".cir.out") - self.modelicaNetlist = os.path.join(self.projDir,self.projName+".mo") + self.ngspiceNetlist = os.path.join( + self.projDir, self.projName + ".cir.out") + self.modelicaNetlist = os.path.join( + self.projDir, self.projName + ".mo") self.map_json = Appconfig.modelica_map_json self.grid = QtGui.QGridLayout() @@ -37,59 +39,84 @@ class OpenModelicaEditor(QtGui.QWidget): self.loadOMbtn.clicked.connect(self.callOMEdit) self.grid.addWidget(self.loadOMbtn, 3, 1) - #self.setGeometry(300, 300, 350, 300) + # self.setGeometry(300, 300, 350, 300) self.setLayout(self.grid) self.show() def browseFile(self): - self.ngspiceNetlist = QtGui.QFileDialog.getOpenFileName(self, 'Open Ngspice file', BROWSE_LOCATION) + self.ngspiceNetlist = QtGui.QFileDialog.getOpenFileName( + self, 'Open Ngspice file', BROWSE_LOCATION) self.FileEdit.setText(self.ngspiceNetlist) def callConverter(self): try: - self.cmd1 = "python ../ngspicetoModelica/NgspicetoModelica.py " + self.ngspiceNetlist + ' ' + self.map_json - #self.obj_workThread1 = Worker.WorkerThread(self.cmd1) - #self.obj_workThread1.start() - convert_process = Popen(self.cmd1, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) + self.cmd1 = "python ../ngspicetoModelica/NgspicetoModelica.py " + \ + self.ngspiceNetlist + ' ' + self.map_json + # self.obj_workThread1 = Worker.WorkerThread(self.cmd1) + # self.obj_workThread1.start() + convert_process = Popen( + self.cmd1, + shell=True, + stdin=PIPE, + stdout=PIPE, + stderr=STDOUT, + close_fds=True) error_code = convert_process.stdout.read() if not error_code: self.msg = QtGui.QMessageBox() - self.msg.setText("Ngspice netlist successfully converted to OpenModelica netlist") - self.obj_appconfig.print_info("Ngspice netlist successfully converted to OpenModelica netlist") + self.msg.setText( + "Ngspice netlist successfully converted to OpenModelica" + + "netlist") + self.obj_appconfig.print_info( + "Ngspice netlist successfully converted to OpenModelica" + + "netlist" + ) self.msg.exec_() else: self.err_msg = QtGui.QErrorMessage() - self.err_msg.showMessage('Unable to convert NgSpice netlist to Modelica netlist. Check the netlist :'+ error_code) - self.err_msg.setWindowTitle("Ngspice to Modelica conversion error") + self.err_msg.showMessage( + 'Unable to convert NgSpice netlist to Modelica netlist.' + + 'Check the netlist :' + + error_code) + self.err_msg.setWindowTitle( + "Ngspice to Modelica conversion error") self.obj_appconfig.print_error(error_code) except Exception as e: self.msg = QtGui.QErrorMessage() - self.msg.showMessage('Unable to convert NgSpice netlist to Modelica netlist. Check the netlist :'+str(e)) + self.msg.showMessage( + 'Unable to convert NgSpice netlist to Modelica netlist.' + + 'Check the netlist :' + + str(e)) self.msg.setWindowTitle("Ngspice to Modelica conversion error") - def callOMEdit(self): if self.obj_validation.validateTool("OMEdit"): self.cmd2 = "OMEdit " + self.modelicaNetlist self.obj_workThread2 = Worker.WorkerThread(self.cmd2) self.obj_workThread2.start() - print "OMEdit called" + print("OMEdit called") self.obj_appconfig.print_info("OMEdit called") else: self.msg = QtGui.QMessageBox() self.msgContent = "There was an error while opening OMEdit.<br/>\ - Please make sure OpenModelica is installed in your system. <br/>\ - To install it on Linux : Go to <a href=https://www.openmodelica.org/download/download-linux>OpenModelica Linux</a> and install nigthly build release.<br/>\ - To install it on Windows : Go to <a href=https://www.openmodelica.org/download/download-windows>OpenModelica Windows</a> and install latest version.<br/>" + Please make sure OpenModelica is installed in your \ + system. <br/>\ + To install it on Linux : Go to <a href= \ + https://www.openmodelica.org/download/download-linux> \ + OpenModelica Linux</a> \ + and install nigthly build release.<br/> \ + To install it on Windows : Go to <a href= \ + https://www.openmodelica.org/download/download-windows>\ + OpenModelica Windows</a> and install latest version. \ + <br/>" self.msg.setTextFormat(QtCore.Qt.RichText) self.msg.setText(self.msgContent) self.msg.setWindowTitle("Missing OpenModelica") self.obj_appconfig.print_info(self.msgContent) self.msg.exec_() - diff --git a/src/ngspicetoModelica/NgspicetoModelica.py b/src/ngspicetoModelica/NgspicetoModelica.py index 7b7e4527..dfeafb53 100644 --- a/src/ngspicetoModelica/NgspicetoModelica.py +++ b/src/ngspicetoModelica/NgspicetoModelica.py @@ -1,29 +1,26 @@ import sys import os -import re +import re import json from string import maketrans + class NgMoConverter: - - + def __init__(self, map_json): - #Loading JSON file which hold the mapping information between ngspice and Modelica. + # Loading JSON file which hold the mapping information between ngspice + # and Modelica. with open(map_json) as mappingFile: self.mappingData = json.load(mappingFile) - + self.ifMOS = False self.sourceDetail = [] self.deviceDetail = [] self.subCktDetail = [] - self.deviceList = ['d','D','j','J','q','Q','m','M'] - self.sourceList = ['v','V','i','I'] - - - - - - def readNetlist(self,filename): + self.deviceList = ['d', 'D', 'j', 'J', 'q', 'Q', 'm', 'M'] + self.sourceList = ['v', 'V', 'i', 'I'] + + def readNetlist(self, filename): """ Read Ngspice Netlist """ @@ -33,67 +30,71 @@ class NgMoConverter: f = open(filename) except Exception as e: print("Error in opening file") - print(str(e)) + print((str(e))) sys.exit() else: - print filename + " does not exist" + print(filename + " does not exist") sys.exit() data = f.read() data = data.splitlines() f.close() for eachline in data: - eachline=eachline.strip() - if len(eachline)>1: - if eachline[0]=='+': - netlist.append(netlist.pop()+eachline.replace('+',' ',1)) + eachline = eachline.strip() + if len(eachline) > 1: + if eachline[0] == '+': + netlist.append( + netlist.pop() + + eachline.replace( + '+', + ' ', + 1)) else: - netlist.append(eachline) - + netlist.append(eachline) + return netlist - - def separateNetlistInfo(self,netlist): + + def separateNetlistInfo(self, netlist): """ Separate schematic data and option data """ optionInfo = [] schematicInfo = [] - - - + for eachline in netlist: - + if len(eachline) > 1: - if eachline[0]=='*': + if eachline[0] == '*': continue - elif eachline[0]=='.': + elif eachline[0] == '.': optionInfo.append(eachline) - #optionInfo.append(eachline.lower()) + # optionInfo.append(eachline.lower()) elif eachline[0] in self.deviceList: - if eachline[0]=='m' or eachline[0]=='M': + if eachline[0] == 'm' or eachline[0] == 'M': self.ifMOS = True schematicInfo.append(eachline) self.deviceDetail.append(eachline) - elif eachline[0]=='x' or eachline[0]=='X': + elif eachline[0] == 'x' or eachline[0] == 'X': schematicInfo.append(eachline) self.subCktDetail.append(eachline) elif eachline[0] in self.sourceList: schematicInfo.append(eachline) self.sourceDetail.append(eachline) - elif eachline[0]=='a' or eachline[0]=='A': - schematicInfo.append(eachline) + elif eachline[0] == 'a' or eachline[0] == 'A': + schematicInfo.append(eachline) else: schematicInfo.append(eachline) - ##No need of making it lower case as netlist is already converted to ngspice - #schematicInfo.append(eachline.lower()) - - - return optionInfo,schematicInfo - - def addModel(self,optionInfo): + # No need of making it lower case as netlist + # is already converted to ngspice + # schematicInfo.append(eachline.lower()) + + return optionInfo, schematicInfo + + def addModel(self, optionInfo): """ - Add model parameters in the modelica file and create dictionary of model parameters - This function extract model and subckt information along with their parameters with the help of optionInfo + Add model parameters in the modelica file and create dictionary of + model parameters. This function extract model and subckt information + along with their parameters with the help of optionInfo """ modelName = [] modelInfo = {} @@ -101,7 +102,7 @@ class NgMoConverter: paramInfo = [] transInfo = {} inbuiltModelDict = {} - + for eachline in optionInfo: words = eachline.split() if words[0] == '.include': @@ -115,76 +116,92 @@ class NgMoConverter: elif words[0] == '.model': model = words[1] modelInfo[model] = {} - eachline = eachline.replace(' = ','=').replace('= ','=').replace(' =','=') + eachline = eachline.replace( + ' = ', + '=').replace( + '= ', + '=').replace( + ' =', + '=') eachline = eachline.split('(') templine = eachline[0].split() trans = templine[1] transInfo[trans] = [] templine[2] = templine[2].lower() - if templine[2] in ['npn', 'pnp', 'pmos', 'nmos','njf','pjf']: + if templine[2] in ['npn', 'pnp', 'pmos', 'nmos', 'njf', 'pjf']: transInfo[trans] = templine[2] else: - inbuiltModelDict[model]=templine[2] + inbuiltModelDict[model] = templine[2] eachline[1] = eachline[1].lower() eachline = eachline[1].split() for eachitem in eachline: if len(eachitem) > 1: - eachitem = eachitem.replace(')','') + eachitem = eachitem.replace(')', '') iteminfo = eachitem.split('=') for each in iteminfo: modelInfo[model][iteminfo[0]] = iteminfo[1] - - #Adding details of model(external) and subckt into modelInfo and subcktInfo + + # Adding details of model(external) and subckt into modelInfo and + # subcktInfo for eachmodel in modelName: filename = eachmodel + '.lib' if os.path.exists(filename): try: f = open(filename) - except: + except BaseException: print("Error in opening file") sys.exit() else: - print filename + " does not exist" + print(filename + " does not exist") sys.exit() data = f.read() - data = data.replace('+', '').replace('\n','').replace(' = ','=').replace('= ','=').replace(' =','=') - #data = data.lower() #Won't work if Reference model name is Upper Case + data = data.replace( + '+', + '').replace( + '\n', + '').replace( + ' = ', + '=').replace( + '= ', + '=').replace( + ' =', + '=') + # data = data.lower() #Won't work if Reference model name is Upper + # Case newdata = data.split('(') templine_f = newdata[0].split() trans_f = templine_f[1] transInfo[trans_f] = [] - templine_f[2] = templine_f[2].lower() - if templine_f[2] in ['npn', 'pnp', 'pmos', 'nmos','njf','pjf']: + templine_f[2] = templine_f[2].lower() + if templine_f[2] in ['npn', 'pnp', 'pmos', 'nmos', 'njf', 'pjf']: transInfo[trans_f] = templine_f[2] - + refModelName = trans_f newdata[1] = newdata[1].lower() modelParameter = newdata[1].split() - + modelInfo[refModelName] = {} - + for eachline in modelParameter: if len(eachline) > 1: - eachline = eachline.replace(')','') + eachline = eachline.replace(')', '') info = eachline.split('=') for eachitem in info: - modelInfo[refModelName][info[0]] = info[1] + modelInfo[refModelName][info[0]] = info[1] f.close() - - - - - return modelName, modelInfo, subcktName, paramInfo ,transInfo,inbuiltModelDict - - def processParam(self,paramInfo): + + return (modelName, modelInfo, subcktName, + paramInfo, transInfo, inbuiltModelDict) + + def processParam(self, paramInfo): """ Process parameter info and update in Modelica syntax """ modelicaParam = [] for eachline in paramInfo: eachline = eachline.split('.param') - #Include ',' in between parameter - #Removing leading and trailing space + # Include ',' in between parameter + # Removing leading and trailing space line = eachline[1].strip() line = line.split() final_line = ','.join(line) @@ -192,9 +209,8 @@ class NgMoConverter: stat = stat.translate(maketrans('{}', ' ')) modelicaParam.append(stat) return modelicaParam - - - def separatePlot(self,schematicInfo): + + def separatePlot(self, schematicInfo): """ separate print plot and component statements """ @@ -209,15 +225,17 @@ class NgMoConverter: else: compInfo.append(eachline) return compInfo, plotInfo - - def separateSource(self,compInfo): + + def separateSource(self, compInfo): """ - Find if dependent sources are present in the schematic and if so make a dictionary with source details + Find if dependent sources are present in the schematic and + if so make a dictionary with source details """ sourceInfo = {} source = [] for eachline in compInfo: - words = eachline.split() ##This line need to be confirmed with Manas + words = eachline.split() + # This line need to be confirmed with Manas if eachline[0] in ['f', 'h']: source.append(words[3]) if len(source) > 0: @@ -226,58 +244,61 @@ class NgMoConverter: if words_s[0] in source: sourceInfo[words_s[0]] = words_s[1:3] return sourceInfo - - def getUnitVal(self,compValue): - #regExp = re.compile("([0-9]+)([a-zA-Z]+)") - #Remove '(' and ')' if any - compValue = compValue.replace('(','').replace(')','') + + def getUnitVal(self, compValue): + # regExp = re.compile("([0-9]+)([a-zA-Z]+)") + # Remove '(' and ')' if any + compValue = compValue.replace('(', '').replace(')', '') compValue = compValue.lower() - #regExp = re.compile("([-])?([0-9]+)\.?([0-9]+)?([a-zA-Z])?") - regExp = re.compile("([-])?([0-9]+)\.?([0-9]+)?(\w+)?") - matchString = regExp.match(str(compValue)) #separating number and string + # regExp = re.compile("([-])?([0-9]+)\.?([0-9]+)?([a-zA-Z])?") + regExp = re.compile(r"([-])?([0-9]+)\.?([0-9]+)?(\w+)?") + # separating number and string + matchString = regExp.match(str(compValue)) try: signVal = matchString.group(1) valBeforeDecimal = matchString.group(2) valAfterDecimal = matchString.group(3) unitValue = matchString.group(4) modifiedcompValue = "" - if str(signVal)=='None': + if str(signVal) == 'None': pass else: modifiedcompValue += signVal - + modifiedcompValue += valBeforeDecimal - - if str(valAfterDecimal)=='None': + + if str(valAfterDecimal) == 'None': pass else: - modifiedcompValue += '.'+valAfterDecimal - - if str(unitValue)=='None': + modifiedcompValue += '.' + valAfterDecimal + + if str(unitValue) == 'None': pass else: modifiedcompValue += self.mappingData["Units"][unitValue] - + return modifiedcompValue - except: + except BaseException: return compValue - - - def compInit(self,compInfo, node, modelInfo, subcktName,dir_name,transInfo,inbuiltModelDict): + + def compInit(self, compInfo, node, modelInfo, subcktName, + dir_name, transInfo, inbuiltModelDict): """ - For each component in the netlist initialize it according to Modelica format + For each component in the netlist initialize it + according to Modelica format """ - #print "CompInfo inside compInit function : compInit------->",compInfo - #### initial processing to check if MOs is present. If so, library to be used is BondLib + # print "CompInfo inside compInit function : compInit------->",compInfo + # initial processing to check if MOs is present. If so, library to be + # used is BondLib modelicaCompInit = [] - numNodesSub = {} + numNodesSub = {} mosInfo = {} - IfMOS = '0' - + # IfMOS = '0' + for eachline in compInfo: - #words = eachline.split() + # words = eachline.split() if eachline[0] == 'm': - IfMOS = '1' + # IfMOS = '1' break if len(subcktName) > 0: subOptionInfo = [] @@ -287,357 +308,555 @@ class NgMoConverter: filename_tem = os.path.join(dir_name, filename_tem) data = self.readNetlist(filename_tem) subOptionInfo, subSchemInfo = self.separateNetlistInfo(data) - + for eachline in subSchemInfo: - #words = eachline.split() + # words = eachline.split() if eachline[0] == 'm': - IfMOS = '1' + # IfMOS = '1' break - - #Lets Start with Source details + + # Lets Start with Source details for eachline in self.sourceDetail: words = eachline.split() - #Preserve component name from lower case function + # Preserve component name from lower case function compName = words[0] - #Now Lower case all other + # Now Lower case all other words = eachline.lower().split() words[0] = compName typ = words[3].split('(') - + sourceType = compName[0].lower() - + if sourceType == 'v': if typ[0] == "pulse": per = words[9].split(')') - stat = self.mappingData["Sources"][sourceType][typ[0]]+' '+compName+'(rising = '+self.getUnitVal(words[6])+', V = '+self.getUnitVal(words[4])\ - +', width = '+self.getUnitVal(words[8])+', period = '+self.getUnitVal(per[0])+', offset = '+self.getUnitVal(typ[1])+', startTime = '+self.getUnitVal(words[5])+', falling = '+self.getUnitVal(words[7])+');' + stat = self.mappingData["Sources"][sourceType][typ[0]] +\ + ' ' + compName + '(rising = ' +\ + self.getUnitVal(words[6]) + ', V = ' +\ + self.getUnitVal(words[4])\ + + ', width = ' + self.getUnitVal(words[8]) +\ + ', period = ' + self.getUnitVal(per[0]) +\ + ', offset = ' + self.getUnitVal( + typ[1]) + ', startTime = ' +\ + self.getUnitVal(words[5]) + ', falling = ' +\ + self.getUnitVal(words[7]) + ');' modelicaCompInit.append(stat) if typ[0] == "sine": theta = words[7].split(')') - stat = self.mappingData["Sources"][sourceType][typ[0]]+' '+compName+'(offset = '+self.getUnitVal(typ[1])+', V = '+self.getUnitVal(words[4])+', freqHz = '+self.getUnitVal(words[5])+', startTime = '+self.getUnitVal(words[6])+', phase = '+self.getUnitVal(theta[0])+');' + stat = self.mappingData["Sources"][sourceType][typ[0]] +\ + ' ' + compName + '(offset = ' +\ + self.getUnitVal(typ[1]) +\ + ', V = ' + self.getUnitVal(words[4]) + ', freqHz = ' +\ + self.getUnitVal(words[5]) + ', startTime = ' +\ + self.getUnitVal(words[6]) + ', phase = ' +\ + self.getUnitVal(theta[0]) + ');' modelicaCompInit.append(stat) if typ[0] == "pwl": - keyw = self.mappingData["Sources"][sourceType][typ[0]]+' ' - stat = keyw + compName + '(table = [' + self.getUnitVal(typ[1]) + ',' + self.getUnitVal(words[4]) + ';' - length = len(words); - for i in range(6,length,2): - if i == length-2: + keyw = self.mappingData["Sources"][sourceType][typ[0]] +\ + ' ' + stat = keyw + compName + \ + '(table = [' + self.getUnitVal(typ[1]) + \ + ',' + self.getUnitVal(words[4]) + ';' + length = len(words) + for i in range(6, length, 2): + if i == length - 2: w = words[i].split(')') - stat = stat + self.getUnitVal(words[i-1]) + ',' + self.getUnitVal(w[0]) + stat = stat + \ + self.getUnitVal( + words[i - 1]) + ',' + self.getUnitVal(w[0]) else: - stat = stat + self.getUnitVal(words[i-1]) + ',' + self.getUnitVal(words[i]) + ';' + stat = stat + \ + self.getUnitVal(words[i - 1]) + ',' + \ + self.getUnitVal(words[i]) + ';' stat = stat + ']);' - modelicaCompInit.append(stat) + modelicaCompInit.append(stat) if typ[0] == words[3] and typ[0] != "dc": - #It is DC constant but no dc keyword + # It is DC constant but no dc keyword val_temp = typ[0].split('v') - stat = self.mappingData["Sources"][sourceType]["dc"]+' ' + compName + '(V = ' + self.getUnitVal(val_temp[0]) + ');' + stat = self.mappingData["Sources"][sourceType]["dc"] + \ + ' ' + \ + compName + \ + '(V = ' + self.getUnitVal(val_temp[0]) + ');' modelicaCompInit.append(stat) elif typ[0] == words[3] and typ[0] == "dc": - stat = self.mappingData["Sources"][sourceType][typ[0]]+' ' + compName + '(V = ' + self.getUnitVal(words[4]) + ');' ### check this + stat = self.mappingData["Sources"][sourceType][typ[0]] + \ + ' ' + \ + compName + \ + '(V = ' + \ + self.getUnitVal(words[4]) + ');' # check this modelicaCompInit.append(stat) - - elif sourceType=='i': - stat = self.mappingData["Sources"][sourceType]["dc"]+' '+compName+'(I='+self.getUnitVal(words[3])+');' + + elif sourceType == 'i': + stat = self.mappingData["Sources"][sourceType]["dc"] + \ + ' ' + compName + '(I=' + self.getUnitVal(words[3]) + ');' modelicaCompInit.append(stat) - - #Now empty the source list as it may be used by subcircuit + + # Now empty the source list as it may be used by subcircuit self.sourceDetail[:] = [] - - #print "Source Detail after processing-------->",self.sourceDetail - - #Lets start for device + + # print "Source Detail after processing-------->",self.sourceDetail + + # Lets start for device for eachline in self.deviceDetail: - words=eachline.split() + words = eachline.split() deviceName = eachline[0].lower() - if deviceName=='d': - if len(words)>3: - if modelInfo[words[3]].has_key('n'): + if deviceName == 'd': + if len(words) > 3: + if 'n' in modelInfo[words[3]]: n = float(modelInfo[words[3]]['n']) else: n = 1.0 - vt = str(float(0.025*n)) - #stat = self.mappingData["Devices"][deviceName]["import"]+' '+ words[0] + '(Ids = ' + modelInfo[words[3]]['is'] + ', Vt = ' + vt + ', R = 1e12' +');' + vt = str(float(0.025 * n)) + ''' + stat = self.mappingData["Devices"][deviceName]["import"]+\ + ' '+words[0] + '(Ids = ' + modelInfo[words[3]]['is']+\ + ', Vt = ' + vt + ', R = 1e12' +');' + ''' start = self.mappingData["Devices"][deviceName]["import"] - stat = start+" "+words[0]+"(" - tempstatList=[] - userDeviceParamList=[] + stat = start + " " + words[0] + "(" + tempstatList = [] + userDeviceParamList = [] refName = words[-1] for key in modelInfo[refName]: - #If parameter is not mapped then it will just pass + # If parameter is not mapped then it will just pass try: - actualModelicaParam = self.mappingData["Devices"][deviceName]["mapping"][key] - tempstatList.append(actualModelicaParam+"="+self.getUnitVal(modelInfo[refName][key])+" ") - userDeviceParamList.append(str(actualModelicaParam)) - except: + actualModelicaParam = ( + self.mappingData["Devices"] + [deviceName] + ["mapping"] + [key] + ) + tempstatList.append( + actualModelicaParam + + "=" + + self.getUnitVal( + modelInfo[refName][key]) + + " ") + userDeviceParamList.append( + str(actualModelicaParam)) + except BaseException: pass - #Adding Vt and R + # Adding Vt and R userDeviceParamList.append("Vt") - tempstatList.append("Vt="+vt) - #Running loop over default parameter of OpenModelica - for default in self.mappingData["Devices"][deviceName]["default"]: + tempstatList.append("Vt=" + vt) + # Running loop over default parameter of OpenModelica + for default in (self.mappingData + ["Devices"] + [deviceName] + ["default"] + ): if default in userDeviceParamList: continue else: - defaultValue = self.mappingData["Devices"][deviceName]["default"][default] - tempstatList.append(default+"="+self.getUnitVal(defaultValue)+" ") - - stat += ",".join(str(item) for item in tempstatList)+");" - + defaultValue = (self.mappingData + ["Devices"] + [deviceName] + ["default"] + [default] + ) + tempstatList.append( + default + "=" + + self.getUnitVal(defaultValue) + " ") + + stat += ",".join(str(item) for item in tempstatList) + ");" + else: - stat = self.mappingData["Devices"][deviceName]["import"]+" "+ words[0] +";" + stat = (self.mappingData + ["Devices"] + [deviceName] + ["import"] + ) + " " + words[0] + ";" modelicaCompInit.append(stat) - - elif deviceName=='q': + + elif deviceName == 'q': trans = transInfo[words[4]] if trans == 'npn': - start = self.mappingData["Devices"][deviceName]["import"]+".NPN" + start = ( + self.mappingData["Devices"][deviceName]["import"] + ) + ".NPN" elif trans == 'pnp': - start = self.mappingData["Devices"][deviceName]["import"]+".PNP" + start = self.mappingData( + ["Devices"] + [deviceName] + ["import"] + ) + ".PNP" else: - print "Transistor "+str(trans)+" Not found" + print("Transistor " + str(trans) + " Not found") sys.exit(1) - - stat = start+" "+words[0]+"(" - tempstatList=[] - userDeviceParamList=[] + + stat = start + " " + words[0] + "(" + tempstatList = [] + userDeviceParamList = [] refName = words[4] for key in modelInfo[refName]: - #If parameter is not mapped then it will just pass + # If parameter is not mapped then it will just pass try: - if key=="vaf": - inv_vak = float(self.getUnitVal(modelInfo[refName][key])) - vak_temp = 1/inv_vak + if key == "vaf": + inv_vak = float( + self.getUnitVal( + modelInfo[refName][key])) + vak_temp = 1 / inv_vak vak = str(vak_temp) - tempstatList.append("Vak="+vak+" ") + tempstatList.append("Vak=" + vak + " ") userDeviceParamList.append(str("Vak")) else: - actualModelicaParam = self.mappingData["Devices"][deviceName]["mapping"][key] - tempstatList.append(actualModelicaParam+"="+self.getUnitVal(modelInfo[refName][key])+" ") - userDeviceParamList.append(str(actualModelicaParam)) - except: + actualModelicaParam = ( + self.mappingData + ["Devices"] + [deviceName] + ["mapping"] + [key] + ) + tempstatList.append( + actualModelicaParam + + "=" + + self.getUnitVal( + modelInfo[refName][key]) + + " ") + userDeviceParamList.append( + str(actualModelicaParam)) + except BaseException: pass - #Running loop over default parameter of OpenModelica - for default in self.mappingData["Devices"][deviceName]["default"]: + # Running loop over default parameter of OpenModelica + for default in ( + self.mappingData + ["Devices"] + [deviceName] + ["default"] + ): if default in userDeviceParamList: continue else: - defaultValue = self.mappingData["Devices"][deviceName]["default"][default] - tempstatList.append(default+"="+self.getUnitVal(defaultValue)+" ") - - stat += ",".join(str(item) for item in tempstatList)+");" + defaultValue = ( + self.mappingData + ["Devices"] + [deviceName] + ["default"] + [default] + ) + tempstatList.append( + default + "=" + self.getUnitVal(defaultValue) + + " ") + + stat += ",".join(str(item) for item in tempstatList) + ");" modelicaCompInit.append(stat) - - elif deviceName=='m': + + elif deviceName == 'm': eachline = eachline.split(words[5]) eachline = eachline[1] eachline = eachline.strip() - eachline = eachline.replace(' = ', '=').replace('= ','=').replace(' =','=').replace(' * ', '*').replace(' + ', '+').replace(' { ', '').replace(' } ', '') + eachline = eachline.replace( + ' = ', '=').replace( + '= ', '=').replace( + ' =', '=').replace( + ' * ', '*').replace( + ' + ', '+').replace( + ' { ', '').replace( + ' } ', '') eachline = eachline.split() mosInfo[words[0]] = {} for each in eachline: if len(each) > 1: - each = each.split('=') + each = each.split('=') mosInfo[words[0]][each[0]] = each[1] trans = transInfo[words[5]] - + if trans == 'nmos': - start = self.mappingData["Devices"][deviceName]["import"]+".Mn" - elif trans=='pmos' : - start = self.mappingData["Devices"][deviceName]["import"]+".Mp" + start = ( + self.mappingData + ["Devices"] + [deviceName] + ["import"] + ) + ".Mn" + elif trans == 'pmos': + start = ( + self.mappingData + ["Devices"] + [deviceName] + ["import"] + ) + ".Mp" else: - print "MOSFET "+str(trans)+" not found" + print("MOSFET " + str(trans) + " not found") sys.exit(1) - - - stat = start+" "+words[0]+"(" - tempstatList=[] - userDeviceParamList=[] + + stat = start + " " + words[0] + "(" + tempstatList = [] + userDeviceParamList = [] refName = words[5] - + for key in modelInfo[refName]: - #If parameter is not mapped then it will just pass + # If parameter is not mapped then it will just pass try: - if key=="uo": - U0 = str(float(self.getUnitVal(modelInfo[refName][key]))*0.0001) - tempstatList.append("U0="+U0+" ") + if key == "uo": + U0 = str( + float( + self.getUnitVal( + modelInfo[refName][key])) * + 0.0001) + tempstatList.append("U0=" + U0 + " ") userDeviceParamList.append(str("U0")) else: - actualModelicaParam = self.mappingData["Devices"][deviceName]["mapping"][key] - tempstatList.append(actualModelicaParam+"="+self.getUnitVal(modelInfo[refName][key])+" ") - userDeviceParamList.append(str(actualModelicaParam)) + actualModelicaParam = ( + self.mappingData + ["Devices"] + [deviceName] + ["mapping"] + [key] + ) + tempstatList.append( + actualModelicaParam + + "=" + + self.getUnitVal( + modelInfo[refName][key]) + + " ") + userDeviceParamList.append( + str(actualModelicaParam)) except Exception as err: - print str(err) - - #Running loop over default parameter of OpenModelica - for default in self.mappingData["Devices"][deviceName]["default"]: + print(str(err)) + + # Running loop over default parameter of OpenModelica + for default in ( + self.mappingData + ["Devices"] + [deviceName] + ["default"] + ): if default in userDeviceParamList: continue else: - defaultValue = self.mappingData["Devices"][deviceName]["default"][default] - tempstatList.append(default+"="+self.getUnitVal(defaultValue)+" ") - - - #Adding LEVEL(This is constant not the device level) - tempstatList.append("Level=1"+" ") - + defaultValue = ( + self.mappingData + ["Devices"] + [deviceName] + ["default"] + [default] + ) + tempstatList.append( + default + "=" + self.getUnitVal(defaultValue) + " " + ) + + # Adding LEVEL(This is constant not the device level) + tempstatList.append("Level=1" + " ") + try: l = mosInfo[words[0]]['l'] - tempstatList.append("L="+self.getUnitVal(l)+" ") + tempstatList.append("L=" + self.getUnitVal(l) + " ") except KeyError: - tempstatList.append("L=1e-6"+" ") + tempstatList.append("L=1e-6" + " ") try: w = mosInfo[words[0]]['w'] - tempstatList.append("W="+self.getUnitVal(w)+" ") + tempstatList.append("W=" + self.getUnitVal(w) + " ") except KeyError: - tempstatList.append("W=100e-6"+" ") + tempstatList.append("W=100e-6" + " ") try: As = mosInfo[words[0]]['as'] ad = mosInfo[words[0]]['ad'] - tempstatList.append("AS="+self.getUnitVal(As)+" ") - tempstatList.append("AD="+self.getUnitVal(ad)+" ") + tempstatList.append("AS=" + self.getUnitVal(As) + " ") + tempstatList.append("AD=" + self.getUnitVal(ad) + " ") except KeyError: - tempstatList.append("AS=0"+" ") - tempstatList.append("AD=0"+" ") + tempstatList.append("AS=0" + " ") + tempstatList.append("AD=0" + " ") try: ps = mosInfo[words[0]]['ps'] pd = mosInfo[words[0]]['pd'] - tempstatList.append("PS="+self.getUnitVal(ps)+" ") - tempstatList.append("PD="+self.getUnitVal(pd)+" ") + tempstatList.append("PS=" + self.getUnitVal(ps) + " ") + tempstatList.append("PD=" + self.getUnitVal(pd) + " ") except KeyError: - tempstatList.append("PS=0"+" ") - tempstatList.append("PD=0"+" ") - - stat += ",".join(str(item) for item in tempstatList)+");" + tempstatList.append("PS=0" + " ") + tempstatList.append("PD=0" + " ") + + stat += ",".join(str(item) for item in tempstatList) + ");" modelicaCompInit.append(stat) - - elif deviceName=='j': + + elif deviceName == 'j': trans = transInfo[words[4]] """ if trans == 'njf': - start = self.mappingData["Devices"][deviceName]["import"]+".J_NJFJFET" + start = self.mappingData( + ["Devices"] + [deviceName] + ["import"] + )+".J_NJFJFET" elif trans == 'pjf': - start = self.mappingData["Devices"][deviceName]["import"]+".J_PJFJFET" + start = self.mappingData( + ["Devices"] + [deviceName] + ["import"] + )+".J_PJFJFET" else: print "JFET "+str(trans)+" Not found" sys.exit(1) """ start = self.mappingData["Devices"][deviceName]["import"] - - stat = start+" "+words[0]+"(modelcard(" - tempstatList=[] - userDeviceParamList=[] + + stat = start + " " + words[0] + "(modelcard(" + tempstatList = [] + userDeviceParamList = [] refName = words[4] for key in modelInfo[refName]: - #If parameter is not mapped then it will just pass + # If parameter is not mapped then it will just pass try: - actualModelicaParam = self.mappingData["Devices"][deviceName]["mapping"][key] - tempstatList.append(actualModelicaParam+"="+self.getUnitVal(modelInfo[refName][key])+" ") + actualModelicaParam = self.mappingData( + ["Devices"] + [deviceName] + ["mapping"] + [key] + ) + tempstatList.append( + actualModelicaParam + + "=" + + self.getUnitVal( + modelInfo[refName][key]) + + " ") userDeviceParamList.append(str(actualModelicaParam)) - except: + except BaseException: pass - #Running loop over default parameter of OpenModelica - for default in self.mappingData["Devices"][deviceName]["default"]: + # Running loop over default parameter of OpenModelica + for default in ( + self.mappingData + ["Devices"] + [deviceName] + ["default"] + ): if default in userDeviceParamList: continue else: - defaultValue = self.mappingData["Devices"][deviceName]["default"][default] - tempstatList.append(default+"="+self.getUnitVal(defaultValue)+" ") - - stat += ",".join(str(item) for item in tempstatList)+"));" + defaultValue = ( + self.mappingData + ["Devices"] + [deviceName] + ["default"] + [default] + ) + tempstatList.append( + default + "=" + self.getUnitVal(defaultValue) + " " + ) + + stat += ",".join(str(item) for item in tempstatList) + "));" modelicaCompInit.append(stat) - - - - #Empty device details as well - self.deviceDetail[:]=[] - #Lets start for Subcircuit + # Empty device details as well + self.deviceDetail[:] = [] + + # Lets start for Subcircuit for eachline in self.subCktDetail: global point global subname temp_line = eachline.split() temp = temp_line[0].split('x') index = temp[1] - for i in range(0,len(temp_line),1): + for i in range(0, len(temp_line), 1): if temp_line[i] in subcktName: subname = temp_line[i] numNodesSub[subname] = i - 1 point = i if len(temp_line) > point + 1: - rem = temp_line[point+1:len(temp_line)] + rem = temp_line[point + 1:len(temp_line)] rem_new = ','.join(rem) - stat = subname + ' ' + subname +'_instance' + index + '(' + rem_new + ');' + stat = subname + ' ' + subname + \ + '_instance' + index + '(' + rem_new + ');' else: - stat = subname + ' ' + subname +'_instance' + index + ';' + stat = subname + ' ' + subname + '_instance' + index + ';' modelicaCompInit.append(stat) - - #Empty Sub Circuit Detail - self.subCktDetail[:] = [] - - #Lets start for inbuilt model of ngspice + + # Empty Sub Circuit Detail + self.subCktDetail[:] = [] + + # Lets start for inbuilt model of ngspice for eachline in compInfo: - words=eachline.split() + words = eachline.split() value = self.getUnitVal(words[-1]) if eachline[0] == 'a' or eachline[0] == 'A': userModelParamList = [] refName = words[-1] actualModelName = inbuiltModelDict[refName] - + start = self.mappingData["Models"][actualModelName]["import"] - stat = start +" "+ words[0]+"(" - tempstatList=[] - + stat = start + " " + words[0] + "(" + tempstatList = [] + for key in modelInfo[refName]: - #If parameter is not mapped then it will just pass + # If parameter is not mapped then it will just pass try: - actualModelicaParam = self.mappingData["Models"][actualModelName]["mapping"][key] - tempstatList.append(actualModelicaParam+"="+self.getUnitVal(modelInfo[refName][key])+" ") + actualModelicaParam = ( + self.mappingData + ["Models"] + [actualModelName] + ["mapping"] + [key] + ) + tempstatList.append( + actualModelicaParam + + "=" + + self.getUnitVal( + modelInfo[refName][key]) + + " ") userModelParamList.append(str(actualModelicaParam)) - except: + except BaseException: pass - - #Running loop over default parameter of OpenModelica - for default in self.mappingData["Models"][actualModelName]["default"]: + + # Running loop over default parameter of OpenModelica + for default in ( + self.mappingData + ["Models"] + [actualModelName] + ["default"] + ): if default in userModelParamList: continue else: - defaultValue = self.mappingData["Models"][actualModelName]["default"][default] - tempstatList.append(default+"="+self.getUnitVal(defaultValue)+" ") - - stat += ",".join(str(item) for item in tempstatList)+");" - modelicaCompInit.append(stat) - + defaultValue = ( + self.mappingData + ["Models"] + [actualModelName] + ["default"] + [default] + ) + tempstatList.append( + default + "=" + self.getUnitVal(defaultValue) + " " + ) + + stat += ",".join(str(item) for item in tempstatList) + ");" + modelicaCompInit.append(stat) + elif eachline[0] == 'r': - stat = 'Analog.Basic.Resistor ' + words[0] + '(R = ' + value + ');' + stat = 'Analog.Basic.Resistor ' + \ + words[0] + '(R = ' + value + ');' modelicaCompInit.append(stat) elif eachline[0] == 'c': - stat = 'Analog.Basic.Capacitor ' + words[0] + '(C = ' + value + ');' + stat = 'Analog.Basic.Capacitor ' + \ + words[0] + '(C = ' + value + ');' modelicaCompInit.append(stat) elif eachline[0] == 'l': - stat = 'Analog.Basic.Inductor ' + words[0] + '(L = ' + value + ');' - modelicaCompInit.append(stat) + stat = 'Analog.Basic.Inductor ' + \ + words[0] + '(L = ' + value + ');' + modelicaCompInit.append(stat) elif eachline[0] == 'e': - stat = 'Analog.Basic.VCV ' + words[0] + '(gain = ' + self.getUnitVal(words[5]) + ');' - modelicaCompInit.append(stat) + stat = 'Analog.Basic.VCV ' + \ + words[0] + '(gain = ' + self.getUnitVal(words[5]) + ');' + modelicaCompInit.append(stat) elif eachline[0] == 'g': - stat = 'Analog.Basic.VCC ' + words[0] + '(transConductance = ' + self.getUnitVal(words[5]) + ');' - modelicaCompInit.append(stat) + stat = 'Analog.Basic.VCC ' + \ + words[0] + '(transConductance = ' + \ + self.getUnitVal(words[5]) + ');' + modelicaCompInit.append(stat) elif eachline[0] == 'f': - stat = 'Analog.Basic.CCC ' + words[0] + '(gain = ' + self.getUnitVal(words[4]) + ');' - modelicaCompInit.append(stat) + stat = 'Analog.Basic.CCC ' + \ + words[0] + '(gain = ' + self.getUnitVal(words[4]) + ');' + modelicaCompInit.append(stat) elif eachline[0] == 'h': - stat = 'Analog.Basic.CCV ' + words[0] + '(transResistance = ' + self.getUnitVal(words[4]) + ');' + stat = 'Analog.Basic.CCV ' + \ + words[0] + '(transResistance = ' + \ + self.getUnitVal(words[4]) + ');' modelicaCompInit.append(stat) else: continue - - + if '0' or 'gnd' in node: modelicaCompInit.append('Analog.Basic.Ground g;') return modelicaCompInit, numNodesSub - - def getSubInterface(self,subname,numNodesSub): + + def getSubInterface(self, subname, numNodesSub): """ Get the list of nodes for subcircuit in .subckt line """ @@ -648,27 +867,28 @@ class NgMoConverter: subOptionInfo_p, subSchemInfo_p = self.separateNetlistInfo(data_p) if len(subOptionInfo_p) > 0: newline = subOptionInfo_p[0] - newline = newline.split('.subckt '+ subname) + newline = newline.split('.subckt ' + subname) intLine = newline[1].split() newindex = numNodesSub[subname] nodesInfoLine = intLine[0:newindex] return nodesInfoLine - - def getSubParamLine(self,subname, numNodesSub, subParamInfo,dir_name): + + def getSubParamLine(self, subname, numNodesSub, subParamInfo, dir_name): """ - Take subcircuit name and give the info related to parameters in the first line and initialize it in + Take subcircuit name and give the info related + to parameters in the first line and initialize it in """ - #nodeSubInterface = [] + # nodeSubInterface = [] subOptionInfo_p = [] subSchemInfo_p = [] filename_t = subname + '.sub' filename_t = os.path.join(dir_name, filename_t) data_p = self.readNetlist(filename_t) subOptionInfo_p, subSchemInfo_p = self.separateNetlistInfo(data_p) - + if len(subOptionInfo_p) > 0: newline = subOptionInfo_p[0] - newline = newline.split('.subckt '+ subname) + newline = newline.split('.subckt ' + subname) intLine = newline[1].split() newindex = numNodesSub[subname] appen_line = intLine[newindex:len(intLine)] @@ -677,11 +897,12 @@ class NgMoConverter: paramLine = paramLine.translate(maketrans('{}', ' ')) subParamInfo.append(paramLine) return subParamInfo - - def nodeSeparate(self,compInfo, ifSub, subname, subcktName,numNodesSub): + + def nodeSeparate(self, compInfo, ifSub, subname, subcktName, numNodesSub): """ - separate the node numbers and create nodes in modelica file; - the nodes in the subckt line should not be inside protected keyword. pinInit is the one that goes under protected keyword. + separate the node numbers and create nodes in modelica file; + the nodes in the subckt line should not be inside protected keyword. + pinInit is the one that goes under protected keyword. """ node = [] nodeTemp = [] @@ -689,81 +910,78 @@ class NgMoConverter: pinInit = 'Modelica.Electrical.Analog.Interfaces.Pin ' pinProtectedInit = 'Modelica.Electrical.Analog.Interfaces.Pin ' protectedNode = [] - #print "CompInfo coming to nodeSeparate function: compInfo",compInfo - - #Removing '[' and ']' from compInfo for Digital node - for i in range(0,len(compInfo),1): - compInfo[i] = compInfo[i].replace("[","").replace("]","") - - + # print "CompInfo coming to nodeSeparate function: compInfo",compInfo + + # Removing '[' and ']' from compInfo for Digital node + for i in range(0, len(compInfo), 1): + compInfo[i] = compInfo[i].replace("[", "").replace("]", "") + for eachline in compInfo: words = eachline.split() - - if eachline[0] in ['m', 'e', 'g', 't','M','E','G','T']: + + if eachline[0] in ['m', 'e', 'g', 't', 'M', 'E', 'G', 'T']: nodeTemp.append(words[1]) nodeTemp.append(words[2]) nodeTemp.append(words[3]) nodeTemp.append(words[4]) - elif eachline[0] in ['q', 'j','J','Q']: + elif eachline[0] in ['q', 'j', 'J', 'Q']: nodeTemp.append(words[1]) nodeTemp.append(words[2]) nodeTemp.append(words[3]) - elif eachline[0]=='x' or eachline[0]=='X': + elif eachline[0] == 'x' or eachline[0] == 'X': templine = eachline.split() - for i in range(0,len(templine),1): + for i in range(0, len(templine), 1): if templine[i] in subcktName: - point = i - #print "Added in node----->",words[1:point] + point = i + # print "Added in node----->",words[1:point] nodeTemp.extend(words[1:point]) else: nodeTemp.append(words[1]) nodeTemp.append(words[2]) - - - - #Replace hyphen '-' from node + + # Replace hyphen '-' from node for i in nodeTemp: if i not in node: - i = i.replace("-","") + i = i.replace("-", "") node.append(i) - - - for i in range(0, len(node),1): + + for i in range(0, len(node), 1): nodeDic[node[i]] = 'n' + node[i] if ifSub == '0': - if i != len(node)-1: + if i != len(node) - 1: pinInit = pinInit + nodeDic[node[i]] + ', ' else: pinInit = pinInit + nodeDic[node[i]] else: - nonprotectedNode = self.getSubInterface(subname, numNodesSub) + nonprotectedNode = self.getSubInterface(subname, numNodesSub) if node[i] in nonprotectedNode: continue else: protectedNode.append(node[i]) if ifSub == '1': if len(nonprotectedNode) > 0: - for i in range(0, len(nonprotectedNode),1): - if i != len(nonprotectedNode)-1: - pinProtectedInit = pinProtectedInit + nodeDic[nonprotectedNode[i]] + ',' + for i in range(0, len(nonprotectedNode), 1): + if i != len(nonprotectedNode) - 1: + pinProtectedInit = pinProtectedInit + \ + nodeDic[nonprotectedNode[i]] + ',' else: - pinProtectedInit = pinProtectedInit + nodeDic[nonprotectedNode[i]] + pinProtectedInit = pinProtectedInit + \ + nodeDic[nonprotectedNode[i]] if len(protectedNode) > 0: - for i in range(0, len(protectedNode),1): - if i != len(protectedNode)-1: + for i in range(0, len(protectedNode), 1): + if i != len(protectedNode) - 1: pinInit = pinInit + nodeDic[protectedNode[i]] + ',' else: pinInit = pinInit + nodeDic[protectedNode[i]] pinInit = pinInit + ';' pinProtectedInit = pinProtectedInit + ';' - #print "Node---->",node - #print "nodeDic----->",nodeDic - #print "PinInit----->",pinInit - #print "pinProtectedinit--->",pinProtectedInit + # print "Node---->",node + # print "nodeDic----->",nodeDic + # print "PinInit----->",pinInit + # print "pinProtectedinit--->",pinProtectedInit return node, nodeDic, pinInit, pinProtectedInit - - - def connectInfo(self,compInfo, node, nodeDic, numNodesSub,subcktName): + + def connectInfo(self, compInfo, node, nodeDic, numNodesSub, subcktName): """ Make node connections in the modelica netlist """ @@ -771,32 +989,44 @@ class NgMoConverter: sourcesInfo = self.separateSource(compInfo) for eachline in compInfo: words = eachline.split() - - #Remove '-' from compInfo - for i in range(0,len(words),1): - words[i] = words[i].replace("-","") - - if eachline[0]=='r' or eachline[0]=='R' or eachline[0]=='c' or eachline[0]=='C' or eachline[0]=='d' or eachline[0]=='D' \ - or eachline[0]=='l' or eachline[0]=='L' or eachline[0]=='v' or eachline[0]=='V' or eachline[0]=='i' or eachline[0]=='I': + + # Remove '-' from compInfo + for i in range(0, len(words), 1): + words[i] = words[i].replace("-", "") + + if( + eachline[0] == 'r' or + eachline[0] == 'R' or + eachline[0] == 'c' or + eachline[0] == 'C' or + eachline[0] == 'd' or + eachline[0] == 'D' or + eachline[0] == 'l' or + eachline[0] == 'L' or + eachline[0] == 'v' or + eachline[0] == 'V' or + eachline[0] == 'i' or + eachline[0] == 'I' + ): conn = 'connect(' + words[0] + '.p,' + nodeDic[words[1]] + ');' connInfo.append(conn) conn = 'connect(' + words[0] + '.n,' + nodeDic[words[2]] + ');' connInfo.append(conn) - elif eachline[0]=='q' or eachline[0]=='Q': + elif eachline[0] == 'q' or eachline[0] == 'Q': conn = 'connect(' + words[0] + '.C,' + nodeDic[words[1]] + ');' connInfo.append(conn) conn = 'connect(' + words[0] + '.B,' + nodeDic[words[2]] + ');' connInfo.append(conn) conn = 'connect(' + words[0] + '.E,' + nodeDic[words[3]] + ');' connInfo.append(conn) - elif eachline[0]=='j' or eachline[0]=='J': - conn = 'connect('+words[0]+'.D,' + nodeDic[words[1]]+');' + elif eachline[0] == 'j' or eachline[0] == 'J': + conn = 'connect(' + words[0] + '.D,' + nodeDic[words[1]] + ');' connInfo.append(conn) - conn = 'connect('+words[0]+'.G,' + nodeDic[words[2]]+');' + conn = 'connect(' + words[0] + '.G,' + nodeDic[words[2]] + ');' connInfo.append(conn) - conn = 'connect('+words[0]+'.S,' + nodeDic[words[3]]+');' + conn = 'connect(' + words[0] + '.S,' + nodeDic[words[3]] + ');' connInfo.append(conn) - elif eachline[0]=='m' or eachline[0]=='M': + elif eachline[0] == 'm' or eachline[0] == 'M': conn = 'connect(' + words[0] + '.D,' + nodeDic[words[1]] + ');' connInfo.append(conn) conn = 'connect(' + words[0] + '.G,' + nodeDic[words[2]] + ');' @@ -805,39 +1035,50 @@ class NgMoConverter: connInfo.append(conn) conn = 'connect(' + words[0] + '.B,' + nodeDic[words[4]] + ');' connInfo.append(conn) - elif eachline[0] in ['f','h','F','H']: + elif eachline[0] in ['f', 'h', 'F', 'H']: vsource = words[3] sourceNodes = sourcesInfo[vsource] - #print "Source Nodes------>",sourceNodes - #print "Source Info------->",sourcesInfo - #sourceNodes = sourceNodes.split() #No need to split as it is in the form of list - conn = 'connect(' + words[0] + '.p1,'+ nodeDic[sourceNodes[0]] + ');' + # print "Source Nodes------>",sourceNodes + # print "Source Info------->",sourcesInfo + # sourceNodes = sourceNodes.split() #No need to split as it is + # in the form of list + conn = 'connect(' + words[0] + '.p1,' + \ + nodeDic[sourceNodes[0]] + ');' connInfo.append(conn) - conn = 'connect(' + words[0] + '.n1,'+ nodeDic[sourceNodes[1]] + ');' + conn = 'connect(' + words[0] + '.n1,' + \ + nodeDic[sourceNodes[1]] + ');' connInfo.append(conn) - conn = 'connect(' + words[0] + '.p2,'+ nodeDic[words[1]] + ');' + conn = 'connect(' + words[0] + '.p2,' + \ + nodeDic[words[1]] + ');' connInfo.append(conn) - conn = 'connect(' + words[0] + '.n2,'+ nodeDic[words[2]] + ');' + conn = 'connect(' + words[0] + '.n2,' + \ + nodeDic[words[2]] + ');' connInfo.append(conn) - elif eachline[0] in ['g','e','G','E']: - conn = 'connect(' + words[0] + '.p1,'+ nodeDic[words[3]] + ');' + elif eachline[0] in ['g', 'e', 'G', 'E']: + conn = 'connect(' + words[0] + '.p1,' + \ + nodeDic[words[3]] + ');' connInfo.append(conn) - conn = 'connect(' + words[0] + '.n1,'+ nodeDic[words[4]] + ');' + conn = 'connect(' + words[0] + '.n1,' + \ + nodeDic[words[4]] + ');' connInfo.append(conn) - conn = 'connect(' + words[0] + '.p2,'+ nodeDic[words[1]] + ');' + conn = 'connect(' + words[0] + '.p2,' + \ + nodeDic[words[1]] + ');' connInfo.append(conn) - conn = 'connect(' + words[0] + '.n2,'+ nodeDic[words[2]] + ');' + conn = 'connect(' + words[0] + '.n2,' + \ + nodeDic[words[2]] + ');' connInfo.append(conn) - elif eachline[0]=='x' or eachline[0]=='X': + elif eachline[0] == 'x' or eachline[0] == 'X': templine = eachline.split() temp = templine[0].split('x') index = temp[1] - for i in range(0,len(templine),1): - if templine[i] in subcktName: + for i in range(0, len(templine), 1): + if templine[i] in subcktName: subname = templine[i] nodeNumInfo = self.getSubInterface(subname, numNodesSub) for i in range(0, numNodesSub[subname], 1): - conn = 'connect(' + subname + '_instance' + index + '.' + 'n'+ nodeNumInfo[i] + ',' + nodeDic[words[i+1]] + ');' + conn = 'connect(' + subname + '_instance' + index + '.' + \ + 'n' + nodeNumInfo[i] + ',' + \ + nodeDic[words[i + 1]] + ');' connInfo.append(conn) else: continue @@ -847,28 +1088,24 @@ class NgMoConverter: elif 'gnd' in node: conn = 'connect(g.p,ngnd);' connInfo.append(conn) - - - - + return connInfo - - - def procesSubckt(self,subcktName,numNodesSub,dir_name): - - #Process the subcircuit file .sub in the project folder - - #subcktDic = {} + + def procesSubckt(self, subcktName, numNodesSub, dir_name): + + # Process the subcircuit file .sub in the project folder + + # subcktDic = {} subOptionInfo = [] subSchemInfo = [] subModel = [] subModelInfo = {} - subsubName = [] + subsubName = [] subParamInfo = [] nodeSubInterface = [] nodeSub = [] nodeDicSub = {} - pinInitsub = [] + # pinInitsub = [] connSubInfo = [] if len(subcktName) > 0: for eachsub in subcktName: @@ -876,81 +1113,107 @@ class NgMoConverter: basename = filename filename = os.path.join(dir_name, filename) data = self.readNetlist(filename) - #print "Data-------------------->",data + # print "Data-------------------->",data subOptionInfo, subSchemInfo = self.separateNetlistInfo(data) - #print "SubOptionInfo------------------->",subOptionInfo - #print "SubSchemInfo-------------------->",subSchemInfo + # print "SubOptionInfo------------------->",subOptionInfo + # print "SubSchemInfo-------------------->",subSchemInfo if len(subOptionInfo) > 0: newline = subOptionInfo[0] - subInitLine = newline - newline = newline.split('.subckt') + # subInitLine = newline + newline = newline.split('.subckt') intLine = newline[1].split() - for i in range(0,len(intLine),1): + for i in range(0, len(intLine), 1): nodeSubInterface.append(intLine[i]) - - subModel, subModelInfo, subsubName, subParamInfo,subtransInfo,subInbuiltModelDict = self.addModel(subOptionInfo) - #print "Sub Model------------------------------------>",subModel - #print "SubModelInfo---------------------------------->",subModelInfo - #print "subsubName------------------------------------->",subsubName - #print "subParamInfo----------------------------------->",subParamInfo - #print "subtransInfo----------------------------------->",subtransInfo - #print "subInbuiltModel----------------------------------->",subInbuiltModelDict - + + subModel, subModelInfo,\ + subsubName, subParamInfo,\ + subtransInfo, subInbuiltModelDict = ( + self.addModel(subOptionInfo) + ) + # print "Sub Model------------------------------->",subModel + # print "SubModelInfo------------------------>",subModelInfo + # print "subsubName---------------------------->",subsubName + # print "subParamInfo------------------------>",subParamInfo + # print "subtransInfo------------------------>",subtransInfo + # print "subInbuiltModel-------------->",subInbuiltModelDict + IfMOSsub = '0' for eachline in subSchemInfo: - #words = eachline.split() + # words = eachline.split() if eachline[0] == 'm': IfMOSsub = '1' break subsubOptionInfo = [] subsubSchemInfo = [] if len(subsubName) > 0: - #subsubOptionInfo = [] - #subsubSchemInfo = [] + # subsubOptionInfo = [] + # subsubSchemInfo = [] for eachsub in subsubName: filename_st = eachsub + '.sub' filename_stemp = os.path.join(dir_name, filename_st) data = self.readNetlist(filename_stemp) - subsubOptionInfo, subsubSchemInfo = self.separateNetlistInfo(data) + subsubOptionInfo, subsubSchemInfo = ( + self.separateNetlistInfo(data) + ) for eachline in subsubSchemInfo: - #words = eachline.split() + # words = eachline.split() if eachline[0] == 'm': IfMOSsub = '1' break - #print "subsubOptionInfo-------------------------->",subsubOptionInfo - #print "subsubSchemInfo-------------------------->",subsubSchemInfo - - modelicaSubParam = self.processParam(subParamInfo) - #print "modelicaSubParam------------------->",modelicaSubParam - nodeSub, nodeDicSub, pinInitSub, pinProtectedInitSub = self.nodeSeparate(subSchemInfo, '1', eachsub, subsubName,numNodesSub) - #print "NodeSub------------------------->",nodeSub - #print "NodeDicSub-------------------------->",nodeDicSub - #print "PinInitSub-------------------------->",pinInitSub - #print "PinProtectedInitSub------------------->",pinProtectedInitSub - modelicaSubCompInit, numNodesSubsub = self.compInit(subSchemInfo, nodeSub, subModelInfo, subsubName,dir_name,subtransInfo,subInbuiltModelDict) - #print "modelicaSubCompInit--------------------->",modelicaSubCompInit - #print "numNodesSubsub-------------------------->",numNodesSubsub - modelicaSubParamNew = self.getSubParamLine(eachsub, numNodesSub, modelicaSubParam,dir_name) ###Ask Manas - #print "modelicaSubParamNew----------------->",modelicaSubParamNew - connSubInfo = self.connectInfo(subSchemInfo, nodeSub, nodeDicSub, numNodesSubsub,subcktName) - #print "connSubInfo----------------->",connSubInfo + # print "subsubOptionInfo------------------>",subsubOptionInfo + # print "subsubSchemInfo-------------------->",subsubSchemInfo + + modelicaSubParam = self.processParam(subParamInfo) + # print "modelicaSubParam------------------>",modelicaSubParam + nodeSub, nodeDicSub, pinInitSub,\ + pinProtectedInitSub = self.nodeSeparate( + subSchemInfo, '1', eachsub, subsubName, numNodesSub) + # print "NodeSub------------------------->",nodeSub + # print "NodeDicSub-------------------------->",nodeDicSub + # print "PinInitSub-------------------------->",pinInitSub + # print "PinProtectedInitSub----------->",pinProtectedInitSub + modelicaSubCompInit, numNodesSubsub = self.compInit( + subSchemInfo, + nodeSub, + subModelInfo, + subsubName, + dir_name, + subtransInfo, + subInbuiltModelDict + ) + # print "modelicaSubCompInit------------>",modelicaSubCompInit + # print "numNodesSubsub---------------------->",numNodesSubsub + modelicaSubParamNew = self.getSubParamLine( + eachsub, + numNodesSub, + modelicaSubParam, + dir_name) # Ask Manas + # print "modelicaSubParamNew------------>",modelicaSubParamNew + connSubInfo = self.connectInfo( + subSchemInfo, + nodeSub, + nodeDicSub, + numNodesSubsub, + subcktName + ) + # print "connSubInfo----------------->",connSubInfo newname = basename.split('.') newfilename = newname[0] - outfilename = newfilename+ ".mo" + outfilename = newfilename + ".mo" outfilename = os.path.join(dir_name, outfilename) - out = open(outfilename,"w") + out = open(outfilename, "w") out.writelines('model ' + newfilename) out.writelines('\n') if IfMOSsub == '0': out.writelines('import Modelica.Electrical.*;') elif IfMOSsub == '1': out.writelines('import BondLib.Electrical.*;') - out.writelines('\n') + out.writelines('\n') for eachline in modelicaSubParamNew: if len(subParamInfo) == 0: continue else: - out.writelines(eachline) + out.writelines(eachline) out.writelines('\n') for eachline in modelicaSubCompInit: if len(subSchemInfo) == 0: @@ -958,7 +1221,7 @@ class NgMoConverter: else: out.writelines(eachline) out.writelines('\n') - + out.writelines(pinProtectedInitSub) out.writelines('\n') if pinInitSub != 'Modelica.Electrical.Analog.Interfaces.Pin ;': @@ -974,14 +1237,27 @@ class NgMoConverter: else: out.writelines(eachline) out.writelines('\n') - out.writelines('end '+ newfilename + ';') + out.writelines('end ' + newfilename + ';') out.writelines('\n') out.close() - - return data, subOptionInfo, subSchemInfo, subModel, subModelInfo, subsubName, \ - subParamInfo, modelicaSubCompInit, modelicaSubParam, nodeSubInterface, nodeSub, nodeDicSub, pinInitSub, connSubInfo - - + + return ( + data, + subOptionInfo, + subSchemInfo, + subModel, + subModelInfo, + subsubName, + subParamInfo, + modelicaSubCompInit, + modelicaSubParam, + nodeSubInterface, + nodeSub, + nodeDicSub, + pinInitSub, + connSubInfo + ) + def main(args): """ @@ -991,97 +1267,121 @@ def main(args): filename = sys.argv[1] map_json = sys.argv[2] else: - print "USAGE:" - print "python NgspicetoModelica.py <filename>" + print("USAGE:") + print("python NgspicetoModelica.py <filename>") sys.exit() - + dir_name = os.path.dirname(os.path.realpath(filename)) - file_basename = os.path.basename(filename) + # file_basename = os.path.basename(filename) cwd = os.getcwd() os.chdir(dir_name) - + obj_NgMoConverter = NgMoConverter(map_json) - - #Getting all the require information + + # Getting all the require information lines = obj_NgMoConverter.readNetlist(filename) - #print "Complete Lines of Ngspice netlist :lines ---------------->",lines + # print "Complete Lines of Ngspice netlist :lines ---------------->",lines optionInfo, schematicInfo = obj_NgMoConverter.separateNetlistInfo(lines) - #print "All option details like analysis,subckt,.ic,.model : OptionInfo------------------->",optionInfo - #print "Schematic connection info :schematicInfo",schematicInfo - modelName, modelInfo, subcktName, paramInfo,transInfo,inbuiltModelDict = obj_NgMoConverter.addModel(optionInfo) - #print "Name of Model : modelName-------------------->",modelName - #print "Model Information :modelInfo--------------------->",modelInfo - #print "Subcircuit Name :subcktName------------------------>",subcktName - #print "Parameter Information :paramInfo---------------------->",paramInfo - #print "InBuilt Model ---------------------->",inbuiltModelDict - - - + # print "All option details like analysis,subckt,.ic,.model : + # OptionInfo------------------->",optionInfo + # print "Schematic connection info :schematicInfo",schematicInfo + modelName, modelInfo, subcktName, paramInfo, transInfo,\ + inbuiltModelDict = ( + obj_NgMoConverter.addModel(optionInfo) + ) + # print "Name of Model : modelName-------------------->",modelName + # print "Model Information :modelInfo--------------------->",modelInfo + # print "Subcircuit Name :subcktName------------------------>",subcktName + # print "Parameter Information :paramInfo---------------------->",paramInfo + # print "InBuilt Model ---------------------->",inbuiltModelDict + modelicaParamInit = obj_NgMoConverter.processParam(paramInfo) - #print "Make modelicaParamInit from paramInfo : processParamInit------------->",modelicaParamInit + # print "Make modelicaParamInit from paramInfo + # : processParamInit------------->",modelicaParamInit compInfo, plotInfo = obj_NgMoConverter.separatePlot(schematicInfo) - #print "Plot info like plot,print etc :plotInfo",plotInfo + # print "Plot info like plot,print etc :plotInfo",plotInfo IfMOS = '0' - + for eachline in compInfo: - words = eachline.split() + # words = eachline.split() if eachline[0] == 'm': IfMOS = '1' break - + subOptionInfo = [] subSchemInfo = [] if len(subcktName) > 0: - #subOptionInfo = [] - #subSchemInfo = [] + # subOptionInfo = [] + # subSchemInfo = [] for eachsub in subcktName: filename_temp = eachsub + '.sub' data = obj_NgMoConverter.readNetlist(filename_temp) - #print "Data---------->",data - subOptionInfo, subSchemInfo = obj_NgMoConverter.separateNetlistInfo(data) + # print "Data---------->",data + subOptionInfo, subSchemInfo = ( + obj_NgMoConverter.separateNetlistInfo(data) + ) for eachline in subSchemInfo: - words = eachline.split() + # words = eachline.split() if eachline[0] == 'm': IfMOS = '1' break - #print "Subcircuit OptionInfo : subOptionInfo------------------->",subOptionInfo - #print "Subcircuit Schematic Info :subSchemInfo-------------------->",subSchemInfo - - node, nodeDic, pinInit, pinProtectedInit = obj_NgMoConverter.nodeSeparate(compInfo, '0', [], subcktName,[]) - #print "All nodes in the netlist :node---------------->",node - #print "NodeDic which will be used for modelica : nodeDic------------->",nodeDic - #print "PinInit-------------->",pinInit - #print "pinProtectedInit----------->",pinProtectedInit - - modelicaCompInit, numNodesSub = obj_NgMoConverter.compInit(compInfo,node, modelInfo, subcktName,dir_name,transInfo,inbuiltModelDict) - #print "ModelicaComponents : modelicaCompInit----------->",modelicaCompInit - #print "SubcktNumNodes : numNodesSub---------------->",numNodesSub - - connInfo = obj_NgMoConverter.connectInfo(compInfo, node, nodeDic, numNodesSub,subcktName) - - #print "ConnInfo------------------>",connInfo - - - ###After Sub Ckt Func + # print "Subcircuit OptionInfo + # : subOptionInfo------------------->",subOptionInfo + # print "Subcircuit Schematic Info + # : subSchemInfo-------------------->",subSchemInfo + + node, nodeDic, pinInit, pinProtectedInit = obj_NgMoConverter.nodeSeparate( + compInfo, '0', [], subcktName, []) + # print "All nodes in the netlist :node---------------->",node + # print "NodeDic which will be used for modelica + # : nodeDic------------->",nodeDic + # print "PinInit-------------->",pinInit + # print "pinProtectedInit----------->",pinProtectedInit + + modelicaCompInit, numNodesSub = obj_NgMoConverter.compInit( + compInfo, + node, + modelInfo, + subcktName, + dir_name, + transInfo, + inbuiltModelDict + ) + # print "ModelicaComponents + # : modelicaCompInit----------->",modelicaCompInit + # print "SubcktNumNodes + # : numNodesSub---------------->",numNodesSub + + connInfo = obj_NgMoConverter.connectInfo( + compInfo, node, nodeDic, numNodesSub, subcktName) + + # print "ConnInfo------------------>",connInfo + + # After Sub Ckt Func if len(subcktName) > 0: - data, subOptionInfo, subSchemInfo, subModel, subModelInfo, subsubName,subParamInfo, modelicaSubCompInit, modelicaSubParam,\ - nodeSubInterface,nodeSub, nodeDicSub, pinInitSub, connSubInfo = obj_NgMoConverter.procesSubckt(subcktName,numNodesSub,dir_name) #Adding 'numNodesSub' by Fahim - - #Creating Final Output file + data, subOptionInfo, subSchemInfo, subModel, subModelInfo,\ + subsubName, subParamInfo, modelicaSubCompInit, modelicaSubParam,\ + nodeSubInterface, nodeSub, nodeDicSub, pinInitSub, connSubInfo = ( + obj_NgMoConverter.procesSubckt( + subcktName, numNodesSub, dir_name + ) + ) # Adding 'numNodesSub' by Fahim + + # Creating Final Output file newfile = filename.split('.') newfilename = newfile[0] outfile = newfilename + ".mo" - out = open(outfile,"w") + out = open(outfile, "w") out.writelines('model ' + os.path.basename(newfilename)) out.writelines('\n') if IfMOS == '0': out.writelines('import Modelica.Electrical.*;') elif IfMOS == '1': out.writelines('import BondLib.Electrical.*;') - #out.writelines('import Modelica.Electrical.*;') + # out.writelines('import Modelica.Electrical.*;') out.writelines('\n') - + for eachline in modelicaParamInit: if len(paramInfo) == 0: continue @@ -1094,29 +1394,28 @@ def main(args): else: out.writelines(eachline) out.writelines('\n') - + out.writelines('protected') out.writelines('\n') out.writelines(pinInit) out.writelines('\n') out.writelines('equation') out.writelines('\n') - + for eachline in connInfo: if len(connInfo) == 0: continue else: out.writelines(eachline) out.writelines('\n') - - out.writelines('end '+ os.path.basename(newfilename) + ';') - out.writelines('\n') + out.writelines('end ' + os.path.basename(newfilename) + ';') + out.writelines('\n') out.close() os.chdir(cwd) - + # Call main function if __name__ == '__main__': diff --git a/src/projManagement/Kicad.py b/src/projManagement/Kicad.py index ec3c69da..2eaef643 100644 --- a/src/projManagement/Kicad.py +++ b/src/projManagement/Kicad.py @@ -1,95 +1,107 @@ -#=============================================================================== +# ========================================================================= # # FILE: openKicad.py -# -# USAGE: --- -# +# +# USAGE: --- +# # DESCRIPTION: It call kicad schematic -# +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Tuesday 17 Feb 2015 +# CREATED: Tuesday 17 Feb 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= import os -import Validation +from . import Validation from configuration.Appconfig import Appconfig -import Worker +from . import Worker from PyQt4 import QtGui + class Kicad: """ - This class called the Kicad Schematic,KicadtoNgspice Converter,Layout editor and Footprint Editor + This class called the Kicad Schematic,KicadtoNgspice Converter,Layout + editor and Footprint Editor """ - def __init__(self,dockarea): + + def __init__(self, dockarea): self.obj_validation = Validation.Validation() self.obj_appconfig = Appconfig() - self.obj_dockarea= dockarea - + self.obj_dockarea = dockarea + def openSchematic(self): """ This function create command to open Kicad schematic """ - print "Function : Open Kicad Schematic" + print("Function : Open Kicad Schematic") self.projDir = self.obj_appconfig.current_project["ProjectName"] try: - self.obj_appconfig.print_info('Kicad Schematic is called for project ' + self.projDir) - except: - pass - #Validating if current project is available or not - + self.obj_appconfig.print_info( + 'Kicad Schematic is called for project ' + self.projDir) + except BaseException: + pass + # Validating if current project is available or not + if self.obj_validation.validateKicad(self.projDir): - #print "calling Kicad schematic ",self.projDir + # print "calling Kicad schematic ",self.projDir self.projName = os.path.basename(self.projDir) - self.project = os.path.join(self.projDir,self.projName) - - #Creating a command to run - self.cmd = "eeschema "+self.project+".sch " + self.project = os.path.join(self.projDir, self.projName) + + # Creating a command to run + self.cmd = "eeschema " + self.project + ".sch " self.obj_workThread = Worker.WorkerThread(self.cmd) self.obj_workThread.start() - + else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('Please select the project first. You can either create new project or open existing project') - self.obj_appconfig.print_warning('Please select the project first. You can either create new project or open existing project') + self.msg.showMessage( + 'Please select the project first. You can either create' + + 'new project or open existing project') + self.obj_appconfig.print_warning( + 'Please select the project first. You can either create' + + 'new project or open existing project') self.msg.setWindowTitle("Error Message") - - + ''' - #Commenting as it is no longer needed as PBC and Layout will open from eeschema + # Commenting as it is no longer needed as PBC and Layout will open from + # eeschema def openFootprint(self): """ - This function create command to open Footprint editor + This function create command to open Footprint editor """ print "Kicad Foot print Editor called" self.projDir = self.obj_appconfig.current_project["ProjectName"] - try: - self.obj_appconfig.print_info('Kicad Footprint Editor is called for project : ' + self.projDir) + try: + self.obj_appconfig.print_info('Kicad Footprint Editor is called' + + 'for project : ' + self.projDir) except: pass #Validating if current project is available or not - + if self.obj_validation.validateKicad(self.projDir): #print "calling Kicad FootPrint Editor ",self.projDir self.projName = os.path.basename(self.projDir) self.project = os.path.join(self.projDir,self.projName) - + #Creating a command to run self.cmd = "cvpcb "+self.project+".net " self.obj_workThread = Worker.WorkerThread(self.cmd) self.obj_workThread.start() - + else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('Please select the project first. You can either create new project or open existing project') - self.obj_appconfig.print_warning('Please select the project first. You can either create new project or open existing project') + self.msg.showMessage('Please select the project first. You can' + + 'either create new project or open existing project') + self.obj_appconfig.print_warning('Please select the project' + + 'first. You can either create new project or open existing' + + 'project') self.msg.setWindowTitle("Error Message") - + def openLayout(self): """ This function create command to open Layout editor @@ -97,68 +109,78 @@ class Kicad: print "Kicad Layout is called" self.projDir = self.obj_appconfig.current_project["ProjectName"] try: - self.obj_appconfig.print_info('PCB Layout is called for project : ' + self.projDir) + self.obj_appconfig.print_info('PCB Layout is called for project : ' + + self.projDir) except: - pass + pass #Validating if current project is available or not if self.obj_validation.validateKicad(self.projDir): print "calling Kicad schematic ",self.projDir self.projName = os.path.basename(self.projDir) self.project = os.path.join(self.projDir,self.projName) - + #Creating a command to run self.cmd = "pcbnew "+self.project+".net " self.obj_workThread = Worker.WorkerThread(self.cmd) self.obj_workThread.start() - + else: - self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('Please select the project first. You can either create new project or open existing project') - self.obj_appconfig.print_warning('Please select the project first. You can either create new project or open existing project') - self.msg.setWindowTitle("Error Message") - + self.msg = QtGui.QErrorMessage(None) + self.msg.showMessage('Please select the project first. You can' + + 'either create new project or open existing project') + self.obj_appconfig.print_warning('Please select the project' + + 'first. You can either create new project or open existing' + + 'project') + self.msg.setWindowTitle("Error Message") + ''' - + def openKicadToNgspice(self): """ This function create command to call kicad to Ngspice converter. """ - print "Function: Open Kicad to Ngspice Converter" - + print("Function: Open Kicad to Ngspice Converter") + self.projDir = self.obj_appconfig.current_project["ProjectName"] try: - self.obj_appconfig.print_info('Kicad to Ngspice Conversion is called') + self.obj_appconfig.print_info( + 'Kicad to Ngspice Conversion is called') self.obj_appconfig.print_info('Current Project is ' + self.projDir) - except: + except BaseException: pass - #Validating if current project is available or not + # Validating if current project is available or not if self.obj_validation.validateKicad(self.projDir): - #Cheking if project has .cir file or not + # Cheking if project has .cir file or not if self.obj_validation.validateCir(self.projDir): self.projName = os.path.basename(self.projDir) - self.project = os.path.join(self.projDir,self.projName) - - #Creating a command to run + self.project = os.path.join(self.projDir, self.projName) + + # Creating a command to run """ - self.cmd = "python ../kicadtoNgspice/KicadtoNgspice.py " +self.project+".cir " + self.cmd = ("python ../kicadtoNgspice/KicadtoNgspice.py " + + "self.project+".cir ") self.obj_workThread = Worker.WorkerThread(self.cmd) self.obj_workThread.start() """ - var=self.project+".cir" + var = self.project + ".cir" self.obj_dockarea.kicadToNgspiceEditor(var) - - - + else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('The project does not contain any Kicad netlist file for conversion.') - self.obj_appconfig.print_error('The project does not contain any Kicad netlist file for conversion.') - self.msg.setWindowTitle("Error Message") - + self.msg.showMessage( + 'The project does not contain any Kicad netlist file for' + + 'conversion.') + self.obj_appconfig.print_error( + 'The project does not contain any Kicad netlist file for' + + 'conversion.') + self.msg.setWindowTitle("Error Message") + else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('Please select the project first. You can either create new project or open existing project') - self.obj_appconfig.print_warning('Please select the project first. You can either create new project or open existing project') - self.msg.setWindowTitle("Error Message") - -
\ No newline at end of file + self.msg.showMessage( + 'Please select the project first. You can either create' + + 'new project or open existing project') + self.obj_appconfig.print_warning( + 'Please select the project first. You can either create' + + 'new project or open existing project') + self.msg.setWindowTitle("Error Message") diff --git a/src/projManagement/Validation.py b/src/projManagement/Validation.py index a582cab5..11cdcaf9 100644 --- a/src/projManagement/Validation.py +++ b/src/projManagement/Validation.py @@ -1,23 +1,24 @@ -#=============================================================================== +# ========================================================================= # # FILE: Validation.py -# -# USAGE: --- -# -# DESCRIPTION: This module is use to create validation for openProject,newProject and other activity. -# +# +# USAGE: --- +# +# DESCRIPTION: This module is use to create validation for openProject, +# newProject and other activity. +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 12 February 2015 +# CREATED: Wednesday 12 February 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= import os -import re +import re import distutils.spawn @@ -27,108 +28,106 @@ class Validation: e.g if .proj is present in project directory or if new project name is already exist in workspace etc """ + def __init__(self): pass - - def validateOpenproj(self,projDir): + + def validateOpenproj(self, projDir): """ This function validate Open Project Information. """ - print "Function: Validating Open Project Information" + print("Function: Validating Open Project Information") projName = os.path.basename(str(projDir)) - lookProj = os.path.join(str(projDir),projName+".proj") - #Check existence of project + lookProj = os.path.join(str(projDir), projName + ".proj") + # Check existence of project if os.path.exists(lookProj): return True else: return False - - - - def validateNewproj(self,projDir): + + def validateNewproj(self, projDir): """ This Project Validate New Project Information """ - print "Function: Validating New Project Information" - - #Checking existence of project with same name + print("Function: Validating New Project Information") + + # Checking existence of project with same name if os.path.exists(projDir): - return "CHECKEXIST" #Project with name already exist + return "CHECKEXIST" # Project with name already exist else: - #Check Proper name for project. It should not have space - if re.search(r"\s",projDir ): + # Check Proper name for project. It should not have space + if re.search(r"\s", projDir): return "CHECKNAME" else: return "VALID" - - def validateKicad(self,projDir): + + def validateKicad(self, projDir): """ This function validate if Kicad components are present """ - print "FUnction : Validating for Kicad components" - if projDir == None: + print("FUnction : Validating for Kicad components") + if projDir is None: return False else: return True - - def validateCir(self,projDir): + + def validateCir(self, projDir): """ This function checks if ".cir" file is present. """ projName = os.path.basename(str(projDir)) - lookCir = os.path.join(str(projDir),projName+".cir") - #Check existence of project + lookCir = os.path.join(str(projDir), projName + ".cir") + # Check existence of project if os.path.exists(lookCir): return True else: return False - - def validateSub(self,subDir,givenNum): + + def validateSub(self, subDir, givenNum): """ This function checks if ".sub" file is present. """ subName = os.path.basename(str(subDir)) - lookSub = os.path.join(str(subDir),subName+".sub") - #Check existence of project + lookSub = os.path.join(str(subDir), subName + ".sub") + # Check existence of project if os.path.exists(lookSub): f = open(lookSub) - data=f.read() + data = f.read() f.close() - netlist=data.splitlines() + netlist = data.splitlines() for eachline in netlist: - eachline=eachline.strip() - if len(eachline)<1: + eachline = eachline.strip() + if len(eachline) < 1: continue - words=eachline.split() + words = eachline.split() if words[0] == '.subckt': - #The number of ports is specified in this line - #eg. '.subckt ua741 6 7 3' has 3 ports (6, 7 and 3). + # The number of ports is specified in this line + # eg. '.subckt ua741 6 7 3' has 3 ports (6, 7 and 3). numPorts = len(words) - 2 - print "Looksub : ",lookSub - print "Given Number of ports : ",givenNum - print "Actual Number of ports :",numPorts + print("Looksub : ", lookSub) + print("Given Number of ports : ", givenNum) + print("Actual Number of ports :", numPorts) if numPorts != givenNum: return "PORT" else: return "True" else: return "DIREC" - - def validateCirOut(self,projDir): + + def validateCirOut(self, projDir): """ This function checks if ".cir.out" file is present. """ projName = os.path.basename(str(projDir)) - lookCirOut = os.path.join(str(projDir),projName+".cir.out") - #Check existence of project + lookCirOut = os.path.join(str(projDir), projName + ".cir.out") + # Check existence of project if os.path.exists(lookCirOut): return True else: return False - - def validateTool(self,toolName): + + def validateTool(self, toolName): """ This function check if tool is present in the system """ return distutils.spawn.find_executable(toolName) is not None -
\ No newline at end of file diff --git a/src/projManagement/Worker.py b/src/projManagement/Worker.py index 6befca65..65c67dde 100644 --- a/src/projManagement/Worker.py +++ b/src/projManagement/Worker.py @@ -1,46 +1,44 @@ -#=============================================================================== +# ========================================================================= # # FILE: WorkerThread.py -# -# USAGE: --- -# +# +# USAGE: --- +# # DESCRIPTION: This class open all third party application using QT Thread -# +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Tuesday 24 Feb 2015 +# CREATED: Tuesday 24 Feb 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= from PyQt4 import QtCore import subprocess from configuration.Appconfig import Appconfig + class WorkerThread(QtCore.QThread): """ This is Thread class use to run the command """ - def __init__(self,args): + + def __init__(self, args): QtCore.QThread.__init__(self) self.args = args - - + def __del__(self): self.wait() - + def run(self): - print "Worker Thread Calling Command :",self.args + print("Worker Thread Calling Command :", self.args) self.call_system(self.args) - - def call_system(self,command): + + def call_system(self, command): procThread = Appconfig() proc = subprocess.Popen(command.split()) procThread.procThread_list.append(proc) - procThread.proc_dict[procThread.current_project['ProjectName']].append(proc.pid) - - - - + procThread.proc_dict[procThread.current_project['ProjectName']].append( + proc.pid) diff --git a/src/projManagement/Worker.py.bak b/src/projManagement/Worker.py.bak new file mode 100644 index 00000000..575ea12c --- /dev/null +++ b/src/projManagement/Worker.py.bak @@ -0,0 +1,46 @@ +#=============================================================================== +# +# FILE: WorkerThread.py +# +# USAGE: --- +# +# DESCRIPTION: This class open all third party application using QT Thread +# +# OPTIONS: --- +# REQUIREMENTS: --- +# BUGS: --- +# NOTES: --- +# AUTHOR: Fahim Khan, fahim.elex@gmail.com +# ORGANIZATION: eSim team at FOSSEE, IIT Bombay. +# CREATED: Tuesday 24 Feb 2015 +# REVISION: --- +#=============================================================================== +from PyQt4 import QtCore +import subprocess +from configuration.Appconfig import Appconfig + +class WorkerThread(QtCore.QThread): + """ + This is Thread class use to run the command + """ + def __init__(self,args): + QtCore.QThread.__init__(self) + self.args = args + + + def __del__(self): + self.wait() + + def run(self): + print("Worker Thread Calling Command :",self.args) + self.call_system(self.args) + + def call_system(self,command): + procThread = Appconfig() + proc = subprocess.Popen(command.split()) + procThread.procThread_list.append(proc) + procThread.proc_dict[procThread.current_project['ProjectName']].append(proc.pid) + + + + diff --git a/src/projManagement/newProject.py b/src/projManagement/newProject.py index 5b4af49a..40d66003 100644 --- a/src/projManagement/newProject.py +++ b/src/projManagement/newProject.py @@ -1,109 +1,116 @@ -#=============================================================================== +# ========================================================================= # # FILE: newProject.py -# -# USAGE: --- -# -# DESCRIPTION: It is called whenever new project is being called. -# +# +# USAGE: --- +# +# DESCRIPTION: It is called whenever new project is being called. +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 12 February 2015 +# CREATED: Wednesday 12 February 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= from PyQt4 import QtGui -from Validation import Validation +from .Validation import Validation from configuration.Appconfig import Appconfig import os import json + class NewProjectInfo(QtGui.QWidget): """ This class is called when User create new Project. """ - + def __init__(self): super(NewProjectInfo, self).__init__() self.obj_validation = Validation() self.obj_appconfig = Appconfig() - - def createProject(self,projName): + def createProject(self, projName): """ This function create Project related directories and files """ - #print "Create Project Called" - self.projName= projName + # print "Create Project Called" + self.projName = projName self.workspace = self.obj_appconfig.default_workspace['workspace'] - #self.projName = self.projEdit.text() - self.projName = str(self.projName).rstrip().lstrip() #Remove leading and trailing space - - self.projDir = os.path.join(self.workspace,str(self.projName)) - - - #Validation for newProject + # self.projName = self.projEdit.text() + # Remove leading and trailing space + self.projName = str(self.projName).rstrip().lstrip() + + self.projDir = os.path.join(self.workspace, str(self.projName)) + + # Validation for newProject if self.projName == "": self.reply = "NONE" else: self.reply = self.obj_validation.validateNewproj(str(self.projDir)) - - #Checking Validations Response + + # Checking Validations Response if self.reply == "VALID": - #create project directory + # create project directory try: os.mkdir(self.projDir) self.close() - self.projFile = os.path.join(self.projDir,self.projName+".proj") - f = open(self.projFile,"w") - except: - #print "Some Thing Went Wrong" + self.projFile = os.path.join( + self.projDir, self.projName + ".proj") + f = open(self.projFile, "w") + except BaseException: + # print "Some Thing Went Wrong" self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('Unable to create project. Please make sure you have write permission on '+self.workspace) + self.msg.showMessage( + 'Unable to create project. Please make sure you have' + + 'write permission on ' + + self.workspace) self.msg.setWindowTitle("Error Message") - f.write("schematicFile " + self.projName+".sch\n") + f.write("schematicFile " + self.projName + ".sch\n") f.close() - - #Now Change the current working project + + # Now Change the current working project newprojlist = [] - #self.obj_appconfig = Appconfig() - self.obj_appconfig.current_project['ProjectName'] = self.projDir - newprojlist.append(self.projName+'.proj') + # self.obj_appconfig = Appconfig() + self.obj_appconfig.current_project['ProjectName'] = self.projDir + newprojlist.append(self.projName + '.proj') self.obj_appconfig.project_explorer[self.projDir] = newprojlist - - self.obj_appconfig.print_info('New project created : ' + self.projName) - self.obj_appconfig.print_info('Current project is : ' + self.projDir) - - json.dump(self.obj_appconfig.project_explorer, open(self.obj_appconfig.dictPath,'w')) + + self.obj_appconfig.print_info( + 'New project created : ' + self.projName) + self.obj_appconfig.print_info( + 'Current project is : ' + self.projDir) + + json.dump( + self.obj_appconfig.project_explorer, open( + self.obj_appconfig.dictPath, 'w')) return self.projDir, newprojlist - + elif self.reply == "CHECKEXIST": - #print "Project already exist" + # print "Project already exist" self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('The project "'+self.projName+'" already exist.Please select the different name or delete existing project') + self.msg.showMessage( + 'The project "' + + self.projName + + '" already exist.Please select the different name or delete' + + ' existing project') self.msg.setWindowTitle("Error Message") - - + elif self.reply == "CHECKNAME": - #print "Name is not proper" + # print "Name is not proper" self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('The project name should not contain space between them') + self.msg.showMessage( + 'The project name should not contain space between them') self.msg.setWindowTitle("Error Message") - + elif self.reply == "NONE": - #print "Empty Project Name" + # print "Empty Project Name" self.msg = QtGui.QErrorMessage(self) self.msg.showMessage('The project name cannot be empty') self.msg.setWindowTitle("Error Message") - + def cancelProject(self): self.close() - - - - -
\ No newline at end of file diff --git a/src/projManagement/openProject.py b/src/projManagement/openProject.py index d980d914..6cdcbb38 100644 --- a/src/projManagement/openProject.py +++ b/src/projManagement/openProject.py @@ -1,24 +1,24 @@ -#=============================================================================== +# ========================================================================= # # FILE: openProject.py -# -# USAGE: --- -# -# DESCRIPTION: It is called whenever new project is being called. -# +# +# USAGE: --- +# +# DESCRIPTION: It is called whenever new project is being called. +# # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Fahim Khan, fahim.elex@gmail.com # ORGANIZATION: eSim team at FOSSEE, IIT Bombay. -# CREATED: Wednesday 12 February 2015 +# CREATED: Wednesday 12 February 2015 # REVISION: --- -#=============================================================================== +# ========================================================================= from PyQt4 import QtGui -from Validation import Validation +from .Validation import Validation from configuration.Appconfig import Appconfig import os import json @@ -28,45 +28,55 @@ class OpenProjectInfo(QtGui.QWidget): """ This class is called when User click on Open Project Button """ + def __init__(self): super(OpenProjectInfo, self).__init__() self.obj_validation = Validation() - + def body(self): self.obj_Appconfig = Appconfig() self.openDir = self.obj_Appconfig.default_workspace["workspace"] - self.projDir=QtGui.QFileDialog.getExistingDirectory(self,"open",self.openDir) - - if self.obj_validation.validateOpenproj(self.projDir) == True: - self.obj_Appconfig.current_project['ProjectName'] = str(self.projDir) + self.projDir = QtGui.QFileDialog.getExistingDirectory( + self, "open", self.openDir) + + if self.obj_validation.validateOpenproj(self.projDir): + self.obj_Appconfig.current_project['ProjectName'] = str( + self.projDir) if os.path.isdir(self.projDir): - print "true" - - for dirs, subdirs, filelist in os.walk(self.obj_Appconfig.current_project["ProjectName"]): - directory = dirs - files = filelist + print("true") + + for dirs, subdirs, filelist in os.walk( + self.obj_Appconfig.current_project["ProjectName"]): + # directory = dirs + # files = filelist + # above 'directory' and 'files' variable never used + pass self.obj_Appconfig.project_explorer[dirs] = filelist - json.dump(self.obj_Appconfig.project_explorer, open(self.obj_Appconfig.dictPath,'w')) + json.dump( + self.obj_Appconfig.project_explorer, open( + self.obj_Appconfig.dictPath, 'w')) self.obj_Appconfig.print_info('Open Project called') self.obj_Appconfig.print_info('Current Project is ' + self.projDir) return dirs, filelist - + else: - self.obj_Appconfig.print_error("The project doesn't contain .proj file. Please select the proper directory else you won't be able to perform any operation") - reply = QtGui.QMessageBox.critical(None, "Error Message",'''<b> Error: The project doesn't contain .proj file.</b><br/> - <b>Please select the proper project directory else you won't be able to perform any operation</b>''',QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel) - + self.obj_Appconfig.print_error( + "The project doesn't contain .proj file. Please select the" + + "proper directory else you won't be able to perform any" + + "operation") + reply = QtGui.QMessageBox.critical(None, "Error Message", + '''<b>Error: The project doesn't contain .proj file.</b><br/> + <b>Please select the proper project directory else you won't + be able to perform any operation</b>''', + QtGui.QMessageBox.Ok | + QtGui.QMessageBox.Cancel) + if reply == QtGui.QMessageBox.Ok: self.body() self.obj_Appconfig.print_info('Open Project called') - self.obj_Appconfig.print_info('Current Project is ' + self.projDir) + self.obj_Appconfig.print_info( + 'Current Project is ' + self.projDir) elif reply == QtGui.QMessageBox.Cancel: self.obj_Appconfig.print_info('No Project opened') else: pass - - - - - -
\ No newline at end of file diff --git a/src/subcircuit/Subcircuit.py b/src/subcircuit/Subcircuit.py index f53acc6a..259ae40a 100644 --- a/src/subcircuit/Subcircuit.py +++ b/src/subcircuit/Subcircuit.py @@ -5,31 +5,34 @@ from subcircuit.newSub import NewSub from subcircuit.openSub import openSub from subcircuit.convertSub import convertSub + class Subcircuit(QtGui.QWidget): """ This class creates Subcircuit GUI. """ - def __init__(self,parent=None): + + def __init__(self, parent=None): super(Subcircuit, self).__init__() QtGui.QWidget.__init__(self) - self.obj_appconfig=Appconfig() - self.obj_validation=Validation() - self.obj_dockarea=parent + self.obj_appconfig = Appconfig() + self.obj_validation = Validation() + self.obj_dockarea = parent self.layout = QtGui.QVBoxLayout() - self.splitter= QtGui.QSplitter() + self.splitter = QtGui.QSplitter() self.splitter.setOrientation(QtCore.Qt.Vertical) self.newbtn = QtGui.QPushButton('New Subcircuit Schematic') self.newbtn.setToolTip('<b>To create new Subcircuit Schematic</b>') - self.newbtn.setFixedSize(200,40) + self.newbtn.setFixedSize(200, 40) self.newbtn.clicked.connect(self.newsch) self.editbtn = QtGui.QPushButton('Edit Subcircuit Schematic') self.editbtn.setToolTip('<b>To edit existing Subcircuit Schematic</b>') - self.editbtn.setFixedSize(200,40) + self.editbtn.setFixedSize(200, 40) self.editbtn.clicked.connect(self.editsch) self.convertbtn = QtGui.QPushButton('Convert Kicad to Ngspice') - self.convertbtn.setToolTip('<b>To convert Subcircuit Kicad Netlist to Ngspice Netlist</b>') - self.convertbtn.setFixedSize(200,40) + self.convertbtn.setToolTip( + '<b>To convert Subcircuit Kicad Netlist to Ngspice Netlist</b>') + self.convertbtn.setFixedSize(200, 40) self.convertbtn.clicked.connect(self.convertsch) self.hbox = QtGui.QHBoxLayout() @@ -41,25 +44,25 @@ class Subcircuit(QtGui.QWidget): self.vbox = QtGui.QVBoxLayout() self.vbox.addLayout(self.hbox) self.vbox.addStretch(1) - + self.setLayout(self.vbox) self.show() - + def newsch(self): - text,ok = QtGui.QInputDialog.getText(self, 'New Schematic','Enter Schematic Name:') + text, ok = QtGui.QInputDialog.getText( + self, 'New Schematic', 'Enter Schematic Name:') if ok: self.schematic_name = (str(text)) self.subcircuit = NewSub() self.subcircuit.createSubcircuit(self.schematic_name) - + else: - print "Sub circuit creation cancelled" - - + print("Sub circuit creation cancelled") + def editsch(self): self.obj_opensubcircuit = openSub() self.obj_opensubcircuit.body() - + def convertsch(self): self.obj_convertsubcircuit = convertSub(self.obj_dockarea) - self.obj_convertsubcircuit.createSub()
\ No newline at end of file + self.obj_convertsubcircuit.createSub() diff --git a/src/subcircuit/convertSub.py b/src/subcircuit/convertSub.py index 358028ed..31ae3022 100644 --- a/src/subcircuit/convertSub.py +++ b/src/subcircuit/convertSub.py @@ -3,39 +3,44 @@ from projManagement.Validation import Validation from configuration.Appconfig import Appconfig import os + class convertSub(QtGui.QWidget): """ This class is called when User create new Project. """ - - def __init__(self,dockarea): + + def __init__(self, dockarea): super(convertSub, self).__init__() self.obj_validation = Validation() - self.obj_appconfig=Appconfig() - self.obj_dockarea=dockarea - + self.obj_appconfig = Appconfig() + self.obj_dockarea = dockarea + def createSub(self): """ This function create command to call kicad to Ngspice converter. """ - print "Openinig Kicad-to-Ngspice converter from Subcircuit Module" + print("Openinig Kicad-to-Ngspice converter from Subcircuit Module") self.projDir = self.obj_appconfig.current_subcircuit["SubcircuitName"] - #Validating if current project is available or not + # Validating if current project is available or not if self.obj_validation.validateKicad(self.projDir): - #Checking if project has .cir file or not + # Checking if project has .cir file or not if self.obj_validation.validateCir(self.projDir): - #print "CIR file present" + # print "CIR file present" self.projName = os.path.basename(self.projDir) - self.project = os.path.join(self.projDir,self.projName) - - var1=self.project+".cir" - var2="sub" - self.obj_dockarea.kicadToNgspiceEditor(var1,var2) + self.project = os.path.join(self.projDir, self.projName) + + var1 = self.project + ".cir" + var2 = "sub" + self.obj_dockarea.kicadToNgspiceEditor(var1, var2) else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('The subcircuit does not contain any Kicad netlist file for conversion.') - self.msg.setWindowTitle("Error Message") + self.msg.showMessage( + 'The subcircuit does not contain any Kicad netlist\ + file for conversion.') + self.msg.setWindowTitle("Error Message") else: self.msg = QtGui.QErrorMessage(None) - self.msg.showMessage('Please select the subcircuit first. You can either create new subcircuit or open existing subcircuit') - self.msg.setWindowTitle("Error Message")
\ No newline at end of file + self.msg.showMessage( + 'Please select the subcircuit first. You can either create \ + new subcircuit or open existing subcircuit') + self.msg.setWindowTitle("Error Message") diff --git a/src/subcircuit/newSub.py b/src/subcircuit/newSub.py index 7ea247ab..c39f7c7a 100644 --- a/src/subcircuit/newSub.py +++ b/src/subcircuit/newSub.py @@ -1,65 +1,80 @@ -from PyQt4 import QtGui,QtCore +from PyQt4 import QtGui from projManagement.Validation import Validation from configuration.Appconfig import Appconfig from projManagement import Worker import os + class NewSub(QtGui.QWidget): """ This class is called when User create new Project. """ - + def __init__(self): super(NewSub, self).__init__() self.obj_validation = Validation() self.obj_appconfig = Appconfig() - - def createSubcircuit(self,subName): + def createSubcircuit(self, subName): """ This function create Subcircuit related directories and files """ self.create_schematic = subName - #Checking if Workspace already exist or not - self.schematic_path = (os.path.join(os.path.abspath('..'),'SubcircuitLibrary',self.create_schematic)) - - #Validation for new subcircuit + # Checking if Workspace already exist or not + self.schematic_path = ( + os.path.join( + os.path.abspath('..'), + 'SubcircuitLibrary', + self.create_schematic)) + + # Validation for new subcircuit if self.schematic_path == "": self.reply = "NONE" else: - self.reply = self.obj_validation.validateNewproj(str(self.schematic_path)) - - #Checking Validations Response + self.reply = self.obj_validation.validateNewproj( + str(self.schematic_path)) + + # Checking Validations Response if self.reply == "VALID": - print "Validated : Creating subcircuit directory" + print("Validated : Creating subcircuit directory") try: os.mkdir(self.schematic_path) - self.schematic = os.path.join(self.schematic_path,self.create_schematic) - self.cmd = "eeschema "+self.schematic+".sch" + self.schematic = os.path.join( + self.schematic_path, self.create_schematic) + self.cmd = "eeschema " + self.schematic + ".sch" self.obj_workThread = Worker.WorkerThread(self.cmd) self.obj_workThread.start() self.close() - except: - #print "Some Thing Went Wrong" + except BaseException: + # print "Some Thing Went Wrong" self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('Unable to create subcircuit. Please make sure you have write permission on '+self.schematic_path) + self.msg.showMessage( + 'Unable to create subcircuit. Please make sure\ + you have write permission on ' + + self.schematic_path) self.msg.setWindowTitle("Error Message") - - self.obj_appconfig.current_subcircuit['SubcircuitName'] = self.schematic_path - + + self.obj_appconfig.current_subcircuit['SubcircuitName'] \ + = self.schematic_path + elif self.reply == "CHECKEXIST": - #print "Project already exist" + # print "Project already exist" self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('The subcircuit "'+self.create_schematic+'" already exist.Please select the different name or delete existing subcircuit') + self.msg.showMessage( + 'The subcircuit "' + + self.create_schematic + + '" already exist.Please select the different name or delete' + + 'existing subcircuit') self.msg.setWindowTitle("Error Message") - + elif self.reply == "CHECKNAME": - #print "Name is not proper" + # print "Name is not proper" self.msg = QtGui.QErrorMessage(self) - self.msg.showMessage('The subcircuit name should not contain space between them') + self.msg.showMessage( + 'The subcircuit name should not contain space between them') self.msg.setWindowTitle("Error Message") - + elif self.reply == "NONE": self.msg = QtGui.QErrorMessage(self) self.msg.showMessage('The subcircuit name cannot be empty') - self.msg.setWindowTitle("Error Message")
\ No newline at end of file + self.msg.setWindowTitle("Error Message") diff --git a/src/subcircuit/openSub.py b/src/subcircuit/openSub.py index fb349f0a..ba6d0617 100644 --- a/src/subcircuit/openSub.py +++ b/src/subcircuit/openSub.py @@ -8,17 +8,22 @@ class openSub(QtGui.QWidget): """ This class is called when User click on Open Project Button """ + def __init__(self): super(openSub, self).__init__() self.obj_appconfig = Appconfig() - + def body(self): - self.editfile = str(QtGui.QFileDialog.getExistingDirectory(None,"Open File","../SubcircuitLibrary")) + self.editfile = str( + QtGui.QFileDialog.getExistingDirectory( + None, "Open File", "../SubcircuitLibrary")) if self.editfile: self.obj_Appconfig = Appconfig() - self.obj_Appconfig.current_subcircuit['SubcircuitName'] = self.editfile + self.obj_Appconfig.current_subcircuit['SubcircuitName'] = ( + self.editfile + ) self.schname = os.path.basename(self.editfile) - self.editfile = os.path.join(self.editfile,self.schname) - self.cmd = "eeschema "+self.editfile+".sch " + self.editfile = os.path.join(self.editfile, self.schname) + self.cmd = "eeschema " + self.editfile + ".sch " self.obj_workThread = WorkerThread(self.cmd) - self.obj_workThread.start()
\ No newline at end of file + self.obj_workThread.start() |