summaryrefslogtreecommitdiff
path: root/src/kicadtoNgspice/KicadtoNgspice.py
blob: f8faa997571487b048e20c429f6bf7cfec09842b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#===============================================================================
#
#          FILE: kicadtoNgspice.py
# 
#         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 
#      REVISION:  ---
#===============================================================================
import sys
import os
from PyQt4 import QtGui,QtCore
from Processing import PrcocessNetlist
import Analysis
import Source
import Model
import DeviceModel
import Convert
import TrackWidget



class MainWindow(QtGui.QWidget):
    """
    This class craete KicadtoNgspice window. 
    And Call Convert function if convert button is pressed. 
    """
    def __init__(self):
        QtGui.QWidget.__init__(self)
        #Create object of track widget
        self.obj_track = TrackWidget.TrackWidget()
              
        print "Init Kicad to Ngspice"             
        #print "Current Project",sys.argv[1]
        
            
        #Creating GUI for kicadtoNgspice window
        self.grid = QtGui.QGridLayout(self)
        self.convertbtn = QtGui.QPushButton("Convert")
        self.convertbtn.clicked.connect(self.callConvert)
        self.cancelbtn = QtGui.QPushButton("Cancel")
        self.cancelbtn.clicked.connect(self.close)
        self.grid.addWidget(self.createcreateConvertWidget(),0,0)
        self.grid.addWidget(self.convertbtn,1,1)
        self.grid.addWidget(self.cancelbtn,1,2)
        #self.setGeometry(800, 800, 1000, 1000)
        self.setWindowState(QtCore.Qt.WindowMaximized)
        self.setLayout(self.grid)
        self.show()
             
    
    def createcreateConvertWidget(self):
        
        self.convertWindow = QtGui.QWidget()
        self.analysisTab = QtGui.QScrollArea()
        self.analysisTab.setWidget(Analysis.Analysis())
        #self.analysisTabLayout = QtGui.QVBoxLayout(self.analysisTab.widget())
        self.analysisTab.setWidgetResizable(True)
        
        self.sourceTab = QtGui.QScrollArea()
        self.sourceTab.setWidget(Source.Source(sourcelist,sourcelisttrack))
        #self.sourceTabLayout = QtGui.QVBoxLayout(self.sourceTab.widget())
        self.sourceTab.setWidgetResizable(True)
        
        self.modelTab = QtGui.QScrollArea()
        self.modelTab.setWidget(Model.Model(schematicInfo,modelList))
        #self.modelTabLayout = QtGui.QVBoxLayout(self.modelTab.widget())
        self.modelTab.setWidgetResizable(True)
        
        self.deviceModelTab = QtGui.QScrollArea()
        self.deviceModelTab.setWidget(DeviceModel.DeviceModel(schematicInfo))
        self.deviceModelTab.setWidgetResizable(True)
        
        

        self.tabWidget = QtGui.QTabWidget()
        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.mainLayout = QtGui.QVBoxLayout()
        self.mainLayout.addWidget(self.tabWidget)
        #self.mainLayout.addStretch(1)
        self.convertWindow.setLayout(self.mainLayout)
        self.convertWindow.show()
    
        
        return self.convertWindow 
    
    def callConvert(self):
        """
        Calling Convert Class Constructor
        """
        global schematicInfo
        global analysisoutput
        self.obj_convert = Convert.Convert(self.obj_track.sourcelisttrack["ITEMS"],
                                           self.obj_track.source_entry_var["ITEMS"],
                                           schematicInfo)
        
        try:
            #Adding Source Value to Schematic Info
            schematicInfo = self.obj_convert.addSourceParameter()
            
            #Adding Model Value to schematicInfo
            schematicInfo = self.obj_convert.addModelParameter(schematicInfo)
            
            #Adding Device Library to SchematicInfo
            schematicInfo = self.obj_convert.addDeviceLibrary(schematicInfo,kicadFile)
            
            
            
            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"])
            #print "SchematicInfo after adding Model Details",schematicInfo
            
            #Calling netlist file generation function
            self.createNetlistFile(schematicInfo)
            
            self.msg = "The Kicad to Ngspice Conversion completed successfully!!!!!!"
            QtGui.QMessageBox.information(self, "Information", self.msg, QtGui.QMessageBox.Ok)
            self.close()         
        except Exception as e:
            print "Exception Message: ",e
            print "There was error while converting kicad to ngspice"
            self.close()
            
    
      
    
    def createNetlistFile(self,schematicInfo):
        print "Creating Final netlist"
        #print "INFOLINE",infoline
        #print "OPTIONINFO",optionInfo
        #print "Device MODEL LIST ",devicemodelList
        #print "SUBCKT ",subcktList
        #print "OUTPUTOPTION",outputOption
        #print "KicadfIle",kicadFile
        
        #checking if analysis files is present
        (projpath,filename) = os.path.split(kicadFile)
        analysisFileLoc = os.path.join(projpath,"analysis")
        #print "Analysis File Location",analysisFileLoc
        if os.path.exists(analysisFileLoc):
            try:
                f = open(analysisFileLoc)
                #Read data
                data = f.read()
                # Close the file
                f.close()

            except :
                print "Error While opening Project Analysis file. Please check it"
                sys.exit()
        else:
            print analysisFileLoc + " does not exist"
            sys.exit()
            
        #Adding analysis file info to optionInfo
        analysisData=data.splitlines()
        for eachline in analysisData:
            eachline=eachline.strip()
            if len(eachline)>1:
                if eachline[0]=='.':
                    optionInfo.append(eachline)
                else:
                    pass
                
        #print "Option Info",optionInfo
        analysisOption = []
        initialCondOption=[]
        simulatorOption =[]
        includeOption=[]  #Don't know why to use it
        model = []      #Don't know why to use it
        
        for eachline in 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'):
                includeOption.append(eachline+'\n')
            elif (option=='.model'):
                model.append(eachline+'\n')
            elif option=='.end':
                continue;
            
            
        #Start creating final netlist cir.out file
        outfile = kicadFile+".out"
        out=open(outfile,"w")
        out.writelines(infoline)
        out.writelines('\n')
        sections=[simulatorOption, initialCondOption, schematicInfo, analysisOption]
        print "SECTIONS",sections
        for section in sections:
            if len(section) == 0:
                continue
            else:
                for line in section:
                    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('print allv > plot_data_v.txt\n')
        out.writelines('print alli > plot_data_i.txt\n')
        out.writelines('.endc\n')
        out.writelines('.end\n')
        
        out.close()
        
   
        
                
            
    
        
