-
Notifications
You must be signed in to change notification settings - Fork 0
/
LewisStructureGen.py
1590 lines (1468 loc) · 72.7 KB
/
LewisStructureGen.py
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#File that handles all the lewis structure drawings and most of the user interface
import Geoms
from tkinter import *
import math
from mendeleev import element
import copy
import re
import pickle
import os
import os.path
from tkinter import filedialog
from targetOutputBaseNew import runGetAnglesAndBondsBase
import numpy as np
from PIL import Image, ImageTk
####################################
#Classes and Methods
####################################
#Classes for atom and bonds + subclasses of bonds
class Atom:
#Model
#An atom has the atomic symbol, its number, its center, and its radius + text scale factor
def __init__(self, atom, cX, cY, radius, ID, color = 'black'):
#Drawing data
self.atom = atom
self.cX, self.cY = cX, cY
self.r = radius
self.color = color
#Valency and geometry data
self.ID = ID #ID of the form element symbol + number
self.numSingleBonds = 0
self.numDoubleBonds = 0
self.numTripleBonds = 0
self.lonePairs = []
self.cardinals = Atom.getCardinals(self.cX, self.cY, self.r)
self.valencyLimit, self.bondLimit = Atom.getValencyData(self.atom)
self.takenPoints = set()
self.bondDomainNumber = (self.numDoubleBonds + self.numSingleBonds + self.numTripleBonds)
self.currValency = 0
self.currBonds = 0
self.lpSingles = self.bondLimit
self.lpDoubles = self.valencyLimit - self.bondLimit
if self.valencyLimit == self.bondLimit == 6:
self.lpSingles = 0
self.lpDoubles = self.valencyLimit
#Steric number and geometry data
self.stericNumber = self.bondDomainNumber + len(self.lonePairs) #Num of bonded atoms + num lone pairs on this atom
self.geometry = Atom.getGeometryFromSterics(self.stericNumber)
#Generates a list of contact points for the atom, just once at the beginning
# Each atom has 8 contact points to start
#View
def draw(self, canvas):
canvas.create_oval(self.cX - self.r, self.cY - self.r, self.cX + self.r,
self.cY + self.r, width = 0, fill = 'white')
canvas.create_text(self.cX, self.cY, font = 'Arial ' +
str(int(self.r)) + ' bold', fill = self.color, text = self.atom)
Atom.drawLonePairs(self, canvas)
#Controller
def generateLonePair(self, data):
badPoints = [] #A tuple of the bad points that links a bond to the atom
coordsToCompare = None
for bond in data.bondList:
if self in bond.connectingAtoms:
#If we dealing with double or triple bond, we just want the coords of the center line
if isinstance(bond, DoubleBond) or isinstance(bond, TripleBond):
coordsToCompare = bond.coordTupleSet3
#If we are dealing with only a single bond
elif isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
coordsToCompare = bond.coordTupleSet
if isinstance(bond, DoubleBond) or isinstance(bond, TripleBond):
for (x, y) in coordsToCompare:
if almostEqual(distance(self.cX, self.cY, x, y), self.r):
badPoints.append((x, y))
elif isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
badPoints.append(Atom.getEdgeLocationsSingleBond(coordsToCompare, self))
#Drawing on the cardinals
if len(badPoints) == 0 and self.cardinals != []:
for (x, y) in self.cardinals:
if (x, y) not in self.takenPoints:
if self.currBonds + len(self.lonePairs) < self.lpSingles:
self.lonePairs.append((x, y, 's'))
elif self.currBonds == self.lpSingles or (len(self.lonePairs)) == self.lpSingles or self.currBonds + len(self.lonePairs) == self.lpSingles:
self.lonePairs.append((x, y, 'd'))
self.takenPoints.add((x, y))
self.cardinals = self.cardinals[1:]
return
elif (len(badPoints) == 0 and self.cardinals == []) or len(badPoints) != 0:
winningPoint, maximumDistance = None, 0
tempDistance = 0
for sector in range(12):
angle = sector * math.pi / 6
newX, newY = self.cX + self.r * math.cos(angle), self.cY - self.r * math.sin(angle)
if (newX, newY) not in self.takenPoints:
if len(badPoints) != 0:
for (x, y) in badPoints:
tempDistance += distance(newX, newY, x, y)
if tempDistance > maximumDistance:
maximumDistance, winningPoint = tempDistance, (newX, newY)
elif len(badPoints) == 0:
winningPoint = (newX, newY)
tempDistance = 0
if self.currBonds + len(self.lonePairs) < self.lpSingles:
self.lonePairs.append((winningPoint[0], winningPoint[1], 's'))
elif self.currBonds >= self.lpSingles or (len(self.lonePairs)) >= self.lpSingles or self.currBonds + len(self.lonePairs) >= self.lpSingles:
self.lonePairs.append((winningPoint[0], winningPoint[1], 'd'))
self.takenPoints.add(winningPoint)
@staticmethod
def getCardinals(x, y, r):
north, south = (x, y - r), (x, y + r)
west, east = (x - r, y), (x + r, y)
return [north, south, west, east]
@staticmethod
def drawLonePairs(atom, canvas):
buffer = 2
for (xCoord, yCoord, lpType) in atom.lonePairs:
if lpType == 'd':
vector = [xCoord - atom.cX, yCoord - atom.cY]
normalVector = vectorNormalize(vector)
leftNorVec, rightNorVec = computerOrthogonals(normalVector)
firstPointX, firstPointY = xCoord + buffer * leftNorVec[0], yCoord + buffer * leftNorVec[1]
secondPointX, secondPointY = xCoord + buffer * rightNorVec[0], yCoord + buffer * rightNorVec[1]
canvas.create_oval(firstPointX - 1, firstPointY - 1, firstPointX + 1, firstPointY + 1, fill = 'black')
canvas.create_oval(secondPointX - 1, secondPointY - 1, secondPointX + 1, secondPointY + 1, fill = 'black')
elif lpType == 's':
canvas.create_oval(xCoord - 1, yCoord - 1, xCoord + 1, yCoord + 1, fill = 'black')
@staticmethod
def getEdgeLocationsSingleBond(coordSet, atom):
startingPoint = None
for (x, y) in coordSet:
if math.isclose(atom.cX, x) and math.isclose(atom.cY, y):
startingPoint = (x, y)
endPoint = None
for (x, y) in coordSet:
if (x, y) != startingPoint: endPoint = (x, y)
vector = [endPoint[0] - startingPoint[0], endPoint[1] - startingPoint[1]]
normalVector = vectorNormalize(vector)
badX = atom.cX + atom.r * normalVector[0]
badY = atom.cY + atom.r * normalVector[1]
return (badX, badY)
@staticmethod
def getValencyData(elem):
elemObj = element(elem)
valencyLimit, bondLimit = None, None
#Check what period the element is in. Greater than 3, expanded valency up to
# octahedral
if elemObj.period >= 3:
valencyLimit, bondLimit = 6, 6
#Elements in period 2 require
elif elemObj.period == 2:
groupName = elemObj.group.name
if groupName == 'Boron group': valencyLimit, bondLimit = 3, 3
elif groupName == 'Carbon group': valencyLimit, bondLimit = 4, 4
elif groupName == 'Pnictogens': valencyLimit, bondLimit = 4, 3
elif groupName == 'Chalcogens': valencyLimit, bondLimit = 4, 2
elif groupName == 'Halogens': valencyLimit, bondLimit = 4, 1
#If less than two, the only one we care about is hydrogen
elif elemObj.period == 1:
valencyLimit, bondLimit = 1, 1
return valencyLimit, bondLimit
@staticmethod
#Gets the molecular geometry from the steric number and bondDomain number (number of bonds)
def getGeometryFromSterics(steric):
if steric == 2: return 'linear'
elif steric == 3: return 'trigPlanar'
elif steric == 4: return 'tetrahedral'
elif steric == 5: return 'trigBiPyramid'
elif steric == 6: return 'octahedral'
#The parent bond class is the same as a single bond
class Bond:
#Model
def __init__(self, coordSet, atom1, atom2):
self.x1, self.y1, self.x2, self.y2 = coordSet
self.coordTupleSet = set()
self.coordTupleSet.add((self.x1, self.y1))
self.coordTupleSet.add((self.x2, self.y2))
#Keep track of the atoms that the bond is linking
self.connectingAtoms = [atom1, atom2]
#View
#Will update this method later with how to draw double and triple bonds
def draw(self, canvas):
canvas.create_line(self.x1, self.y1, self.x2, self.y2, width = 2)
class DoubleBond(Bond):
def __init__(self, coordSet, coordSet2, coordSet3, atom1, atom2):
super().__init__(coordSet, atom1, atom2)
self.secX1, self.secY1, self.secX2, self.secY2 = coordSet2
self.coordTupleSet2 = set()
self.coordTupleSet2.add((self.secX1, self.secY1))
self.coordTupleSet2.add((self.secX2, self.secY2))
self.thrX1, self.thrY1, self.thrX2, self.thrY2 = coordSet3
self.coordTupleSet3 = set()
self.coordTupleSet3.add((self.thrX1, self.thrY1))
self.coordTupleSet3.add((self.thrX2, self.thrY2))
pass
def draw(self, canvas):
canvas.create_line(self.x1, self.y1, self.x2, self.y2, width = 2)
canvas.create_line(self.secX1, self.secY1, self.secX2, self.secY2,
width = 2)
class TripleBond(DoubleBond):
def __init__(self, coordSet, coordSet2, coordSet3, atom1, atom2):
super().__init__(coordSet, coordSet2, coordSet3, atom1, atom2)
pass
def draw(self, canvas):
super().draw(canvas)
canvas.create_line(self.thrX1, self.thrY1, self.thrX2, self.thrY2,
width = 2)
class Ring:
def __init__(self, cX, cY, vertices, radius = 80):
self.cX, self.cY, self.vertices, self.r = cX, cY, vertices, radius
self.vertexList = []
self.vertexList = Ring.generatePolygonCoordinates(self.cX, self.cY, self.vertices, self.r)
self.vertexIDList = [i for i in range(len(self.vertexList))]
self.connectedAtoms = [None for i in range(len(self.vertexList))] #A series of nonetypes that we can replace gradually
def draw(self, canvas):
vertexListUnpacked = []
for (x, y) in self.vertexList:
vertexListUnpacked.append(x), vertexListUnpacked.append(y)
canvas.create_polygon(vertexListUnpacked, fill = '', outline = 'black', width = 2)
@staticmethod
def generatePolygonCoordinates(x, y, vertices, radius):
vertexList = []
sectorAngle = (2 * math.pi) / vertices
for i in range(vertices):
angle = i * sectorAngle
newX, newY = x + (radius * math.cos(angle)), y - (radius * math.sin(angle))
vertexList.append((newX, newY))
return vertexList
# =============================================================================
# Main program functions
# =============================================================================
#Comparing if two values are around equal based on 5% of max value
def almostEqual(x, y):
maxValue = max(x, y)
return abs(x - y) < 0.08 * maxValue
#Handles comparisons near zero,
def almostEqualNearZero(x, y, data):
return abs(x - y) < 0.10 * (2 * data.atomRadius)
#Euclidian distance
def distance(x1, y1, x2, y2):
return (((x2 - x1) ** 2) + ((y2 - y1) ** 2)) ** 0.5
#m = (y2 - y1) / (x2 - x1)
def calculateSlope(x1, y1, x2, y2, data):
if almostEqualNearZero((x2 - x1), 0, data):
return 'Vertical'
else: return (y2 - y1) / (x2 - x1)
#y = mx + b, finds b
def findIntercept(slope, x, y):
return y - (slope * x)
#Function for normalizing vectors
def vectorNormalize(vector):
vecMagnitude = (((vector[0]) ** 2) + ((vector[1]) ** 2)) ** 0.5
normalVector = copy.copy(vector)
for i in range(len(normalVector)):
normalVector[i] /= vecMagnitude
return normalVector
#Function for giving anti-parallel vectors
def vectorReverse(vector):
reverseVector = copy.deepcopy(vector)
for i in range(len(reverseVector)):
reverseVector[i] *= -1
return reverseVector
#In 2D space, finds the two vectors that are perpendicular to a parent vector
def computerOrthogonals(vector):
#There are two possible perpendicular vectors, and we will find both by
# switching and negating the original vector's x + y components. The original
# vector is <x, y>. The left will be <y, -x> and the right will be <-y, x>
leftPerpVector, rightPerpVector = copy.copy(vector), copy.copy(vector)
#computing the left vector
leftPerpVector[0], leftPerpVector[1] = leftPerpVector[1], leftPerpVector[0]
leftPerpVector[1] = -leftPerpVector[1]
rightPerpVector[0], rightPerpVector[1] = rightPerpVector[1], rightPerpVector[0]
rightPerpVector[0] = -rightPerpVector[0]
return leftPerpVector, rightPerpVector
#Function that generates the coordinate sets for bonds
def generateCoordSets(data, flag):
if flag == 'db':
sepFac = 2
elif flag == 'tb':
sepFac = 5
atom1, atom2 = data.atoms[data.selectedAtoms[0]], data.atoms[data.selectedAtoms[1]]
cX1, cY1, cX2, cY2 = atom1.cX, atom1.cY, atom2.cX, atom2.cY
#Vector between the two centers of two atoms, pointed in the direction
# of the second atom
vector = [cX2 - cX1, cY2 - cY1]
#Returns normal vector of magnitude 1
normalVector = vectorNormalize(vector)
#Anti-parallel of normalVector, pointing towards first atom
antiNormalVector = vectorReverse(normalVector)
stCenterX, stCenterY = cX1 + data.atomRadius * normalVector[0],\
cY1 + data.atomRadius * normalVector[1]
endCenterX, endCenterY = cX2 + data.atomRadius * antiNormalVector[0],\
cY2 + data.atomRadius * antiNormalVector[1]
#The imaginary line b/w the two bonding lines is thought of as
# (stCenterX, stCenterY) --> (endCenterX, endCenterY)
leftVec, rightVec = computerOrthogonals(normalVector)
firstX1, firstY1 = stCenterX + sepFac * leftVec[0], stCenterY + sepFac * leftVec[1]
firstX2, firstY2 = endCenterX + sepFac * leftVec[0], endCenterY + sepFac * leftVec[1]
secondX1, secondY1 = stCenterX + sepFac * rightVec[0], stCenterY + sepFac * rightVec[1]
secondX2, secondY2 = endCenterX + sepFac * rightVec[0], endCenterY + sepFac * rightVec[1]
coordSet = (firstX1, firstY1, firstX2, firstY2)
coordSet2 = (secondX1, secondY1, secondX2, secondY2)
#CoordSet for the center line is going to be the third coordSet
coordSet3 = (stCenterX, stCenterY, endCenterX, endCenterY)
return coordSet, coordSet2, coordSet3, atom1, atom2
#If you remove an atom, we also want to remove all the bonds tied to that
# atom, and decrease the counts of all other connected atoms accordingly
def removeBadBondsAtomDependent(data, target):
remAtom = data.atoms[target]
badBonds = set()
for i in range(len(data.bondList)):
bond = data.bondList[i]
if remAtom in bond.connectingAtoms:
badBonds.add(i)
newBondList = []
for i in range(len(data.bondList)):
bond = data.bondList[i]
if i not in badBonds: newBondList.append(bond)
else:
for atom in bond.connectingAtoms:
if isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
atom.numSingleBonds -= 1
elif isinstance(bond, DoubleBond) and not isinstance(bond, TripleBond):
atom.numDoubleBonds -= 1
elif isinstance(bond, TripleBond):
atom.numTripleBonds -= 1
updateCurrValency(atom)
data.bondList = newBondList
def singleBondCheck(mousex, mousey, bond, data):
farthestRight = max(bond.x1, bond.x2)
farthestLeft = min(bond.x1, bond.x2)
if mousex > farthestRight or mousex < farthestLeft: pass
else:
slope = calculateSlope(bond.x1, bond.y1, bond.x2, bond.y2, data)
#Dealing with near vertical bonds
if slope == 'Vertical':
farthestUp = min(bond.y1, bond.y2)
farthestDown = max(bond.y1, bond.y2)
if farthestUp < mousey < farthestDown:
return True
else:
intCept = findIntercept(slope, bond.x1, bond.y1)
eqOutput = (slope * mousex) + intCept
#If the mouse position is close enough to the bond position
# for math.isclose, the rel_tol is a percentage
if almostEqual(eqOutput, mousey):
return True
def doubleTripleCheck(mousex, mousey, bond, data):
firstX1, firstY1, firstX2, firstY2 = bond.x1, bond.y1, bond.x2, bond.y2
secX1, secY1, secX2, secY2 = bond.secX1, bond.secY1, bond.secX2, bond.secY2
thrX1, thrY1, thrX2, thrY2 = bond.thrX1, bond.thrY1, bond.thrX2, bond.thrY2
farthestRight = max(firstX1, firstX2, secX1, secX2, thrX1, thrX2)
farthestLeft = min(firstX1, firstX2, secX1, secX2, thrX1, thrX2)
if mousex > farthestRight or mousex < farthestLeft: pass
else:
slope = calculateSlope(firstX1, firstY1, firstX2, firstY2, data)
if slope == 'Vertical':
farthestUp = min(firstY1, firstY2, secY1, secY2, thrY1, thrY2)
farthestDown = max(firstY1, firstY2, secY1, secY2, thrY1, thrY2)
if farthestUp < mousey < farthestDown:
return True
else:
#Wildly unequal intercepts
intCept1 = findIntercept(slope, firstX1, firstY1)
intCept2 = findIntercept(slope, secX1, secY1)
intCept3 = findIntercept(slope, thrX1, thrY1)
eqOutput1 = (slope * mousex) + intCept1
eqOutput2 = (slope * mousex) + intCept2
eqOutput3 = (slope * mousex) + intCept3
maxOut = max(eqOutput1, eqOutput2, eqOutput3)
minOut = min(eqOutput1, eqOutput2, eqOutput3)
proxCondition = (almostEqual(eqOutput1, mousey) or almostEqual(eqOutput2, mousey)\
or almostEqual(eqOutput3, mousey)) or (minOut < mousey < maxOut)
if proxCondition:
return True
#Removing bonds just by clicking on them, checks slope formulas. Takes in event.x,
# event.y, and data
def removeBadBondsNonAtomDependent(mousex, mousey, data, flag):
badBondIndSet = set()
for i in range(len(data.bondList)):
bond = data.bondList[i]
#if we are dealing with a single bond
if isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
if singleBondCheck(mousex, mousey, bond, data):
if len(badBondIndSet) < 1:
badBondIndSet.add(i)
flag.append(True)
#Double bonds and triple bonds require that we check three lines
elif isinstance(bond, DoubleBond) or isinstance(bond, TripleBond):
if doubleTripleCheck(mousex, mousey, bond, data):
if len(badBondIndSet) < 1:
badBondIndSet.add(i)
flag.append(True)
newBondList = []
for i in range(len(data.bondList)):
bond = data.bondList[i]
if i not in badBondIndSet: newBondList.append(bond)
else:
for atom in bond.connectingAtoms:
if isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
atom.numSingleBonds -= 1
elif isinstance(bond, DoubleBond) and not isinstance(bond, TripleBond):
atom.numDoubleBonds -= 1
elif isinstance(bond, TripleBond):
atom.numTripleBonds -= 1
updateCurrValency(atom)
data.bondList = newBondList
#TODO: Finish this method
def removeRings(mouseX, mouseY, data):
badRingIndex = None
for i in range(len(data.rings)):
ring = data.rings[i]
cX, cY = ring.cX, ring.cY
dist = distance(mouseX, mouseY, cX, cY)
if dist < data.atomRadius:
badRingIndex = i
break
if badRingIndex == None:
return
else:
badRing = data.rings[badRingIndex]
for atom in badRing.connectedAtoms:
if atom != None:
atom.numSingleBonds -= 2
updateCurrValency(atom)
data.rings.pop(badRingIndex)
#Initializes data for the program
def init(data):
data.atoms = []
data.atom = 'C'
data.cursorMode = 'atomPlacement'
data.atomRadius = 20
data.selectedAtoms = []
data.bondType = 'single'
data.bondList = []
data.rightCursorMode = 'rmAtom'
data.atomDict = dict()
data.rings = []
data.ringVertices = 3
data.moleculeFormula = ""
data.moleculeWeight = 0
data.order = ['C', 'H', 'N', 'O']
data.stringVar = StringVar()
data.stringVar.set("Formula: %s Weight: %0.2f g/mol Cursor Mode: %s Atom: %s" %
(data.moleculeFormula, data.moleculeWeight, data.cursorMode, data.atom))
def partialInit(data):
data.atoms = []
data.atom = 'C'
data.cursorMode = 'atomPlacement'
data.selectedAtoms = []
data.bondType = 'single'
data.bondList = []
data.atomDict = dict()
data.rings = []
data.ringVertices = 3
data.moleculeFormula = ""
data.moleculeWeight = 0
data.stringVar.set("Formula: %s Weight: %0.2f g/mol Cursor Mode: %s Atom: %s" %
(data.moleculeFormula, data.moleculeWeight, data.cursorMode, data.atom))
def findNearestRingVertex(x, y, data):
ringID, closestVertexID, minDistance = None, None, None
for i in range(len(data.rings)): #The ring ID in data.rings
ring = data.rings[i]
for j in range(len(ring.vertexList)): #The vertexID inside the ring's vertex list
(x2, y2) = ring.vertexList[j]
dist = distance(x, y, x2, y2)
if minDistance == None:
minDistance, closestVertexID, ringID = dist, j, i
elif minDistance != None:
if dist < minDistance:
minDistance, closestVertexID, ringID = dist, j, i
return ringID, closestVertexID, minDistance
#Finds the closest atom to a mouseclick
def findClosestAtom(x, y, data):
minDistance = None
closestAtomIndex = None
for i in range(len(data.atoms)):
atom = data.atoms[i]
x2, y2 = atom.cX, atom.cY
dist = distance(x, y, x2, y2)
if minDistance == None:
minDistance, closestAtomIndex = dist, i
elif minDistance != None:
if dist < minDistance:
minDistance, closestAtomIndex = dist, i
return minDistance, closestAtomIndex
#Checks to see if the atom to be placed overlaps with any other atom
def checkOverlap(atom, data):
#Simple check to see if the atoms overlap
x1, y1 = atom.cX, atom.cY
for atom in data.atoms:
x2, y2 = atom.cX, atom.cY
#Overlap is found
if distance(x1, y1, x2, y2) <= 2 * data.atomRadius:
return True
return False
#Checks to see if the atom to be placed overlaps any existing bonds, based off
# a series of points around the atom
def checkBondOverlap(atom, data):
cX, cY = atom.cX, atom.cY
for bond in data.bondList:
if isinstance(bond, Bond) and not ((isinstance(bond, DoubleBond) or isinstance(bond, TripleBond))):
#Chose 12 b/c 2pi / (pi/6) = 12
for sector in range(12):
angle = sector * math.pi / 6
x, y = cX + atom.r * math.cos(angle), cY - atom.r * math.sin(angle)
if singleBondCheck(x, y, bond, data):
return True
elif isinstance(bond, DoubleBond) or isinstance(bond, TripleBond):
for sector in range(12):
angle = sector * math.pi / 6
x, y = cX + atom.r * math.cos(angle), cY - atom.r * math.sin(angle)
if doubleTripleCheck(x, y, bond, data):
return True
return False
def updateBondNumber(data): #Updates the number of bonds that an atom has attached to it
selectedAtomIDs = [data.atoms[data.selectedAtoms[0]].ID, data.atoms[data.selectedAtoms[1]].ID]
selectedAtomIDSet = set(selectedAtomIDs)
for bond in data.bondList:
joinedAtomIDs = [atom.ID for atom in bond.connectingAtoms]
joinedAtomIDSet = set(joinedAtomIDs)
if joinedAtomIDSet == selectedAtomIDSet:
for atom in data.atoms:
if atom.ID in selectedAtomIDSet:
if isinstance(bond, Bond) and not ((isinstance(bond, DoubleBond) or isinstance(bond, TripleBond))):
atom.numSingleBonds += 1
elif isinstance(bond, DoubleBond) and not isinstance(bond, TripleBond):
atom.numDoubleBonds += 1
elif isinstance(bond, TripleBond):
atom.numTripleBonds += 1
updateCurrValency(atom)
#Updates the current valency and steric number and others
def updateCurrValency(atom):
atom.currValency = (atom.numSingleBonds) + (2 * atom.numDoubleBonds) + (3 * atom.numTripleBonds) + len(atom.lonePairs)
atom.currBonds = (atom.numSingleBonds) + (2 * atom.numDoubleBonds) + (3 * atom.numTripleBonds)
atom.bondDomainNumber = atom.numSingleBonds + atom.numDoubleBonds + atom.numTripleBonds
atom.stericNumber = atom.bondDomainNumber + len(atom.lonePairs)
atom.geometry = Atom.getGeometryFromSterics(atom.stericNumber)
#TODO: Continue from here
def updateFormulaAndWeight(data):
countDict = dict()
formula, weight = '', 0
#Gives us a count of all the elements
for atom in data.atoms:
elem = atom.atom
if elem in countDict:
countDict[elem] += 1
elif elem not in countDict:
countDict[elem] = 1
keySet = set(countDict.keys())
finishedAtoms = set()
#Adds all the elements from data.order first
for atomSym in data.order:
if atomSym in keySet:
tempAddition = atomSym + str(countDict[atomSym])
formula += tempAddition
elemObj, count = element(atomSym), countDict[atomSym]
weight += (count * elemObj.atomic_weight)
finishedAtoms.add(atomSym)
for atomos in countDict:
if atomos not in finishedAtoms:
tempAddition = atomos + str(countDict[atomos])
formula += tempAddition
elemObj, count = element(atomos), countDict[atomos]
weight += (count * elemObj.atomic_weight)
finishedAtoms.add(atomos)
data.moleculeFormula, data.moleculeWeight = formula, weight
data.stringVar.set("Formula: %s Weight: %0.2f g/mol Cursor Mode: %s Atom: %s" %
(data.moleculeFormula, data.moleculeWeight, data.cursorMode, data.atom))
#Generating popup messages
def popupMsg(msg):
popup = Tk()
#Icon taken from https://www.flaticon.com/free-icon/molecule_195742
popup.iconbitmap(os.path.join(os.getcwd(), 'BackgroundImages', 'molecule.ico'))
popup.resizable(width = False, height = False)
popup.wm_title('Error!')
label = Label(popup, text = msg, font = 'Arial 12 bold')
label.pack(side = 'top', fill = 'x', pady = 10)
B1 = Button(popup, text = 'Okay', command = popup.destroy)
B1.pack()
popup.mainloop()
#PAY CLOSE ATTENTION TO THIS FUNCTION
def mousePressed(event, data):
# use event.x and event.y
#Updates the number of the atom that is shown on screen
if data.cursorMode == 'atomPlacement':
element = data.atom
if element not in data.atomDict: data.atomDict[element] = 1
else: data.atomDict[element] += 1
ID = element + str(data.atomDict[element]) #Add in a unique identifier for each atom
ringID, closestVertexID, minDistanceVertex = findNearestRingVertex(event.x, event.y, data)
if minDistanceVertex != None and minDistanceVertex < data.atomRadius:
atmX, atmY = data.rings[ringID].vertexList[closestVertexID]
atom = Atom(element, atmX, atmY, data.atomRadius, ID)
data.rings[ringID].connectedAtoms[closestVertexID] = atom
data.atoms.append(atom)
updateValencyInRing(data)
updateFormulaAndWeight(data)
else:
atom = Atom(element, event.x, event.y, data.atomRadius, ID)
if not checkOverlap(atom, data) and not checkBondOverlap(atom, data):
data.atoms.append(atom)
updateFormulaAndWeight(data)
elif data.cursorMode == 'lonePairPlacement': #Placing lone pairs
minDistance, closestAtomIndex = findClosestAtom(event.x, event.y, data)
if minDistance == None: pass
elif minDistance != None:
if minDistance < data.atomRadius:
atom = data.atoms[closestAtomIndex]
if atom.currValency < atom.valencyLimit:
atom.generateLonePair(data)
updateCurrValency(atom)
else: popupMsg('Maximum Valency Exceeded!')
elif data.cursorMode == 'bondPlacement': #Creating bonds
minDistance, closestAtomIndex = findClosestAtom(event.x, event.y, data)
#if minDistance == None, no atom was found
if minDistance == None: pass
elif minDistance != None:
if minDistance < data.atomRadius:
atom = data.atoms[closestAtomIndex]
atom.color = 'green'
data.selectedAtoms.append(closestAtomIndex)
else:
for atom in data.atoms: atom.color = 'black' #clicking outside the molecule resets all atom colors to black
data.selectedAtoms = []
return
if len(data.selectedAtoms) == 2: #two atoms have been selected
checkAndGenerateBonds(data)
elif len(data.selectedAtoms) > 2: #more than two atoms have been selected
data.selectedAtoms = [data.selectedAtoms[-1]] #Keep only the third one
for i in range(len(data.atoms)):
if i not in data.selectedAtoms:
#Reset all colors to black
data.atoms[i].color = 'black'
elif data.cursorMode == 'ringPlacement':
ring = Ring(event.x, event.y, data.ringVertices)
data.rings.append(ring)
def checkAndGenerateBonds(data):
selectedAtomIDs = [data.atoms[data.selectedAtoms[0]].ID, data.atoms[data.selectedAtoms[1]].ID]
selectedAtomIDSet = set(selectedAtomIDs)
for bond in data.bondList:
joinedAtomIDs = [atom.ID for atom in bond.connectingAtoms]
joinedAtomIDSet = set(joinedAtomIDs)
if selectedAtomIDSet == joinedAtomIDSet: return #A bond already exists between these two atoms
for index in data.selectedAtoms:
atom = data.atoms[index]
if data.bondType == 'single':
if not atom.currBonds <= (atom.bondLimit - 1):
popupMsg('Maximum Valency Exceeded!')
return
elif data.bondType == 'double':
if not atom.currBonds <= (atom.bondLimit - 2):
popupMsg('Maximum Valency Exceeded!')
return
elif data.bondType == 'triple':
if not atom.currBonds <= (atom.bondLimit - 3):
popupMsg('Maximum Valency Exceeded!')
return
generateBond(data)
updateBondNumber(data)
#General method for removing elements from the screen
def mouseRightClick(event, data):
minDistance, closestAtomIndex = findClosestAtom(event.x, event.y, data)
#if minDistance == None, no atom was found
if minDistance == None: pass
elif minDistance != None:
if minDistance < data.atomRadius:
removeBadBondsAtomDependent(data, closestAtomIndex) #FIX here so that all the atoms after the one that's popped are lowered in number by one
if closestAtomIndex != len(data.atoms) - 1:
closestAtomElement = data.atoms[closestAtomIndex].atom
finalIndex = None
for i in range(closestAtomIndex + 1, len(data.atoms)):
atom = data.atoms[i]
if atom.atom == closestAtomElement:
idStr = atom.ID
splitList = re.split('(\d+)', idStr)
number = int(splitList[1])
number -= 1
newID = splitList[0] + str(number)
atom.ID = newID
finalIndex = i
#This was the last element of that kind in the list
if finalIndex == None:
removedAtom = data.atoms[closestAtomIndex]
removeAtomFromRingData(removedAtom, data)
splitLst = re.split('(\d+)', removedAtom.ID)
number = int(splitLst[1])
data.atomDict[removedAtom.atom] = number - 1
data.atoms.pop(closestAtomIndex)
#Another element of that kind was found later in the list
elif finalIndex != None:
finalAtom = data.atoms[finalIndex]
#Handle the ring data first; the finalID is to deal with other atoms
removedAtom = data.atoms[closestAtomIndex]
removeAtomFromRingData(removedAtom, data)
finalID = finalAtom.ID
splitListFinal = re.split('(\d+)', finalID)
data.atomDict[finalAtom.atom] = int(splitListFinal[1])
data.atoms.pop(closestAtomIndex)
else: #In the event that the atom you removed is the last one in the list
removedAtom = data.atoms.pop(closestAtomIndex)
removeAtomFromRingData(removedAtom, data)
splitLst = re.split('(\d+)', removedAtom.ID)
data.atomDict[removedAtom.atom] = int(splitLst[1]) - 1
updateFormulaAndWeight(data)
return
#Here, we make it so that you can remove the bonds by right clicking on
flag = []
removeBadBondsNonAtomDependent(event.x, event.y, data, flag)
if flag == [True]:
updateFormulaAndWeight(data)
else:
removeRings(event.x, event.y, data)
updateFormulaAndWeight(data)
#FIx this function
def removeAtomFromRingData(removedAtom, data):
if len(data.rings) == 0:
pass
else:
ringID, vertexID = None, None
x, y = removedAtom.cX, removedAtom.cY
for i in range(len(data.rings)):
ring = data.rings[i]
for j in range(len(ring.vertexList)):
(x2, y2) = ring.vertexList[j]
if x2 == x and y2 == y:
ringID, vertexID = i, j
if ringID != None and vertexID != None:
ring = data.rings[ringID]
ring.connectedAtoms[vertexID] = None
def generateBond(data):
#First, find the closest two contact points between atoms
if data.bondType == 'single':
atom1Index, atom2Index = data.selectedAtoms[0], data.selectedAtoms[1]
atom1, atom2 = data.atoms[atom1Index], data.atoms[atom2Index]
coordSet = (atom1.cX, atom1.cY, atom2.cX, atom2.cY)
bond = Bond(coordSet, atom1, atom2)
data.bondList.append(bond)
elif data.bondType == 'double':
coordSet, coordSet2, coordSet3, atom1, atom2 = generateCoordSets(data, 'db')
bond = DoubleBond(coordSet, coordSet2, coordSet3, atom1, atom2)
data.bondList.append(bond)
elif data.bondType == 'triple':
coordSet, coordSet2, coordSet3, atom1, atom2 = generateCoordSets(data, 'tb')
bond = TripleBond(coordSet, coordSet2, coordSet3, atom1, atom2)
data.bondList.append(bond)
# =============================================================================
# Represent the connectivity matrix as a dictionary as follows:
# {Atom1 : [(Atom2, 'sb'), (Atom3, 'sb'), (Atom4, 'sb'), (Atom5, 'sb'), 'tetrahedral']...}
# Each atom is a key that connects to other atoms, and we will draw based of the specific geometries
# =============================================================================
def generateConnectivityMatrix(data): #Generates the adjacency matrix for 3D drawing
connectMatrix = {}
for atom in data.atoms:
atomID, tempList = atom.ID, []
for bond in data.bondList:
tempAddition = None
joinedAtomIDs = [atom.ID for atom in bond.connectingAtoms]
joinedAtomIDSet = set(joinedAtomIDs)
if atomID in joinedAtomIDSet:
joinedAtomIDSet.remove(atomID)
remainingAtom = list(joinedAtomIDSet)[0]
if isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
tempAddition = (remainingAtom, 'sb')
elif isinstance(bond, DoubleBond) and not (isinstance(bond, TripleBond)):
tempAddition = (remainingAtom, 'db')
elif isinstance(bond, TripleBond):
tempAddition = (remainingAtom, 'tb')
tempList.append(tempAddition)
tempList.append(atom.geometry)
connectMatrix[atomID] = tempList
return connectMatrix
#Generate a partial connectivity matrix from the ring data
def genConnectMatrixFromRingData(data):
partialConnectMatrix = {}
for i in range(len(data.rings)):
ring = data.rings[i]
for j in range(len(ring.connectedAtoms)):
tempList, currAtom = [], ring.connectedAtoms[j].ID
prevIndex, nextIndex = j - 1, j + 1
#Handles indexing out of range
if nextIndex > len(ring.connectedAtoms) - 1:
nextIndex = nextIndex % len(ring.connectedAtoms)
tempList.append((ring.connectedAtoms[prevIndex].ID, 'sb'))
tempList.append((ring.connectedAtoms[nextIndex].ID, 'sb'))
tempList.append('ring' + str(i))
partialConnectMatrix[currAtom] = tempList
updateValencyInRing(data)
return partialConnectMatrix
#TODO: Continue here
#Updates the connectivity matrix generated from ring data
def updatePartialConnectivityMatrix(partialRingMatrix, data):
originalRingMatrixKeys = set(partialRingMatrix.keys())
for atom in data.atoms:
atomID = atom.ID
if atomID in originalRingMatrixKeys:
currResult = partialRingMatrix[atomID]
tempLst = []
for bond in data.bondList:
joinedAtomIDs = [atm.ID for atm in bond.connectingAtoms]
joinedAtomIDSet = set(joinedAtomIDs)
if atomID in joinedAtomIDSet:
joinedAtomIDSet.remove(atomID)
remainingAtom = list(joinedAtomIDSet)[0]
if isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
tempLst.append((remainingAtom, 'sb'))
elif isinstance(bond, DoubleBond) and not (isinstance(bond, TripleBond)):
tempLst.append((remainingAtom, 'db'))
elif isinstance(bond, TripleBond):
tempLst.append((remainingAtom, 'tb'))
finalResult = currResult + tempLst
partialRingMatrix[atomID] = finalResult
elif atomID not in originalRingMatrixKeys:
tempLst = []
for bond in data.bondList:
tempAddition = None
joinedAtomIDs = [atm.ID for atm in bond.connectingAtoms]
joinedAtomIDSet = set(joinedAtomIDs)
if atomID in joinedAtomIDSet:
joinedAtomIDSet.remove(atomID)
remainingAtom = list(joinedAtomIDSet)[0]
if isinstance(bond, Bond) and not (isinstance(bond, DoubleBond) or isinstance(bond, TripleBond)):
tempAddition = (remainingAtom, 'sb')
elif isinstance(bond, DoubleBond) and not (isinstance(bond, TripleBond)):
tempAddition = (remainingAtom, 'db')
elif isinstance(bond, TripleBond):
tempAddition = (remainingAtom, 'tb')
tempLst.append(tempAddition)
tempLst.append(atom.geometry) #Only add the geometry if the atom is not in a ring
partialRingMatrix[atomID] = tempLst
def addRingEntries(partialMatrixUpdated, data):
masterRingList = []
for ring in data.rings:
connectedAtoms = ring.connectedAtoms
idList = [atm.ID for atm in connectedAtoms]
masterRingList.append(idList)
partialMatrixUpdated['rings'] = masterRingList
def updateValencyInRing(data): #By default, atoms in a ring will only have, at max, four atoms bonded to it
for ring in data.rings:
for atom in ring.connectedAtoms:
if atom != None:
atom.numSingleBonds = 2
updateCurrValency(atom)
data.ringValencyUpdated = True
#Checks if there are solo atoms; molecule fails immediately if this is true
def checkConectivitySoloAtoms(matrix):
for atom in matrix:
connectedAtoms = matrix[atom]
if len(connectedAtoms) == 1:
return False
return True
def keyPressed(event, data):
# use event.char and event.keysym
if event.char == 'Z':
if data.cursorMode == 'atomPlacement':
if len(data.atoms) != 0:
data.atoms.pop()
elif data.cursorMode == 'bondPlacement':
if len(data.bondList) != 0:
data.bondList.pop()
elif event.char == 'l':
data.cursorMode = 'lonePairPlacement'
data.stringVar.set("Formula: %s Weight: %0.2f g/mol Cursor Mode: %s Atom: %s" %
(data.moleculeFormula, data.moleculeWeight, data.cursorMode, data.atom))
elif event.char == 'b':
bondPopup(data)
elif event.char == 'a':
data.cursorMode = 'atomPlacement'
data.stringVar.set("Formula: %s Weight: %0.2f g/mol Cursor Mode: %s Atom: %s" %
(data.moleculeFormula, data.moleculeWeight, data.cursorMode, data.atom))
elif event.char == 'r':
partialInit(data)
updateFormulaAndWeight(data)
elif event.char == 'i':
ringPopUp(data)
def redrawAll(canvas, data):
for bond in data.bondList:
bond.draw(canvas)
for ring in data.rings:
ring.draw(canvas)
for atom in data.atoms:
atom.draw(canvas)
#Menu Functions to be called
def resetData(canvas, data):
partialInit(data)
canvas.delete(ALL)
canvas.create_rectangle(0, 0, data.width, data.height,
fill='white', width=0)
redrawAll(canvas, data)
canvas.update()
#Saving, loading: Pickle, filedialog?
def updateReference(data): #Relinks items together after a pickle file has been loaded
#Update bond reference first
for bond in data.bondList:
connectedAtoms = bond.connectingAtoms
connectedAtomsIDs = [atom.ID for atom in connectedAtoms]
for i in range(len(connectedAtomsIDs)):
currID = connectedAtomsIDs[i]
for atm in data.atoms:
if atm.ID == currID:
connectedAtoms[i] = atm
bond.connectingAtoms = connectedAtoms
#Update ring references next
for ring in data.rings:
joinedAtoms = ring.connectedAtoms
joinedAtomsIDs = [elem.ID for elem in joinedAtoms]
for j in range(len(joinedAtomsIDs)):
currentID = joinedAtomsIDs[j]
for atomos in data.atoms:
if atomos.ID == currentID:
joinedAtoms[j] = atomos
ring.connectedAtoms = joinedAtoms
def saveLewisStructures(data):
filePath = os.path.join(os.getcwd(), 'LewisStructs', data.moleculeFormula) + '.p'
file_out = open(filePath, 'wb')
pickle.dump(data.atoms, file_out)
pickle.dump(data.bondList, file_out)
pickle.dump(data.atomDict, file_out)
pickle.dump(data.rings, file_out)
pickle.dump(data.moleculeFormula, file_out)
pickle.dump(data.moleculeWeight, file_out)
#The objects are serialized in order, so load them in order
file_out.close()
def saveAsLewisStructures(data):
tempPop = Tk()
#Icon taken from https://www.flaticon.com/free-icon/molecule_195742