summaryrefslogtreecommitdiff
path: root/Connections/Shear/Finplate/finPlateMain.py
blob: a9398d8249a303eafcc1679d5fda001bb2d79277 (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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
'''
Created on 07-May-2015
comment

@author: deepa
'''
from PyQt4.QtCore import QString
from PyQt4.QtGui import QMessageBox
from OCC.TopoDS import topods, TopoDS_Shape
from OCC.BRepPrimAPI import BRepPrimAPI_MakeBox, BRepPrimAPI_MakeCylinder,\
    BRepPrimAPI_MakeSphere
from OCC.gp import gp_Pnt
'''
Created on 21-Aug-2014

@author: deepa
'''
import sys
from OCC import VERSION
#from PyQt4 import QtGui,QtCore
from ui_finPlate import Ui_MainWindow
from model import *
#from finPlateCalc import finConn
from finplate_calc1 import finConn
import yaml
import pickle
import logging 
#from exampleSimpleGUI import init_display
from OCC.BRepAlgoAPI import BRepAlgoAPI_Fuse
from OCC._Quantity import Quantity_NOC_RED,Quantity_NOC_BLUE1,Quantity_NOC_SADDLEBROWN
from ISection import ISection
import numpy
from OCC.Graphic3d import Graphic3d_NOT_2D_ALUMINUM
from weld import  Weld
from plate import Plate
from bolt import Bolt
from nut import Nut 
import os.path
from utilities import osdagDisplayShape
from OCC.Display.pyqt4Display import qtViewer3d
from colWebBeamWebConnectivity import ColWebBeamWeb
from colFlangeBeamWebConnectivity import ColFlangeBeamWeb
from OCC import IGESControl
from filletweld import FilletWeld


class MainController(QtGui.QMainWindow):
    
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.inputDock.setFixedSize(310,710)
        
        self.gradeType ={'Please Select Type':'',
                         'HSFG': [8.8,10.8],
                         'Black Bolt':[3.6,4.6,4.8,5.6,5.8,6.8,9.8,12.9]}
        self.ui.comboType.addItems(self.gradeType.keys())
        self.ui.comboType.currentIndexChanged[str].connect(self.combotype_currentindexchanged)
        self.ui.comboType.setCurrentIndex(0)
        
        self.ui.comboConnLoc.currentIndexChanged[str].connect(self.setimage_connection)
        
        self.ui.btn_Reset.clicked.connect(self.resetbtn_clicked)
        
        self.ui.btn_Design.clicked.connect(self.design_btnclicked)
        
        self.ui.btnInput.clicked.connect(lambda: self.dockbtn_clicked(self.ui.inputDock))
        self.ui.btnOutput.clicked.connect(lambda: self.dockbtn_clicked(self.ui.outputDock))
        self.ui.btn_front.clicked.connect(self.call_Frontview)
        self.ui.btn_top.clicked.connect(self.call_Topview)
        self.ui.btn_side.clicked.connect(self.call_Sideview)
        
        self.ui.btn3D.clicked.connect(self.call_3DModel)
        self.ui.chkBxBeam.clicked.connect(self.call_3DBeam)
        self.ui.chkBxCol.clicked.connect(self.call_3DColumn)
        self.ui.chkBxFinplate.clicked.connect(self.call_3DFinplate)
        
        validator = QtGui.QIntValidator()
        self.ui.txtFu.setValidator(validator)
        self.ui.txtFy.setValidator(validator)
        
        dbl_validator = QtGui.QDoubleValidator()
        self.ui.txtPlateLen.setValidator(dbl_validator)
        self.ui.txtPlateLen.setMaxLength(7)
        self.ui.txtPlateWidth.setValidator(dbl_validator)
        self.ui.txtPlateWidth.setMaxLength(7)
        self.ui.txtShear.setValidator(dbl_validator)
        self.ui.txtShear.setMaxLength(7)
        
        minfuVal = 290
        maxfuVal = 590
        self.ui.txtFu.editingFinished.connect(lambda: self.check_range(self.ui.txtFu,self.ui.lbl_fu, minfuVal, maxfuVal))
        
        minfyVal = 165
        maxfyVal = 450
        self.ui.txtFy.editingFinished.connect(lambda: self.check_range(self.ui.txtFy,self.ui.lbl_fy, minfyVal, maxfyVal))
       
        self.ui.combo_Beam.addItems(get_beamcombolist())
        self.ui.comboColSec.addItems(get_columncombolist())
        
        self.ui.menuView.addAction(self.ui.inputDock.toggleViewAction())
        self.ui.menuView.addAction(self.ui.outputDock.toggleViewAction())
        self.ui.btn_CreateDesign.clicked.connect(self.save_design)
        #self.ui.btn_Saveoutput.clicked.connect(self.save_design)
        self.ui.btn_SaveMessages.clicked.connect(self.save_log)
        #self.ui.btn_Savelog.clicked.connect(self.save_log)
        
        

        # Saving and Restoring the finPlate window state.
        self.retrieve_prevstate()
        
        
        # Initialising the qtviewer
        self.display,_ = self.init_display(backend_str="pyqt4")
        #self.display2d,_,_ = self.init_display(backend_str="pyqt4")
        
        self.ui.btnSvgSave.clicked.connect(self.save3DtoIGES)
        #self.ui.btnSvgSave.clicked.connect(lambda:self.saveTopng(self.display))
        
        self.colWebBeamWeb =  self.create3DColWebBeamWeb()
        # my_box = BRepPrimAPI_MakeBox(gp_Pnt(20,0,0),10., 20., 30.).Shape()
        # my_cylendar = BRepPrimAPI_MakeCylinder(10,30).Shape()
        # self.memberlist =  [my_box, my_cylendar, my_cylendar]
        
        #my_sphere = BRepPrimAPI_MakeSphere(5).Shape()
        self.fuse_model = self.create2Dcad()
        #self.fuse_model = my_sphere 
        self.validatePlateThickCombo()
        #self.closeEvent()



    
    def validatePlateThickCombo(self):

        beam_sec = self.ui.combo_Beam.currentText()
        dictbeamdata  = get_beamdata(beam_sec)
        beam_tw = float(dictbeamdata[QString("tw")])
        plateThickness = ['select Thickness',6,8,10,12,14,16,18,20]
        newlist = ['Select Thickness']
        #comboPlateThickItenewlist = []
        for item in plateThickness[1:]:
            if item >= beam_tw:
                newlist.append(str(item))
        print newlist
        
        for i in newlist[:]:
            self.ui.comboPlateThick_2.addItem(str(i))
        #self.ui.comboPlateThick_2.setCurrentIndex(0)
           
        
        
    def saveTopng(self,display):
        display.ExportToImage('/home/Pictures/cad.png')
    
    def retrieve_prevstate(self):
        uiObj = self.get_prevstate()
        if(uiObj != None):
            
            self.ui.combo_Beam.setCurrentIndex(self.ui.combo_Beam.findText(uiObj['Member']['beamSection']))
            self.ui.comboColSec.setCurrentIndex(self.ui.comboColSec.findText(uiObj['Member']['columSection']))
            
            self.ui.txtFu.setText(str(uiObj['Member']['fu(MPa)']))
            self.ui.txtFy.setText(str(uiObj['Member']['fy(MPa)']))
           
            self.ui.comboConnLoc.setCurrentIndex(self.ui.comboConnLoc.findText(str(uiObj['Member']['connectivity'])))
            
            self.ui.txtShear.setText(str(uiObj['Load']['shearForce(kN)']))
            
            self.ui.comboDaimeter.setCurrentIndex(self.ui.comboDaimeter.findText(str(uiObj['Bolt']['diameter(mm)'])))
            comboTypeIndex = self.ui.comboType.findText(str(uiObj['Bolt']['type']))
            self.ui.comboType.setCurrentIndex(comboTypeIndex)
            self.combotype_currentindexchanged(str(uiObj['Bolt']['type']))
            
            prevValue = str(uiObj['Bolt']['grade'])
        
            comboGradeIndex = self.ui.comboGrade.findText(prevValue)
          
            self.ui.comboGrade.setCurrentIndex(comboGradeIndex)
        
            #self.ui.comboDaimeter.currentText(str(uiObj['Bolt']['diameter(mm)']))
            #self.ui.comboType.currentText(str(uiObj['Bolt']['diameter(mm)']))
            #self.ui.comboGrade.currentText(str(uiObj['Bolt']['grade']))
            selection = str(uiObj['Plate']['thickness(mm)'])
            selectionIndex = self.ui.comboPlateThick_2.findText(selection)
            self.ui.comboPlateThick_2.setCurrentIndex(selectionIndex)
            #self.ui.comboPlateThick_2.currentText(str(uiObj['Plate']['thickness(mm)']))
            self.ui.txtPlateLen.setText(str(uiObj['Plate']['height(mm)']))
            self.ui.txtPlateWidth.setText(str(uiObj['Plate']['width(mm)']))
            
            self.ui.comboWldSize.setCurrentIndex(self.ui.comboWldSize.findText(str(uiObj['Weld']['size(mm)'])))
            #self.ui.comboWldSize.currentText(str(uiObj['Weld']['size(mm)']))
        #else:
        #    self.btnreset_clicked() 
        
    def setimage_connection(self):
        '''
        Setting image to connctivity.
        '''
        self.ui.lbl_connectivity.show()
        loc = self.ui.comboConnLoc.currentText()
        if loc == "Column flange-Beam web":
            
            pixmap = QtGui.QPixmap(":/newPrefix/images/beam2.jpg")
            pixmap.scaledToHeight(50)
            pixmap.scaledToWidth(60)
            self.ui.lbl_connectivity.setPixmap(pixmap)
            #self.ui.lbl_connectivity.show()
        elif(loc == "Column web-Beam web"):
            picmap = QtGui.QPixmap(":/newPrefix/images/beam.jpg")
            picmap.scaledToHeight(50)
            picmap.scaledToWidth(60)
            self.ui.lbl_connectivity.setPixmap(picmap)
        else:
            self.ui.lbl_connectivity.hide()
            
        
    def getuser_inputs(self):
        '''(nothing) -> Dictionary
        
        Returns the dictionary object with the user input fields for designing fin plate connection
        
        '''
        uiObj = {}
        uiObj["Bolt"] = {}
        uiObj["Bolt"]["diameter(mm)"] = self.ui.comboDaimeter.currentText().toInt()[0]
        uiObj["Bolt"]["grade"] = float(self.ui.comboGrade.currentText())                                                                                                                                                                                                                                                              
        uiObj["Bolt"]["type"] = str(self.ui.comboType.currentText())
        
            
        uiObj["Weld"] = {}
        uiObj["Weld"]['size(mm)'] = self.ui.comboWldSize.currentText().toInt()[0]
        
        uiObj['Member'] = {}
        uiObj['Member']['beamSection'] = str(self.ui.combo_Beam.currentText())
        uiObj['Member']['columSection'] = str(self.ui.comboColSec.currentText())
        uiObj['Member']['connectivity'] = str(self.ui.comboConnLoc.currentText())
        uiObj['Member']['fu(MPa)'] = self.ui.txtFu.text().toInt()[0]
        uiObj['Member']['fy(MPa)'] = self.ui.txtFy.text().toInt()[0]
        
        uiObj['Plate'] = {}
        uiObj['Plate']['thickness(mm)'] = self.ui.comboPlateThick_2.currentText().toInt()[0]
        uiObj['Plate']['height(mm)'] = self.ui.txtPlateLen.text().toInt()[0] # changes the label length to height 
        uiObj['Plate']['width(mm)'] = self.ui.txtPlateWidth.text().toInt()[0]
        
        uiObj['Load'] = {}
        uiObj['Load']['shearForce(kN)'] = self.ui.txtShear.text().toInt()[0]
        
        
        return uiObj    
    
    def save_inputs(self,uiObj):
         
        '''(Dictionary)--> None
         
        '''
        return
        inputFile = QtCore.QFile('saveINPUT.txt')
        if not inputFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, "Application",
                    "Cannot write file %s:\n%s." % (inputFile, file.errorString()))
        #yaml.dump(uiObj, inputFile,allow_unicode=True, default_flow_style = False)
        pickle.dump(uiObj, inputFile)
        
    
    def get_prevstate(self):
        '''
        '''
        fileName = 'saveINPUT.txt'
         
        if os.path.isfile(fileName):
            fileObject = open(fileName,'r')
            uiObj = pickle.load(fileObject)
            return uiObj
        else:
            return None
    
            
    def outputdict(self):
        
        ''' Returns the output of design in dictionary object.
        '''
        outObj = {}
        outObj['Plate'] ={}
        #outObj['Plate']["Thickness(mm)"] = float(self.ui.txtPlateThick.text())
        outObj['Plate']["External Moment(kNm)"] = float(self.ui.txtExtMomnt.text())
        outObj['Plate']["Moment Capacity(kNm)"] = float(self.ui.txtMomntCapacity.text())
        
        outObj['Weld'] ={}
        #outObj['Weld']["Weld Thickness(mm)"] = float(self.ui.txtWeldThick.text())
        outObj['Weld']["Resultant Shear(kN/mm)"] = float(self.ui.txtResltShr.text())
        outObj['Weld']["Weld Strength(kN/mm)"] = float(self.ui.txtWeldStrng.text())
        
        outObj['Bolt'] = {}
        outObj['Bolt']["Shear Capacity(kN)"] = float(self.ui.txtShrCapacity.text())
        outObj['Bolt']["Bearing Capacity(kN)"] = float(self.ui.txtbearCapacity.text())
        outObj['Bolt']["Capacity Of Bolt(kN)"] = float(self.ui.txtBoltCapacity.text())
        outObj['Bolt']["No Of Bolts"] = float(self.ui.txtNoBolts.text())
        outObj['Bolt']["No.Of Row"] = int(self.ui.txt_row.text())
        outObj['Bolt']["No.Of Column"] = int(self.ui.txt_col.text())
        outObj['Bolt']["Pitch Distance(mm)"] = float(self.ui.txtPitch.text())
        outObj['Bolt']["Guage Distance(mm)"] = float(self.ui.txtGuage.text())
        outObj['Bolt']["End Distance(mm)"]= float(self.ui.txtEndDist.text())
        outObj['Bolt']["Edge Distance(mm)"]= float(self.ui.txtEdgeDist.text())
        
        return outObj
    
    
    def save_design(self):
        self.outdict = self.outputdict()
        self.inputdict = self.getuser_inputs()
        self.save_yaml(self.outdict,self.inputdict)
    
        #self.save(self.outdict,self.inputdict)
        
    def save_log(self):
        
        fileName,pat =QtGui.QFileDialog.getSaveFileNameAndFilter(self,"Save File As","/home/deepa/SaveMessages","Text files (*.txt)")
        return self.save_file(fileName+".txt")
          
    def save_file(self, fileName):
        '''(file open for writing)-> boolean
        '''
        fname = QtCore.QFile(fileName)
        if not fname.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, "Application",
                    "Cannot write file %s:\n%s." % (fileName, fname.errorString()))
            return False

        outf = QtCore.QTextStream(fname)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
        outf << self.ui.textEdit.toPlainText()
        QtGui.QApplication.restoreOverrideCursor()

        #self.setCurrentFile(fileName);
        QtGui.QMessageBox.about(self,'Information',"File saved")
        return True
    
    
    def save_yaml(self,outObj,uiObj):
        '''(dictiionary,dictionary) -> NoneType
        Saving input and output to file in following format.
        Bolt:
          diameter: 6
          grade: 8.800000190734863
          type: HSFG
        Load:
          shearForce: 100
          
        '''
        newDict = {"INPUT": uiObj, "OUTPUT": outObj} 
        fileName = QtGui.QFileDialog.getSaveFileName(self,"Save File As","/home/deepa/SaveDesign","Text File (*.txt)")
        f = open(fileName,'w')
        yaml.dump(newDict,f,allow_unicode=True, default_flow_style=False)
        return self.save_file(fileName+".txt")

        
    def resetbtn_clicked(self):
        '''(NoneType) -> NoneType
        
        Resets all fields in input as well as output window
    
        '''
        # user Inputs
        self.ui.combo_Beam.setCurrentIndex((0))
        self.ui.comboColSec.setCurrentIndex((0))
        self.ui.comboConnLoc.setCurrentIndex((0))
        self.ui.txtFu.clear()
        self.ui.txtFy.clear()
        
        self.ui.txtShear.clear()
        
        self.ui.comboDaimeter.setCurrentIndex(0)
        self.ui.comboType.setCurrentIndex((0))
        self.ui.comboGrade.setCurrentIndex((0))
        
        self.ui.comboPlateThick_2.setCurrentIndex((0))
        self.ui.txtPlateLen.clear()
        self.ui.txtPlateWidth.clear()
        
        self.ui.comboWldSize.setCurrentIndex((0))
        
        #----Output
        self.ui.txtShrCapacity.clear()
        self.ui.txtbearCapacity.clear()
        self.ui.txtBoltCapacity.clear()
        self.ui.txtNoBolts.clear()
        self.ui.txtboltgrpcapacity.clear()
        self.ui.txt_row.clear()
        self.ui.txt_col.clear()
        self.ui.txtPitch.clear()
        self.ui.txtGuage.clear()
        self.ui.txtEndDist.clear()
        self.ui.txtEdgeDist.clear()
        
        #self.ui.txtPlateThick.clear()
        self.ui.txtplate_ht.clear()
        self.ui.txtplate_width.clear()
        self.ui.txtExtMomnt.clear()
        self.ui.txtMomntCapacity.clear()
        
        #self.ui.txtWeldThick.clear()
        self.ui.txtResltShr.clear()
        self.ui.txtWeldStrng.clear()
        self.ui.textEdit.clear()
        
    def dockbtn_clicked(self,widget):
        
        '''(QWidget) -> NoneType
        
        This method dock and undock widget(QdockWidget)
        '''
        
        flag = widget.isHidden()
        if(flag):
            
            widget.show()
        else:
            widget.hide()
            
    def  combotype_currentindexchanged(self,index):
        
        '''(Number) -> NoneType
        '''
        items = self.gradeType[str(index)]

        self.ui.comboGrade.clear()
        strItems = []
        for val in items:
            strItems.append(str(val))
            
        self.ui.comboGrade.addItems(strItems)
        
        
    def check_range(self, widget,lblwidget, minVal, maxVal):
        
        '''(QlineEdit,QLable,Number,Number)---> NoneType
        Validating F_u(ultimate Strength) and F_y (Yeild Strength) textfields
        '''
        textStr = widget.text()
        val = int(textStr) 
        if( val < minVal or val > maxVal):
            QtGui.QMessageBox.about(self,'Error','Please Enter a value between %s-%s' %(minVal, maxVal))
            widget.clear()
            widget.setFocus()
            palette = QtGui.QPalette()
            palette.setColor(QtGui.QPalette.Foreground,QtCore.Qt.red)
            lblwidget.setPalette(palette)
        else:
            palette = QtGui.QPalette()
            lblwidget.setPalette(palette)
            
    def display_output(self, resultObj):
        
        '''(dictionary) --> NoneType
        
        Setting design result values to the respective textboxes in the output window
        
        '''
        # resultObj['Bolt']
        shear_capacity = resultObj['Bolt']['shearcapacity']
        self.ui.txtShrCapacity.setText(str(shear_capacity))
        
        bearing_capacity = resultObj['Bolt']['bearingcapacity']
        self.ui.txtbearCapacity.setText(str(bearing_capacity))
        
        bolt_capacity = resultObj['Bolt']['boltcapacity']
        self.ui.txtBoltCapacity.setText(str(bolt_capacity))
        
        no_ofbolts = resultObj['Bolt']['numofbolts']
        self.ui.txtNoBolts.setText(str(no_ofbolts))
        #newly added field
        boltGrp_capacity = resultObj['Bolt']['boltgrpcapacity']
        self.ui.txtboltgrpcapacity.setText(str(boltGrp_capacity))
        
        no_ofrows = resultObj['Bolt']['numofrow']
        self.ui.txt_row.setText(str(no_ofrows))
        
        no_ofcol = resultObj['Bolt']['numofcol']
        self.ui.txt_col.setText(str(no_ofcol))
        
        pitch_dist = resultObj['Bolt']['pitch']
        self.ui.txtPitch.setText(str(pitch_dist))
        
        gauge_dist = resultObj['Bolt']['gauge']
        self.ui.txtGuage.setText(str(gauge_dist))
        
        end_dist = resultObj['Bolt']['enddist']
        self.ui.txtEndDist.setText(str(end_dist))
        
        edge_dist = resultObj['Bolt']['edge']
        self.ui.txtEdgeDist.setText(str(edge_dist))
        
        
        # weld_thickness = resultObj['Weld']['thickness']
        # self.ui.txtWeldThick.setText(str(weld_thickness))
        
        resultant_shear = resultObj['Weld']['resultantshear']
        self.ui.txtResltShr.setText(str(resultant_shear))
        
        weld_strength = resultObj['Weld']['weldstrength']
        self.ui.txtWeldStrng.setText(str(weld_strength))
         
        
        # Newly included fields
        plate_ht = resultObj['Plate']['height'] 
        self.ui.txtplate_ht.setText(str(plate_ht))
        
        plate_width = resultObj['Plate']['width'] 
        self.ui.txtplate_width.setText(str(plate_width))
        
        moment_demand = resultObj['Plate']['externalmoment']
        self.ui.txtExtMomnt.setText(str(moment_demand))
        
        moment_capacity =  resultObj['Plate']['momentcapacity']
        self.ui.txtMomntCapacity.setText(str(moment_capacity))
        
   
    def displaylog_totextedit(self):
        '''
        This method displaying Design messages(log messages)to textedit widget.
        '''
        
        afile = QtCore.QFile('fin.log')
        
        if not afile.open(QtCore.QIODevice.ReadOnly):#ReadOnly
            QtGui.QMessageBox.information(None, 'info', afile.errorString())
        
        stream = QtCore.QTextStream(afile)
        #self.ui.textEdit.setFocus()
        self.ui.textEdit.clear()
        self.ui.textEdit.setHtml(stream.readAll())
        
        afile.close()
        
        
    def get_backend(self):
        """
        loads a backend
        backends are loaded in order of preference
        since python comes with Tk included, but that PySide or PyQt4
        is much preferred
        """
        try:
            from PySide import QtCore, QtGui
            return 'pyside'
        except:
            pass
        try:
            from PyQt4 import QtCore, QtGui
            return 'pyqt4'
        except:
            pass
        # Check wxPython
        try:
            import wx
            return 'wx'
        except:
            raise ImportError("No compliant GUI library found. You must have either PySide, PyQt4 or wxPython installed.")
            sys.exit(1)
        
    # QtViewer
    def init_display(self,backend_str=None, size=(1024, 768)):
        
        global display,start_display, app, _, USED_BACKEND
    
        if not backend_str:
            USED_BACKEND = self.get_backend()
        elif backend_str in [ 'pyside', 'pyqt4']:
            USED_BACKEND = backend_str
        else:
            raise ValueError("You should pass either 'qt' or 'tkinter' to the init_display function.")
            sys.exit(1)
    
        # Qt based simple GUI
        if USED_BACKEND in ['pyqt4', 'pyside']:
            if USED_BACKEND == 'pyqt4':
                from PyQt4 import QtCore, QtGui, QtOpenGL
                from OCC.Display.pyqt4Display import qtViewer3d
            elif USED_BACKEND == 'pyside':
                from PySide import QtCore, QtGui, QtOpenGL
                from OCC.Display.pysideDisplay import qtViewer3d
    
        self.ui.modelTab = qtViewer3d(self)
        #self.ui.model2dTab = qtViewer3d(self)
        
        self.setWindowTitle("Osdag-%s 3d viewer ('%s' backend)" % (VERSION, USED_BACKEND))
        self.ui.mytabWidget.resize(size[0], size[1])
        self.ui.mytabWidget.addTab(self.ui.modelTab,"")
        #self.ui.mytabWidget.addTab(self.ui.model2dTab,"")
        
        self.ui.modelTab.InitDriver()
        display = self.ui.modelTab._display
        #display_2d = self.ui.model2dTab._display
        
        # background gradient
        display.set_bg_gradient_color(23,1,32,23,1,32)
        #display_2d.set_bg_gradient_color(255,255,255,255,255,255)
        # display black trihedron
        display.display_trihedron()
        display.View.SetProj(1, 1, 1)
        def centerOnScreen(self):
                    '''Centers the window on the screen.'''
                    resolution = QtGui.QDesktopWidget().screenGeometry()
                    self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
                              (resolution.height() / 2) - (self.frameSize().height() / 2))
        def start_display():
            
            self.ui.modelTab.raise_()
            #self.ui.model2dTab.raise_()   # make the application float to the top
          
        return display, start_display
        
    def display3Dmodel(self,cadlist,component):
        self.display.EraseAll()
        self.display.SetModeShaded()
        #self.display,_ = self.init_display(backend_str="pyqt4")
        self.display.set_bg_gradient_color(23,1,32,23,1,32)
        
        if component == "Column":
            
            osdagDisplayShape(self.display, cadlist[0], update=True)
        elif component == "Beam":
            self.display.EraseAll()
            osdagDisplayShape(self.display, cadlist[1],material = Graphic3d_NOT_2D_ALUMINUM, update=True)
        elif component == "Finplate" :
            display.EraseAll()
            osdagDisplayShape(self.display,cadlist[2],color = 'red', update = True)
            osdagDisplayShape(self.display, cadlist[3], color = 'red', update = True)
            osdagDisplayShape(self.display, cadlist[4], color = 'blue', update = True)
            self.display.DisplayShape(cadlist[5:8],color = Quantity_NOC_SADDLEBROWN, update=True)
            self.display.DisplayShape(cadlist[8:11],color = Quantity_NOC_SADDLEBROWN, update = True)
        elif  component == "Model":
            self.display.EraseAll()
            osdagDisplayShape(self.display, cadlist[0], update=True)
            osdagDisplayShape(self.display, cadlist[1],material = Graphic3d_NOT_2D_ALUMINUM, update=True)
            osdagDisplayShape(self.display,cadlist[2],color = 'red', update = True)
            osdagDisplayShape(self.display,cadlist[3],color = 'red', update = True)
            osdagDisplayShape(self.display, cadlist[4], color = 'blue', update = True)
            self.display.DisplayShape(cadlist[5:8],color = Quantity_NOC_SADDLEBROWN, update=True)
            self.display.DisplayShape(cadlist[8:11],color = Quantity_NOC_SADDLEBROWN, update = True)
            
        else:
            pass
             
        start_display()
        
    
    def create3DColWebBeamWeb(self):
        '''
        creating 3d cad model with column web beam web
        '''
        
        column = ISection(B = 83, T = 14.1, D = 250, t = 11, R1 = 12, R2 = 3.2, alpha = 98, length = 1000)
        beam = ISection(B = 140, T = 16,D = 400,t = 8.9, R1 = 14, R2 = 7, alpha = 98,length = 500)
        Fweld1 = FilletWeld(L= 300,b = 6, h = 6)
        #Fweld1 = Weld(L= 300,W = beam.t, T = 8)
        
        plate = Plate(L= 300,W =100, T = 10)
        boltRadius = 10
        nutRadius = 10
        
        boltPlaceObj = finConn(self.getuser_inputs())
        colwebconn =  ColWebBeamWeb(column,beam,Fweld1,plate,boltRadius,nutRadius,boltPlaceObj)
        colwebconn.create_3dmodel()
        return  colwebconn
        
    def createColFlangeBeamWeb(self):
        '''
        Creating 3d cad model with column flange beam web connection
        '''
        column = ISection(B = 83, T = 14.1, D = 250, t = 11, R1 = 12, R2 = 3.2, alpha = 98, length = 1000)
        beam = ISection(B = 140, T = 16,D = 400,t = 8.9, R1 = 14, R2 = 7, alpha = 98,length = 500)
        weld = Weld(L= 300,b = 6.0, T = 8)
        plate = Plate(L= weld.L,W =100, T = 10)
        boltRadius = 10
        nutRadius = 10
        
        colflangeconn =  ColFlangeBeamWeb(column,beam,weld,plate,boltRadius,nutRadius)
        return colflangeconn.create_3dmodel()
     
    def call_3DModel(self):
        
        if self.ui.btn3D.isEnabled():
            self.ui.chkBxBeam.setChecked(QtCore.Qt.Unchecked)
            self.ui.chkBxCol.setChecked(QtCore.Qt.Unchecked)
            self.ui.chkBxFinplate.setChecked(QtCore.Qt.Unchecked)
            self.ui.mytabWidget.setCurrentIndex(0)
            
        if self.ui.comboConnLoc.currentText()== "Column web-Beam web":
            connectivity =  self.colWebBeamWeb
        else:
            self.ui.mytabWidget.setCurrentIndex(0)
            connectivity =  self.createColFlangeBeamWeb()
            
        self.display3Dmodel(connectivity.get_models(), "Model")
        
    
    def call_3DBeam(self):
        '''
        Creating and displaying 3D Beam
        '''
        if self.ui.chkBxBeam.isChecked():
            self.ui.chkBxCol.setChecked(QtCore.Qt.Unchecked)
            self.ui.chkBxFinplate.setChecked(QtCore.Qt.Unchecked)
            self.ui.mytabWidget.setCurrentIndex(0)
        
        self.display3Dmodel(self.memberlist, "Beam")
            
    def call_3DColumn(self):
        '''
        '''
        if self.ui.chkBxCol.isChecked():
            self.ui.chkBxBeam.setChecked(QtCore.Qt.Unchecked)
            self.ui.chkBxFinplate.setChecked(QtCore.Qt.Unchecked)
            self.ui.mytabWidget.setCurrentIndex(0)
        self.display3Dmodel(self.memberlist, "Column")
            
            
    def call_3DFinplate(self):
        '''Displaying FinPlate in 3D
        '''
        if self.ui.chkBxFinplate.isChecked():
            self.ui.chkBxBeam.setChecked(QtCore.Qt.Unchecked)
            self.ui.chkBxCol.setChecked(QtCore.Qt.Unchecked)
            self.ui.mytabWidget.setCurrentIndex(0)
            
        self.display3Dmodel(self.memberlist, "Finplate")
           
    
        
        
    def design_btnclicked(self):
        '''
        '''
        designLogger =  logging.getLogger("Designlogger.finPlateCalc")
        
        self.ui.outputDock.setFixedSize(310,710)
        #self.set_designlogger()
        # Getting User Inputs.
        uiObj = self.getuser_inputs()
        print uiObj
        
        # FinPlate Design Calculations. 
        resultObj = finConn(uiObj)
        
        # Displaying Design Calculations To Output Window
        self.display_output(resultObj)
        
        # Displaying Messages related to FinPlate Design.
        self.displaylog_totextedit()
        
        
    

    def create2Dcad(self):
        cadlist =  self.colWebBeamWeb.get_models()

        final_model = cadlist[0]
        for model in cadlist[1:]:
            final_model = BRepAlgoAPI_Fuse(model,final_model).Shape()
        return final_model           
         
    
    # Export to IGES
    def save3DtoIGES(self):
        
        shape = self.create2Dcad()
        i  = IGESControl.IGESControl_Controller()
        i.Init()
        iges_writer = IGESControl.IGESControl_Writer()
        iges_writer.AddShape(shape)
        iges_writer.Write('/home/deepa/Pictures/osdag.iges')
    
    def display2DModelOriginal(self, final_model, viewName):
        
        self.display,_ = self.init_display()
        self.display.ResetView()
        self.display.EraseAll()      
        #self.display.SetModeWireFrame()
        
        self.display.DisplayShape(final_model, update = True)
        self.display.SetModeHLR()
        
        
        
        if (viewName == "Front"):
            self.display.View_Front()
        elif (viewName == "Top"):
            self.display.View_Top()
        elif (viewName == "Right"):
            self.display.View_Right()
        else:
            pass

    def display2DModel(self, final_model, viewName):
        
        #display, start_display, _, _ = self.simpleGUI()
        #self.display2d,_,_ = self.init_display(backend_str="pyqt4")
        #self.display.EraseAll()      

        self.display.set_bg_gradient_color(255, 255, 255, 255, 255, 255)
        
        self.display.SetModeHLR()
        #self.display.SetModeShaded()
        # Get Context
        ais_context = self.display.GetContext().GetObject()

        # Get Prs3d_drawer from previous context
        drawer_handle = ais_context.DefaultDrawer()
        drawer = drawer_handle.GetObject()
        drawer.EnableDrawHiddenLine()
        
        hla = drawer.HiddenLineAspect().GetObject()
        hla.SetWidth(2)
        hla.SetColor(Quantity_NOC_RED)
        
        # increase line width in the current viewer
        # This is only viewed in the HLR mode (hit 'e' key for instance)
        
        line_aspect = drawer.SeenLineAspect().GetObject()
        line_aspect.SetWidth(2.8)
        line_aspect.SetColor(Quantity_NOC_BLUE1)
        
        self.display.DisplayShape(final_model, update = False)
        
        if (viewName == "Front"):
            #self.display.SetModeHLR()
            self.display.View_Front()
        elif (viewName == "Top"):
            #self.display.SetModeHLR()
            self.display.View_Top()
        elif (viewName == "Right"):
            #self.display.SetModeHLR()
            self.display.View_Right()
        else:
            pass
            
        #start_display()

    def call_Frontview(self):
        
        '''Displays front view of 2Dmodel
        '''
        self.ui.chkBxBeam.setChecked(QtCore.Qt.Unchecked)
        self.ui.chkBxCol.setChecked(QtCore.Qt.Unchecked)
        self.ui.chkBxFinplate.setChecked(QtCore.Qt.Unchecked)
            
        self.display.EraseAll()
        self.ui.mytabWidget.setCurrentIndex(1)
        
        self.display2DModel(self.fuse_model, "Front")
    
    def call_Topview(self):
        
        '''Displays Top view of 2Dmodel
        '''
        self.ui.chkBxBeam.setChecked(QtCore.Qt.Unchecked)
        self.ui.chkBxCol.setChecked(QtCore.Qt.Unchecked)
        self.ui.chkBxFinplate.setChecked(QtCore.Qt.Unchecked)
            
        self.display.EraseAll()
        self.ui.mytabWidget.setCurrentIndex(1)
        
        self.display2DModel(self.fuse_model, "Top")
        
    def call_Sideview(self):
        
        '''Displays Side view of the 2Dmodel'
        '''
        self.ui.chkBxBeam.setChecked(QtCore.Qt.Unchecked)
        self.ui.chkBxCol.setChecked(QtCore.Qt.Unchecked)
        self.ui.chkBxFinplate.setChecked(QtCore.Qt.Unchecked)
        
        self.ui.mytabWidget.setCurrentIndex(1)
        self.display2DModel(self.fuse_model, "Right")
        
    def closeEvent(self, event):
        '''
        Closing finPlate window.
        '''
        uiInput = self.getuser_inputs()
        self.save_inputs(uiInput)
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore() 

                        
def set_osdaglogger():
    
    logger = logging.getLogger("osdag")
    logger.setLevel(logging.DEBUG)
 
    # create the logging file handler
    fh = logging.FileHandler("fin.log", mode="a")
    
    #,datefmt='%a, %d %b %Y %H:%M:%S'
    #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    formatter = logging.Formatter('''
    <div  class="LOG %(levelname)s">
        <span class="DATE">%(asctime)s</span>
        <span class="LEVEL">%(levelname)s</span>
        <span class="MSG">%(message)s</span>
    </div>''')
    formatter.datefmt = '%a, %d %b %Y %H:%M:%S'
    fh.setFormatter(formatter)
 
    # add handler to logger object
    logger.addHandler(fh)
    
    
    

if __name__ == '__main__':
    
    # linking css to log file to display colour logs.
    set_osdaglogger()
    rawLogger = logging.getLogger("raw")
    rawLogger.setLevel(logging.INFO)
    fh = logging.FileHandler("fin.log", mode="w")
    formatter = logging.Formatter('''%(message)s''')
    fh.setFormatter(formatter)
    rawLogger.addHandler(fh)
    rawLogger.info('''<link rel="stylesheet" type="text/css" href="log.css"/>''')
    
    
    app = QtGui.QApplication(sys.argv)
    window = MainController()
    window.show()
    sys.exit(app.exec_())