def main(args):
    print "=================================="
    print "Kicad to Ngspice netlist converter "
    print "=================================="
    global kicadFile,kicadNetlist,schematicInfo
    global infoline,optionInfo
    #kicadFile = "/home/fahim/eSim-Workspace/BJT_amplifier/BJT_amplifier.cir"
    kicadFile = sys.argv[1]
    
    #Object of Processing
    obj_proc = PrcocessNetlist()
    
    # Read the netlist
    kicadNetlist = obj_proc.readNetlist(kicadFile)
    
    # Construct parameter information
    param = obj_proc.readParamInfo(kicadNetlist)
    
    # Replace parameter with values
    netlist,infoline = obj_proc.preprocessNetlist(kicadNetlist,param)
    
    print "NETLIST ",netlist
    print "INFOLINE",infoline
    
    # Separate option and schematic information
    optionInfo, schematicInfo = obj_proc.separateNetlistInfo(netlist)
    
    print "OPTIONINFO",optionInfo
    print "SCHEMATICINFO",schematicInfo
    
           
    #List for storing source and its value
    global sourcelist, sourcelisttrack
    sourcelist=[]
    sourcelisttrack=[]
    schematicInfo,sourcelist = obj_proc.insertSpecialSourceParam(schematicInfo,sourcelist)
    
    print "SOURCELIST",sourcelist
    print "SCHEMATICINFO",schematicInfo
    
    #List storing model detail
    global modelList,outputOption
    modelList = [] 
    outputOption = []
    schematicInfo,outputOption,modelList,unknownModelList,multipleModelList = obj_proc.convertICintoBasicBlocks(schematicInfo,outputOption,modelList)
    print "Unknown Model List",unknownModelList  
    print "Multiple Model List",multipleModelList
    print "Model List",modelList
    

    
    #Checking for unknown Model List and Multiple Model List
    if unknownModelList:
        print "ErrorMessage : These Models are not available.Please check it",unknownModelList
        sys.exit(2)
    else:
        if multipleModelList:
            print "ErrorMessage: There are multiple model of same name. Please check it",multipleModelList
            sys.exit(2)
        else:
            pass
        
    
    
    
    app = QtGui.QApplication(args)
    #app.setApplicationName("KicadToNgspice")
    #app.setQuitOnLastWindowClosed(True)
    kingWindow = MainWindow()
    kingWindow.show()
    sys.exit(app.exec_())
     
    

   
if __name__ == '__main__':
    main(sys.argv)