-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqaTerm.py
1519 lines (1239 loc) · 59.4 KB
/
sqaTerm.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
# Copyright 2009-2022 SecondQuantizationAlgebra Developers. All Rights Reserved.
#
# Licensed under the GNU General Public License v3.0;
# you may not use this file except in compliance with the License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# In addition, any modification or use of this software should
# cite the following paper:
#
# E. Neuscamman, T. Yanai, and G. K.-L. Chan.
# J. Chem. Phys. 130, 124102 (2009)
#
# Author: Eric Neuscamman <[email protected]>
#
# The term class represents a set of constants and tensors that have been multiplied together.
# The class consists of a numerical constant factor, a list of named constants, and a list
# of tensors.
#
# It is common to encounter a list of term objects, which is often used to represent an expression.
# For example, the Hamiltonian in second quantization can be written as a list of terms.
#
import threading
from sqaIndex import index
from sqaTensor import tensor, kroneckerDelta, sfExOp, creOp, desOp
from sqaMisc import makePermutations
from sqaOptions import options
import time
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
class term:
"A class for terms used in operator algebra. Each term is a multiplicative string of constants, tensors, and operators."
#------------------------------------------------------------------------------------------------
def __init__(self, numConstant, constList, tensorList, isInCanonicalForm = False):
self.constants = []
self.tensors = []
if type(numConstant) == type(1.0) or type(numConstant) == type(1):
self.numConstant = float(numConstant)
else:
raise TypeError("numConstant must be given as a float or an int.")
for c in constList:
if type(c) != type('a'):
raise TypeError("constList must be a list of strings")
self.constants.append(c)
for t in tensorList:
if not isinstance(t, tensor):
raise TypeError("tensorList must be a list of tensor objects")
self.tensors.append(t.copy())
if type(isInCanonicalForm) == type(True):
self.isInCanonicalForm = isInCanonicalForm
else:
raise TypeError("if specified, isInCanonicalForm must be True or False")
#------------------------------------------------------------------------------------------------
def __cmp__(self,other):
if not isinstance(other,term):
raise TypeError("term object can only be compared to other term objects.")
# sort by number of loose creation operators first
retval = cmp(self.nCreOps(),other.nCreOps())
if retval != 0:
return retval
# next sort by number of loose destruction operators
retval = cmp(self.nDesOps(),other.nDesOps())
if retval != 0:
return retval
# next sort by the orders of the spin free excitation operators
retval = cmp(self.sfExOp_ranks(),other.sfExOp_ranks())
if retval != 0:
return retval
# next sort by the number of constants
retval = cmp(len(self.constants),len(other.constants))
if retval != 0:
return retval
# next sort by the number of tensors
retval = cmp(len(self.tensors),len(other.tensors))
if retval != 0:
return retval
# next sort by the tensors' names
retval = cmp([t.name for t in self.tensors], [t.name for t in other.tensors])
if retval != 0:
return retval
# next sort by the tensors
retval = cmp(self.tensors,other.tensors)
if retval != 0:
return retval
# next sort by the constants
retval = cmp(self.constants,other.constants)
if retval != 0:
return retval
# finally compare the numerical constants
numDiff = self.numConstant - other.numConstant
if abs(numDiff) < 1e-6:
return 0
elif numDiff < 0:
return -1
elif numDiff > 0:
return 1
else:
raise RuntimeError("Failure in comparison of terms' numeric constants.")
return numDiff
#------------------------------------------------------------------------------------------------
def __str__(self):
# numerical constant
retval = " (%10.5f) " %self.numConstant
# non-numerical constants
for i in range(len(self.constants)):
retval += self.constants[i] + " "
# tensors
for t in self.tensors:
retval += str(t) + " "
return retval
#------------------------------------------------------------------------------------------------
def __add__(self,other):
"Adds the terms self and other. Only works if the constants, tensors, and operators of two terms all match."
if self.sameForm(other):
retval = self.copy()
retval.numConstant += other.numConstant
else:
raise RuntimeError("self and other must have the same constants, tensors, and operators")
return retval
#------------------------------------------------------------------------------------------------
def copy(self):
"Returns a deep copy of the term."
return term(self.numConstant, self.constants, self.tensors, self.isInCanonicalForm)
#------------------------------------------------------------------------------------------------
def nCreOps(self):
"Returns the number of loose creation operators in the term"
retval = 0
for t in self.tensors:
if isinstance(t, creOp):
retval += 1
return retval
#------------------------------------------------------------------------------------------------
def nDesOps(self):
"Returns the number of loose destruction operators in the term"
retval = 0
for t in self.tensors:
if isinstance(t, desOp):
retval += 1
return retval
#------------------------------------------------------------------------------------------------
def sfExOp_ranks(self):
"Returns a list of the ranks of the spin free excitation operators in the term"
retval = []
for t in self.tensors:
if isinstance(t, sfExOp):
retval.append(len(t.indices)/2)
return retval
#------------------------------------------------------------------------------------------------
def scale(self, factor):
"Multiplies the term by factor."
if type(factor) == type(1.0) or type(factor) == type(1):
self.numConstant *= factor
else:
raise ValueError("factor must an integer or float")
#------------------------------------------------------------------------------------------------
def sameForm(self,other):
"Determines whether the terms are of the same form."
self.makeCanonical()
other.makeCanonical()
if self.constants != other.constants or self.tensors != other.tensors:
return False
return True
#------------------------------------------------------------------------------------------------
def contractDeltaFuncs(self):
"Contracts the indices within any kronecker delta functions in the term."
i = 0
while i < len(self.tensors):
t = self.tensors[i]
# If the term is a delta funciton with a repeated index, remove it
if isinstance(t, kroneckerDelta) and (t.indices[0] == t.indices[1]) and (t.indices[0].userDefined == t.indices[1].userDefined):
del(self.tensors[i])
# If the term is a delta funciton with contractable indices, contract them and remove the delta func
elif isinstance(t, kroneckerDelta) and (t.indices[0].isSummed or t.indices[1].isSummed):
i0 = t.indices[0]
i1 = t.indices[1]
# Check that the indices have the same number of type groups
if len(i0.indType) != len(i1.indType):
raise RuntimeError("Cannot contract indices %s, %s. They have different numbers of type groups." %(str(i0), str(i1)))
# Determine the type of the new index based on the overlap between
# the types of the two indices
typeOverlap = []
for j in range(len(i0.indType)):
typeOverlap.append([])
for typeString in i0.indType[j]:
if typeString in i1.indType[j]:
typeOverlap[-1].append(typeString)
# for l0 in i0.indType:
# typeOverlap.append([])
# for s0 in l0:
# for l1 in i1.indType:
# if s0 in l1:
# typeOverlap[-1].append(s0)
# If there is no overlap between any of the type groups, the delta function is zero
if ( len(i0.indType) > 0 or len(i1.indType) > 0 ) and [] in typeOverlap:
self.numConstant = 0.0
return
# Create the new index
if not i0.isSummed:
newIndex = index(i0.name, typeOverlap, i0.isSummed, i0.userDefined)
else:
newIndex = index(i1.name, typeOverlap, i1.isSummed, i1.userDefined)
# Remove the delta function
del(self.tensors[i])
# Excecute the index replacement
for ten in self.tensors:
for j in range(len(ten.indices)):
if ten.indices[j] in [i0,i1]:
ten.indices[j] = newIndex.copy()
# Otherwise move on to the next tensor
else:
i += 1
#------------------------------------------------------------------------------------------------
def generateAlphabet(self):
"Returns a list of strings that shares no elements with the term's index names."
# Compile list of index names in self
usedNames = []
for t in self.tensors:
for i in t.indices:
if i.userDefined:
i.name = 'user_' + i.userDefined
if not (i.name in usedNames):
usedNames.append(i.name)
# Generate an alphabet with no elements overlapping with usedNames
alphabet = []
i = 0
while len(alphabet) < len(usedNames):
if not (str(i) in usedNames):
alphabet.append(str(i))
i += 1
return alphabet
#------------------------------------------------------------------------------------------------
def isNormalOrdered(self):
"Returns true if the term is in normal order and false otherwise"
creFlag = False
desFlag = False
sfExFlag = False
for t in self.tensors:
if ( isinstance(t,creOp) or isinstance(t,sfExOp) ) and ( desFlag or sfExFlag ):
return False
if isinstance(t, creOp):
creFlag = True
if isinstance(t, desOp):
desFlag = True
if isinstance(t, sfExOp):
sfExFlag = True
return True
#------------------------------------------------------------------------------------------------
def makeCanonical(self, rename_user_defined = True):
"Converts the term to a unique canonical form."
# Use the non recursive function
self.makeCanonical_non_recursive(rename_user_defined)
return
# If the tensor is already in canonical form, do nothing
if self.isInCanonicalForm:
return
# print "Converting to canonical form:"
# print self
# If the term is not normal ordered, raise an error
if not self.isNormalOrdered():
raise RuntimeError("A term must have normal ordered operators to be converted to canonical form.")
# Sort the constants
self.constants.sort()
# If there are no tensors in the term then skip the tensor sorting.
if len(self.tensors) == 0:
self.isInCanonicalForm = True
return
# Create all tensor lists in which the tensors are sorted by type and name.
# There can be more than one term here if there are multiple tensors with the same name.
candidateTensorLists = self.getCandidateTensorLists()
# Generate an alphabet for use in renaming indices
# This is done to avoid renaming with an index name already in use.
# Should try using numbers, i.e. '1', '2', '3', etc.
alphabet = self.generateAlphabet()
# For each candidate list, rename the indices canonically and record the score for that list.
bestScore = [-1]
nTopScore = 0
for i in range(len(candidateTensorLists)):
(score,map,sign,newTensorList) = getcim(candidateTensorLists[i],alphabet)
if score > bestScore:
(bestScore,bestMap,bestSign,bestTensorList) = (score,map,sign,newTensorList)
nTopScore = 1
elif score == bestScore:
nTopScore += 1
# Check to see that only one candidate achieved the top score
if nTopScore > 1:
raise RuntimeError("%i candidates tied for the top score." %nTopScore)
# Set the tensors and their indices in the canonical order (the order with the highest score)
self.tensors = bestTensorList
# Apply the sign produced from the index sorting
self.scale(bestSign)
# Create an index mapping that converts to a canonical alphabet, i.e. a-z
map = bestMap
alphabet = list('abcdefghijklmnopqrstuvwxyz')
if len(alphabet) < len(map):
raise RuntimeError("Alphabet smaller than number of indices, no more names left!")
canonMap = {}
while map.keys():
minVal = min(map.values())
for key in map.keys():
if map[key] == minVal:
canonMap[map[key].tup()] = map[key].copy()
canonMap[map[key].tup()].name = alphabet.pop(0)
del map[key]
break
map = canonMap
# Rename the indices using the canonical mapping
for t in self.tensors:
for i in range(len(t.indices)):
if t.indices[i].tup() in map.keys():
t.indices[i] = map[t.indices[i].tup()].copy()
# Turn on the canonical form flag to avoid calling this function again unnecessarily
self.isInCanonicalForm = True
#------------------------------------------------------------------------------------------------
def makeCanonical_non_recursive(self, rename_user_defined = True):
"Converts the term to a unique canonical form using a non-recursive algorithm."
# If the tensor is already in canonical form, do nothing
if self.isInCanonicalForm:
return
# If the term is not normal ordered, raise an error
if not self.isNormalOrdered():
raise RuntimeError("A term must have normal ordered operators to be converted to canonical form.")
# Sort the constants
self.constants.sort()
# If there are no tensors in the term then skip the tensor sorting.
if len(self.tensors) == 0:
self.isInCanonicalForm = True
return
# Sort the freely commuting tensors by number and name
fcList = []
ncList = []
for t in self.tensors:
if t.freelyCommutes:
fcList.append(t)
else:
ncList.append(t)
fcList.sort(lambda x,y: cmp(x.name,y.name))
nameGroups = []
uniqueNames = []
for t in fcList:
if t.name in uniqueNames:
nameGroups[-1].append(t)
else:
uniqueNames.append(t.name)
nameGroups.append([t])
nameGroups.sort(lambda x,y: cmp(len(x),len(y)))
for t in ncList:
nameGroups.append([t])
del(uniqueNames,fcList,ncList,t)
# Generate an alphabet for use in renaming indices
# This is done to avoid renaming with an index name already in use.
# Should try using numbers, i.e. '1', '2', '3', etc.
alphabet = self.generateAlphabet()
# Determine the best ordering and index mapping
best_tensor_list = None
best_factor = None
bestMap = None
bestScore = [-1]
nTopScore = 0
# job format: (map, gCount, tCount, aCount, gPerms)
jobStack = [({},0,0,0,[])]
while jobStack:
# get the next job
map,gCount,tCount,aCount,gPerms = jobStack.pop()
# If there are no name groups remaining, compute the score
if gCount == len(nameGroups):
# Compute a new tensor list in which any dummy indices are given their
# new names and all indices are sorted.
# Also compute a list of these ordered indices.
# Also compute the multiplicitive factor generated by sorting the indices.
tenList = []
indexList = []
factor = 1
for i in range(len(nameGroups)):
for j in range(len(nameGroups[i])):
tenList.append(nameGroups[i][gPerms[i][j]].copy())
for k in range(len(tenList[-1].indices)):
if tenList[-1].indices[k].isSummed:
tenList[-1].indices[k] = map[tenList[-1].indices[k].tup()]
factor *= tenList[-1].sortIndeces()
for ind in tenList[-1].indices:
indexList.append(ind)
# Compute a score based on how alphabetical the indices are
score = []
for i in range(len(indexList)-1):
score.append(0)
for j in range(i+1,len(indexList)):
if indexList[i] < indexList[j]:
score[-1] += 1
# If the current score is the best score, save the result
if score > bestScore:
nTopScore = 1
bestScore = score
bestMap = map
best_factor = factor
best_tensor_list = tenList
# If the current score ties for the best, count the number of best scores
elif score == bestScore:
nTopScore += 1
# If only cre/des operators remain, sort them and compute the score
elif min([ (len(i) == 1 and (isinstance(i[0], creOp) or isinstance(i[0], desOp))) for i in nameGroups[gCount:] ]):
# Compute a new tensor list in which any dummy indices are given their
# new names and all indices are sorted.
# Also compute a list of these ordered indices.
# Also compute the multiplicitive factor generated by sorting the indices.
tenList = []
indexList = []
factor = 1
for i in range(gCount):
for j in range(len(nameGroups[i])):
tenList.append(nameGroups[i][gPerms[i][j]].copy())
for k in range(len(tenList[-1].indices)):
if tenList[-1].indices[k].isSummed:
tenList[-1].indices[k] = map[tenList[-1].indices[k].tup()]
factor *= tenList[-1].sortIndeces()
for ind in tenList[-1].indices:
indexList.append(ind)
# Apply the input mapping to the creation/destruction operators
# Create and apply a new mapping for any new dummy indices
opList = [nameGroups[i][0].copy() for i in range(gCount,len(nameGroups))]
nNewMaps = 0
for op in opList:
if op.indices[0].tup() in map:
op.indices[0] = map[op.indices[0].tup()]
elif op.indices[0].isSummed:
map[op.indices[0].tup()] = index(alphabet[aCount+nNewMaps], op.indices[0].indType, op.indices[0].isSummed, op.indices[0].userDefined)
nNewMaps += 1
op.indices[0] = map[op.indices[0].tup()]
# Sort the operators and apply the resulting sign
(s,opList) = sortOps(opList)
factor *= s
# Add the operators' indices to the ordered list of indices.
# Also add the sorted operators to the new tensor list.
for op in opList:
indexList.append(op.indices[0])
tenList.append(op)
# Compute a score based on how alphabetical the indices are
score = []
for i in range(len(indexList)-1):
score.append(0)
for j in range(i+1,len(indexList)):
if indexList[i] < indexList[j]:
score[-1] += 1
# If the current score is the best score, save the result
if score > bestScore:
nTopScore = 1
bestScore = score
bestMap = map
best_factor = factor
best_tensor_list = tenList
# If the current score ties for the best, count the number of best scores
elif score == bestScore:
nTopScore += 1
# If only a sfExOp remains, sort its indices and compute the score
elif (gCount == len(nameGroups)-1) and (len(nameGroups[gCount]) == 1) and isinstance(nameGroups[gCount][0], sfExOp):
# Compute a new tensor list in which any dummy indices are given their
# new names and all indices are sorted.
# Also compute a list of these ordered indices.
# Also compute the multiplicitive factor generated by sorting the indices.
tenList = []
indexList = []
factor = 1
for i in range(gCount):
for j in range(len(nameGroups[i])):
tenList.append(nameGroups[i][gPerms[i][j]].copy())
for k in range(len(tenList[-1].indices)):
if tenList[-1].indices[k].isSummed:
tenList[-1].indices[k] = map[tenList[-1].indices[k].tup()]
factor *= tenList[-1].sortIndeces()
for ind in tenList[-1].indices:
indexList.append(ind)
# Apply the input mapping to the sfExOp
# Create and apply a new mapping for any new dummy indices
t = nameGroups[gCount][0].copy()
nNewMaps = 0
for i in range(len(t.indices)):
if t.indices[i].tup() in map:
t.indices[i] = map[t.indices[i].tup()]
elif t.indices[i].isSummed:
map[t.indices[i].tup()] = index(alphabet[aCount+nNewMaps], t.indices[i].indType, t.indices[i].isSummed, t.indices[i].userDefined)
nNewMaps += 1
t.indices[i] = map[t.indices[i].tup()]
# Sort the indices of the sfExOp (go go gadget bubble sort!)
i = 0
while i < t.order-1:
if t.indices[i] > t.indices[i+1]:
temp = t.indices[i+1]
t.indices[i+1] = t.indices[i]
t.indices[i] = temp
temp = t.indices[i+t.order+1]
t.indices[i+t.order+1] = t.indices[i+t.order]
t.indices[i+t.order] = temp
i = 0
else:
i += 1
# Add the sfExOp to the new tensor list
tenList.append(t)
# Add the sfExOp's indices to the ordered index list
for i in t.indices:
indexList.append(i)
# Compute a score based on how alphabetical the indices are
score = []
for i in range(len(indexList)-1):
score.append(0)
for j in range(i+1,len(indexList)):
if str(indexList[i].name) < str(indexList[j].name):
score[-1] += 1
# If the current score is the best score, save the result
if score > bestScore:
nTopScore = 1
bestScore = score
bestMap = map
best_factor = factor
best_tensor_list = tenList
# If the current score ties for the best, count the number of best scores
elif score == bestScore:
nTopScore += 1
# If starting a new name group, sort the group's names based on the input mapping
# and schedule a new job for each permutation of the tensors with no index assignments
elif len(gPerms) <= gCount:
withMapped = []
withoutMapped = []
for i in range(len(nameGroups[gCount])):
leastMapped = False
for ind in nameGroups[gCount][i].indices:
if (ind.tup() in map) and ((leastMapped is False) or (map[ind.tup()] < leastMapped)):
leastMapped = map[ind.tup()]
if leastMapped is False:
withoutMapped.append(i)
else:
withMapped.append((leastMapped,i))
withMapped.sort(lambda x,y: cmp(x[0],y[0]))
withMapped = [i[1] for i in withMapped]
if len(withoutMapped) <= 1:
jobStack.append((map,gCount,tCount,aCount,gPerms + [withMapped + withoutMapped]))
else:
for perm in makePermutations(len(withoutMapped)):
new_gPerm = withMapped + [withoutMapped[i] for i in perm]
jobStack.append((map,gCount,tCount,aCount,gPerms + [new_gPerm]))
del(new_gPerm,perm)
del(withMapped,withoutMapped,leastMapped)
# If continuing an existing group, schedule a new job for each equivelent ordering
# of the current tensor's indices
else:
# Give the current tensor a convenient name
t = nameGroups[gCount][gPerms[gCount][tCount]]
# Get the tensor's symmetry permutations
(symPerms,factors) = t.symPermutes()
# Compute gCount and tCount for the next job
next_gCount = gCount
next_tCount = tCount + 1
if next_tCount == len(nameGroups[gCount]):
next_gCount += 1
next_tCount = 0
# For each of the tensor's symmetry-equivelent index orderings, create mappings for any
# un-mapped dummy indices and schedule a new job
for perm in symPerms:
nNewMaps = 0
newMap = {}
newMap.update(map)
for ind in [t.indices[perm[i]] for i in range(len(t.indices))]:
if ind.isSummed and ind.tup() not in newMap:
newMap[ind.tup()] = index(alphabet[aCount+nNewMaps], ind.indType, ind.isSummed, ind.userDefined)
nNewMaps += 1
jobStack.append((newMap,next_gCount,next_tCount,aCount+nNewMaps,gPerms))
# # Check to see that only one candidate achieved the top score
# if nTopScore > 1:
# #raise RuntimeError("%i candidates tied for the top score." %nTopScore)
# print "WARNING: %i candidates tied for the top score." %nTopScore
# Set the tensor list as the list with the 'best' index naming and ordering
if best_tensor_list is not None:
self.tensors = best_tensor_list
# Apply the factor produced from the canonical ordering
if best_factor is not None:
self.scale(best_factor)
if bestMap is None:
bestMap = map
# Create an index mapping that converts to a canonical alphabet, i.e. a-z
alphabet = list('abcdefghijklmnopqrstuvwxyz')
filtered_alphabet = []
for character in alphabet:
if character not in options.user_defined_indices:
filtered_alphabet.append(character)
alphabet = filtered_alphabet
if len(alphabet) < len(bestMap):
raise RuntimeError("Alphabet smaller than number of indices, no more names left!")
canonMap = {}
while bestMap.keys():
minVal = min(bestMap.values())
for key in bestMap.keys():
if bestMap[key] == minVal:
canonMap[bestMap[key].tup()] = bestMap[key].copy()
canonMap[bestMap[key].tup()].name = alphabet.pop(0)
del bestMap[key]
break
# Rename the indices using the canonical mapping
for t in self.tensors:
for i in range(len(t.indices)):
if t.indices[i].tup() in canonMap.keys():
t.indices[i] = canonMap[t.indices[i].tup()].copy()
if rename_user_defined and t.indices[i].userDefined:
t.indices[i].rename()
# Turn on the canonical form flag to avoid calling this function again unnecessarily
self.isInCanonicalForm = True
#------------------------------------------------------------------------------------------------
def getCandidateTensorLists(self):
"""
Create all tensor lists in which the term's tensors are sorted by name.
Multiple lists occur when there are multiple freely commuting tensors with the same name.
"""
# Separate the tensors into two lists: freely commuting and non-commuting
fcList = []
ncList = []
for t in self.tensors:
if t.freelyCommutes:
fcList.append(t.copy())
else:
ncList.append(t.copy())
if len(fcList) > 0:
# Sort the freely commuting tensors by name
fcList.sort(lambda x,y: cmp(x.name,y.name))
# For the freely commuting tensors, compile a list of unique tensor names and the number of times they occur
uniqueNames = []
nameCounts = []
for ten in fcList:
if ten.name in uniqueNames:
nameCounts[uniqueNames.index(ten.name)] += 1
else:
uniqueNames.append(ten.name)
nameCounts.append(1)
# For each unique name, generate ordering permutations
permutes = []
for i in nameCounts:
permutes.append(makePermutations(i))
# Combine the name perturbations above into all possible lists in which the freely commuting tensors
# are ordered by name
tensorsByName = []
total = 0
for i in nameCounts:
tensorsByName.append(fcList[total:total+i])
total += i
candidateLists = []
for perm in permutes[0]:
candidateLists.append([])
for p in perm:
candidateLists[-1].append(tensorsByName[0][p].copy())
for i in range(1,len(uniqueNames)):
nOldVariants = len(candidateLists)
for perm in permutes[i]:
for j in range(nOldVariants):
candidateLists.append([])
candidateLists[-1].extend(candidateLists[j])
for p in perm:
candidateLists[-1].append(tensorsByName[i][p].copy())
del(candidateLists[0:nOldVariants])
else:
candidateLists = [[]]
# Append the non-commuting tensors to each candidate list
for l in candidateLists:
for t in ncList:
l.append(t.copy())
# Return the list of candidate tensor orders
return candidateLists
#------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
def combineTerms(termList, maxThreads = 1):
"Combines any like terms in termList"
if options.verbose:
print('')
print('Combining like terms:')
print('Converting %i terms to canonical form...' %(len(termList)))
startTime = time.time()
# Put the terms in termList into their canonical (unique) forms
if maxThreads > 1:
# Initialize counters and locks
termCount = [0]
printCount = [0]
tLock = threading.Lock()
pLock = threading.Lock()
# Define function to use in threads
def threadFunc(nTerms):
batchSize = 100
# Get first batch
tLock.acquire()
i = termCount[0]
termCount[0] += batchSize
tLock.release()
k = i + batchSize
while i < nTerms:
termList[i].makeCanonical(rename_user_defined = False)
# pLock.acquire()
# print '%6i %s' %(printCount[0],str(termList[i]))
# printCount[0] += 1
# pLock.release()
i += 1
if i == k:
# Get next batch
tLock.acquire()
i = termCount[0]
termCount[0] += batchSize
tLock.release()
k = i + batchSize
# Start threads
threads = []
nTerms = len(termList)
for i in range(maxThreads):
threads.append(threading.Thread(target=threadFunc, args=(nTerms,)))
threads[-1].start()
# Wait for the threads to finish
for thread in threads:
thread.join()
else:
# Convert the terms to canonical form in the main thread
for i in range(len(termList)):
if options.verbose:
print '%6i %s' %(i,str(termList[i]))
termList[i].makeCanonical(rename_user_defined = False)
# Sort the terms
termList.sort()
# Combine any terms with the same canonical form
i = 0
while i < len(termList)-1:
if termList[i].sameForm(termList[i+1]):
termList[i+1] += termList[i]
del(termList[i])
else:
i += 1
# Rename user defined dummy indices
for _term in termList:
for _tensor in _term.tensors:
for _ind in range(len(_tensor.indices)):
_tensor.indices[_ind].rename()
# i = 0
# while i < len(termList)-1:
# j = i + 1
# while j < len(termList):
# if termList[j].sameForm(termList[i]):
# termList[i] += termList[j]
# del(termList[j# else:
# else:
# j += 1
# i += 1
# Remove terms with coefficients of zero
termChop(termList)
if options.verbose:
print("Finished combining terms in %.3f seconds" %(time.time() - startTime))
print("")
# Sort the terms
termList.sort()
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
def multiplyTerms(t1,t2):
if (not isinstance(t1,term)) or (not isinstance(t2,term)):
raise TypeError("t1 and t2 must be of type term")
numConst = t1.numConstant * t2.numConstant
constList = []
constList.extend(t1.constants)
constList.extend(t2.constants)
tensorList = []
tensorList.extend(t1.tensors)
tensorList.extend(t2.tensors)
return term(numConst,constList,tensorList)
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
def termChop(termList, tolerance = 1e-6):
"Removes any terms with zero constant factors from termList."
TypeErrorMessage = "termList must be a list of terms"
if type(termList) != type([]):
raise TypeError(TypeErrorMessage)
i = 0
while i < len(termList):
if not isinstance(termList[i],term):
raise TypeError(TypeErrorMessage)
if abs(termList[i].numConstant) < tolerance:
del(termList[i])
else:
i += 1
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
def getcim(tenList, alphabet, tenCount = 0, alphaCount = 0, inputMaps = {}):
"""
Determines the index mapping necessary to canonicalize the indices in tenList.
Assumes any creation/destruction operators are in normal order.
"""
# Determine what types of tensors are left to process
no_tensors_left = ( tenCount == len(tenList) )
only_sfExOp_left = ( (tenCount == len(tenList)-1) and isinstance(tenList[-1], sfExOp) )
only_creDes_left = ( tenCount < len(tenList) )
for t in tenList[tenCount:]:
if ( not isinstance(t, creOp) ) and ( not isinstance(t, desOp) ):
only_creDes_left = False
break
if no_tensors_left or only_creDes_left or only_sfExOp_left:
# Copy the input mapping into a new map that can be added to
map = {}
map.update(inputMaps)
# For the preceeding tensors, create an ordered list of indeces
# and a list of tensors with the canonical index sorting
indexList = []
newTensorList = []
sign = 1
for t in tenList[:tenCount]:
tcopy = t.copy()
for j in range(len(tcopy.indices)):
if tcopy.indices[j].tup() in map.keys():
tcopy.indices[j] = map[tcopy.indices[j].tup()]
# Keep track of the sign produced by sorting the tensor's indices
sign *= tcopy.sortIndeces()
newTensorList.append(tcopy)
for ind in tcopy.indices:
indexList.append(ind)
if only_creDes_left:
# Apply the input mapping to the creation/destruction operators
# Create and apply a new mapping for any new dummy indices
opList = []