-
Notifications
You must be signed in to change notification settings - Fork 3
/
searcher.py
1758 lines (1366 loc) · 60.9 KB
/
searcher.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
#!/usr/bin/env python
from sys import stderr, maxint, exit
import logging
from copy import deepcopy
import pickle
from os import path, mkdir, chdir, getcwd
from numpy import array, asarray, ceil, abs, sqrt, dot
from numpy import empty, zeros, linspace, arange
from numpy import argmax
from path import Path, Arc, scatter1
from pts.memoize import Elemental_memoize
import pts.common as common
import pts
import pts.metric as mt
from history import History
previous = []
def test_previous(state_vec):
"""
Mainly for testing. Keeps an additional record of calcs that have
previously been performed.
"""
prev = []
for v in state_vec:
matches = sum([(v == p).all() for p in previous])
if matches == 0:
prev.append(False)
previous.append(v)
elif matches == 1:
prev.append(True)
else:
assert False
return prev
lg = logging.getLogger("pts.searcher")
lg.setLevel(logging.INFO)
if not globals().has_key("lg"):
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
lg.addHandler(sh)
def _functionId(nFramesUp):
""" Create a string naming the function n frames up on the stack.
"""
import sys
co = sys._getframe(nFramesUp+1).f_code
return "%s (%s @ %d)" % (co.co_name, co.co_filename, co.co_firstlineno)
def masked_assign(mask, dst, src):
"""Assigns y to x if mask allows it.
There are three different cases for each element possible:
m = 0: keep the old value of dst
m = 1: use new value of src
m = 2: only represented in src (not in dst)
thus of course not keep it and
make sure it is not counted in dst
>>> m = [1, 1]
>>> orig = arange(4).reshape(2,-1)
>>> x = orig.copy()
>>> y = array([5,4,3,2]).reshape(2,-1)
>>> x = masked_assign(m, x, y)
>>> (x == y).all()
True
>>> m = [0, 0]
>>> x = orig.copy()
>>> (x != masked_assign(m, x, y)).all()
False
"""
dstc = src.copy()
assert len(mask) == len(dstc)
j = 0
for i, m in enumerate(mask):
if mask[i] == 1:
j = j + 1
elif mask[i] == 0:
dstc[i] = dst[j]
j = j + 1
return dstc
def freeze_ends(bc):
"""
Generates a mask for masked_assign function which fixes
the two termination beads (with 0 ) and updates the rest
of them (1)
"""
return [0] + [1 for i in range(bc-2)] + [0]
def new_bead_positions( weights, ci_len, ci_pos, ci_num):
"""
gives a new abcissa, calculated from the original and the new values as followes:
the abscissa from ci_num (climbing image) will be taken. The other
abscissa are thus distributed on the remaining space, that their relation to
the climbing image is kept
>>> xo = [0., 0.2, 0.25, 0.4, 0.5, 0.75, 1.]
>>> xn = [0., 0.3, 0.25, 0.45, 0.4, 0.12, 1.]
>>> out = new_bead_positions(xo, xn[3], xn[3], 3)
>>> print " %4.3f"* 7 %( tuple(out))
0.000 0.225 0.281 0.450 0.542 0.771 1.000
The number at 1 should be still have as big as 3:
>>> 0.5 * out[3] - out[1] < 1e-7
True
>>> out = new_bead_positions(xo, xn[4], xn[4], 4)
>>> print " %4.3f"* 7 %( tuple(out))
0.000 0.160 0.200 0.320 0.400 0.700 1.000
Image 2 should be halve as big:
>>> 0.5 * out[4] - out[2] < 1e-7
True
Image 5 should be exactly in the middle between image 4 and
1.
>>> 1. - out[5] - (out[5] - out[4]) < 1e-7
True
Squeeze everything into small area:
>>> out = new_bead_positions(xo, xn[5], xn[5], 5)
>>> print " %4.3f"* 7 %( tuple(out))
0.000 0.032 0.040 0.064 0.080 0.120 1.000
If the postion of it is unchanged, so are all:
>>> out = new_bead_positions(xo, xn[2], xn[2], 2)
>>> print " %4.3f"* 7 %( tuple(out))
0.000 0.200 0.250 0.400 0.500 0.750 1.000
"""
# Function is somewhat specialized
assert weights[0] == 0
assert weights[-1] == 1.
# distribute the weights anew
chang_weights = asarray(weights).copy()
# This is the positions where CI should be if it was not CI, here it
# is used as reference to get the scalings relative to it
ab_ci_ref = weights[ci_num]
end = 1.
def new_absc(old):
if old < ab_ci_ref:
# Scale from the left
# ( [0, ab_ci_ref] -> [0, ci_len])
return old * ci_len / ab_ci_ref
else:
#Start from the other end:
# ( [ci_ref, 1.] -> [ci_len, 1.])
return end - (end - old) * (end - ci_len) / (end - ab_ci_ref)
# Do not change terminal beads, generate_normd_positions would complain
for i in range(1, len(weights) -1):
if i == ci_num:
# This is the climbing image, it will stay fixed
chang_weights[i] = ci_pos
continue
chang_weights[i] = new_absc(weights[i])
return chang_weights
def new_abscissa(state_vec, metric):
"""
Generates a new (normalized) abscissa, using the metric
"metric". The abscissa will be according to the sum of pythagorean
distances in metric for all the beads before, normed to 1.
"""
separations = common.pythag_seps(state_vec, metric.norm_up)
new_abscissa = common.cumm_sum(separations)
new_abscissa /= new_abscissa[-1]
return new_abscissa
class ReactionPathway(object):
"""Abstract object for chain-of-state reaction pathway."""
dimension = -1
eg_calls = 0
bead_eg_calls = 0
# incremented by callback function
callbacks = 0
# no times path has been regenerated
respaces = 0
string = False
def __init__(self,
reagents,
beads_count,
pes,
parallel,
result_storage,
reporting=None,
convergence_beads=3,
steps_cumm=3,
pmap=map,
workhere = 1,
freeze_beads=False,
output_level = 3,
output_path = ".",
climb_image = False,
start_climb = 5,
conv_mode='gradstep'):
"""
convergence_beads:
number of highest beads to consider when testing convergence
steps_cumm:
number of previous steps to consider when testing convergence
freeze_beads:
freeze some beads if they are not in the highest 3 or subject to low forces.
"""
self.parallel = parallel
self.pes = pes
self.beads_count = beads_count
self.prev_beads_count = beads_count
self.output_path = output_path
self.convergence_beads = convergence_beads
self.steps_cumm = steps_cumm
self.freeze_beads = freeze_beads
self.opt_iter = 0
self.__dimension = len(reagents[0])
#TODO: check that all reagents are same length
self.initialise()
self.history = History()
# mask of gradients to update at each position
self.bead_update_mask = freeze_ends(self.beads_count)
self._maxit = maxint
if reporting:
assert type(reporting) == file
self.reporting = reporting
legal_conv_modes = ('gradstep', 'energy', 'gradstep_new')
assert conv_mode in legal_conv_modes
self.conv_mode = conv_mode
# This can be set externally to a file object to allow recording of picled archive data
self.arc_record = None
self.output_level = output_level
self.allvals = Elemental_memoize(self.pes, pmap=pmap, cache = result_storage, workhere = workhere, format = "bead%02d")
self.climb_image = climb_image
self.start_climb = start_climb
self.ci_num = None
def initialise(self):
beads_count = self.beads_count
shape = (beads_count, self.dimension)
# forces perpendicular to pathway
self.perp_bead_forces = zeros(shape)
self.para_bead_forces = zeros(beads_count)
# energies / gradients of beads, excluding any spring forces / projections
self.bead_pes_energies = zeros(beads_count)
self.bead_pes_gradients = zeros(shape)
self.prev_state = None
self.prev_perp_forces = None
self.prev_para_forces = None
self.prev_energies = None
self._step = zeros(shape)
def lengths_disparate(self, metric):
return False
def signal_callback(self):
self.callbacks += 1
# This functionality below was used with generic 3rd party optimisers,
# i.e. it would force the optimiser to exit, so that a respace could
# be done.
if self.lengths_disparate(mt.metric):
raise pts.MustRegenerate
def test_convergence(self, etol, ftol, xtol):
self.opt_iter = self.opt_iter + 1
t_clim = self.climb_image
if self.growing and self.climb_image:
# If used together with string let it work only on complete strings
t_clim = self.grown()
if self.conv_mode == 'gradstep':
conv = self.test_convergence_GS(ftol, xtol)
if self.conv_mode == 'gradstep_new':
conv = self.test_convergence_GS_new(ftol, xtol)
if self.conv_mode == 'energy':
conv = self.test_convergence_E(etol)
# conv = True means:
# * Convergence with current convergence test has been finished,
# * OR substring is converged enough for growing.
# If climbing image has not yet started to climb, convergence was tested
# without it, thus CI is not yet correctly finshed. Then force a growing
# and test again. If CI does not find a valid CI-image abort in this case.
# Test only the rougher convergence criteria in preoptimization state of
# CI method.
if t_clim:
# If climbing image is used on NEB or a completely grown string
# try to find the image, which should actually climb
if ((self.opt_iter >= self.start_climb) or conv) \
and self.ci_num == None:
clim = self.try_set_ci_num()
if clim:
print "Turned image", self.ci_num, " into climbing image"
assert not self.ci_num == None
# convergence check will raise this unwanted again:
self.opt_iter = self.opt_iter - 1
# eventually the new convergence criteria are already met.
conv = self.test_convergence( etol, ftol, xtol)
else:
if conv:
print "ATTENTION: no climbing image found on current converged path!"
print " thus only did calculation without CI "
print >> stderr, "ATTENTION: calculation converged but CI was not applied"
if conv:
raise pts.Converged
def test_convergence_E(self, etol):
if self.eg_calls < 2:
# because forces are always zero at zeroth iteration
return False
bc_history = self.history.bead_count(2)
if bc_history[1] != bc_history[0]:
lg.info("Testing Convergence: string just grown, so skipping.")
return False
es = array(self.history.e(2)) / (self.beads_count - 2)
# TODO: should remove abs(), only converged if energy went down
# Or maybe should look at difference between lowest energies so far.
diff = abs(es[0] - es[1])
lg.info("Testing Convergence of %f to %f eV / moving bead / step." % (diff, etol))
if diff < etol:
return True
return False
def test_convergence_GS(self, f_tol, x_tol, always_tight=False):
"""
Raises Converged if converged, applying weaker convergence
criteria if growing string is not fully grown.
During growth: rmsf < 10 * f_tol
When grown: rmsf < f_tol OR
max_step < x_tol AND rmsf < 5*f_tol
where max_step is max step in optimisation coordinates
taken by H highest beads and C cummulative beads,
where H is self.convergence_beads
and C is self.steps_cumm
both set by __init__
At time of writing (19/02/2010): convergence is tested
in callback function which is called after every
iteration, not including backtracks. The state is
recorded at every
"""
rmsf = self.f_conv()[0]
if self.eg_calls == 0:
# because forces are always zero at zeroth iteration
return False
elif not always_tight and ((self.growing and not self.grown()) \
or (self.climb_image and self.ci_num == None)):
lg.info("Testing During-Growth Convergence to %f: %f" % (f_tol*5, rmsf))
if rmsf < f_tol*5:
return True
else:
max_step = self.history.step(self.convergence_beads, self.steps_cumm)
max_step = abs(max_step).max()
lg.info("Testing Non-Growing Convergence to f: %f / %f, x: %f / %f" % (rmsf, f_tol, max_step, x_tol))
if rmsf < f_tol or (self.eg_calls > self.steps_cumm and max_step < x_tol and rmsf < 5*f_tol):
return True
return False
def test_convergence_GS_new(self, f_tol, x_tol):
"""
Raises Converged if converged, applying weaker convergence
criteria if growing string is not fully grown.
During growth: rmsf < 5 * f_tol
When grown: rmsf < f_tol OR
max_step < x_tol AND rmsf < 5*f_tol
where max_step is max step in optimisation coordinates
taken by H highest beads and C cummulative beads,
where H is self.convergence_beads
and C is self.steps_cumm
both set by __init__
At time of writing (19/02/2010): convergence is tested
in callback function which is called after every
iteration, not including backtracks. The state is
recorded at every
"""
f = self.f_conv()[1]
max_step = self.history.step(self.convergence_beads, self.steps_cumm)
max_step = abs(max_step).max()
if self.eg_calls == 0:
# because forces are always zero at zeroth iteration
return False
elif self.growing and not self.grown() \
or (self.climb_image and self.ci_num == None):
lg.info("Testing During-Growth Convergence to f: %f / %f (max), x: %f / %f" % (f, 5*f_tol, max_step, 2*x_tol))
if f < f_tol*5 or (self.eg_calls > self.steps_cumm and max_step < 2*x_tol):
return True
else:
lg.info("Testing Non-Growing Convergence to f: %f / %f (max), x: %f / %f" % (f, f_tol, max_step, x_tol))
if f < f_tol or (self.eg_calls > self.steps_cumm and max_step < x_tol):
return True
return False
def try_set_ci_num(self):
"""
The bead with the maximal energy will become the climbing image
But if it would be one of the termination beads this does not make
much sense, then tell wrong and maybe retry another time
"""
assert self.climb_image
i = argmax(self.bead_pes_energies)
if i > 0 and i < len(self.bead_pes_energies) - 1:
self.ci_num = i
return True
return False
@property
def rmsf_perp(self):
"""RMS forces, not including those of end beads."""
return common.rms(self.perp_bead_forces[1:-1]), [common.rms(f) for f in self.perp_bead_forces]
def f_conv(self):
""" forces for convergence test, not including those of end beads. first RMS forces, second maxforces"""
f = self.perp_bead_forces
if self.climb_image and not self.ci_num == None:
f[self.ci_num] = -self.bead_pes_gradients[self.ci_num]
l = []
for i, mask in enumerate(self.bead_update_mask):
if mask > 0:
l.append(i)
assert len(l) > 0
return common.rms(f[l]), abs(f[l]).max()
def pathpos(self):
return None
@property
def maxf_perp(self):
"""RMS forces, not including those of end beads."""
return abs(self.perp_bead_forces[1:-1]).max()
@property
def rmsf_para(self):
"""RMS forces, not including those of end beads."""
return common.rms(self.para_bead_forces), [f for f in self.para_bead_forces]
@property
def step(self):
"""RMS forces, not including those of end beads."""
return common.rms(self._step[1:-1]), array([common.rms(s) for s in self._step]), abs(self._step)
@property
def energies(self):
"""RMS forces, not including those of end beads."""
return self.bead_pes_energies.sum(), self.bead_pes_energies
@property
def state_summary(self):
s = common.vec_summarise(self.state_vec)
s_beads = [common.vec_summarise(b) for b in self.state_vec]
return s, s_beads
def __str__(self):
e_total, e_beads = self.energies
rmsf_perp_total, rmsf_perp_beads = self.rmsf_perp
rmsf_para_total, rmsf_para_beads = self.rmsf_para
maxf_beads = [abs(f).max() for f in self.bead_pes_gradients]
path_pos = self.pathpos()
if path_pos == None:
# set up dummy spline abscissa for non-spline methods
path_pos = [0.0 for i in range(len(self.bead_pes_gradients))]
eg_calls = self.eg_calls
step_total, step_beads, step_raw = self.step
angles = self.angles
seps_pythag = self.update_bead_separations()
total_len_pythag = seps_pythag.sum()
total_len_spline = 0
state_sum, beads_sum = self.state_summary
e_reactant, e_product = e_beads[0], e_beads[-1]
e_max = max(e_beads)
barrier_fwd = e_max - e_reactant
barrier_rev = e_max - e_product
format = lambda f, l: ' | '.join([f % i for i in l])
all_coordinates = ("%-24s : %s\n" % (" Coordinate %3d " % 1 , format('%10.4f',(self.state_vec[:,0]))))
(coord_dim1, coord_dim2) = self.state_vec.shape
for i in range(1,coord_dim2 ):
all_coordinates += ("%-24s : %s\n" % (" Coordinate %3d " % (i+1) , format('%10.4f',self.state_vec[:,i])))
ts_ix = 0
# max cummulative step over steps_cumm iterations
step_max_bead_cumm = self.history.step(self.convergence_beads, self.steps_cumm).max()
step_ts_estim_cumm = self.history.step(ts_ix, self.steps_cumm).max()
if self.output_level > 2:
arc = {'bc': self.beads_count,
'N': eg_calls,
'resp': self.respaces,
'cb': self.callbacks,
'rmsf': rmsf_perp_total,
'maxf': self.maxf_perp,
'e': e_total,
'maxe': e_max,
's': abs(step_raw).max(),
's_ts_cumm': step_ts_estim_cumm,
's_max_cumm': step_max_bead_cumm,
'ixhigh': self.bead_pes_energies.argmax()}
bead_es = bead_gs = (self.beads_count - 2) * eg_calls + 2
arc['bead_es'] = bead_es
arc['bead_gs'] = bead_gs
f = '%10.3e'
s = [ "\n----------------------------------------------------------",
"Chain of States Summary for %d gradient/energy calculations" % eg_calls,
"VALUES FOR WHOLE STRING",
"%-24s : %10.4f" % ("Total Energy" , e_total) ,
"%-24s : %10.4f | %10.4f" % ("RMS Forces (perp|para)", rmsf_perp_total, rmsf_para_total),
"%-24s : %10.4f | %10.4f" % ("Step Size (RMS|MAX)", step_total, step_raw.max()),
"%-24s : %10.4f" % ("Cumulative steps (max bead)", step_max_bead_cumm),
"%-24s : %10.4f" % ("Cumulative steps (ts estim)", step_ts_estim_cumm),
"%-24s : %8s %10.4f" % ("Bead Sep ratio (Pythagorean)", "|", seps_pythag.max() / seps_pythag.min()),
"VALUES FOR SINGLE BEADS",
"%-24s : %s" % ("Bead Energies",format('%10.4f', e_beads)) ,
"%-24s : %s" % ("RMS Perp Forces", format(f, rmsf_perp_beads)),
"%-24s : %s" % ("Para Forces", format(f, rmsf_para_beads)),
"%-24s : %s" % ("MAX Forces", format(f, maxf_beads)),
"%-24s : %s" % ("RMS Step Size", format(f, step_beads)),
"%-24s : %12s %s |" % ("Bead Angles","|" , format('%10.0f', angles)),
"%-24s : %6s %s" % ("Bead Separations (Pythagorean)", "|", format(f, seps_pythag)),
"%-24s : %s" % ("Bead Path Position", format(f, path_pos)),
"%-24s :" % ("Raw State Vector"),
all_coordinates,
"GENERAL STATS",
"%-24s : %10d" % ("Number of iteration", self.opt_iter),
"%-24s : %10d" % ("Callbacks", self.callbacks),
"%-24s : %10d" % ("Number of respaces", self.respaces),
"%-24s : %10d" % ("Beads Count", self.beads_count)]
if self.climb_image:
if self.ci_num == None:
s += ["%-24s : %10s" % ("Climbing image", "None")]
else:
s += ["%-24s : %10d" % ("Climbing image", self.ci_num)]
s += ["%-24s : %.4f %.4f" % ("Total Length (Pythag|Spline)", total_len_pythag, total_len_spline),
"%-24s : %10s" % ("State Summary (total)", state_sum),
"%-24s : %s" % ("State Summary (beads)", format('%10s', beads_sum)),
"%-24s : %10.4f | %10.4f " % ("Barriers (Fwd|Rev)", barrier_fwd, barrier_rev)]
if self.output_level > 2:
s += ["Archive %s" % arc]
if self.arc_record and self.output_level > 2:
assert type(self.arc_record) == file, type(self.arc_record)
sv = self.state_vec.reshape(self.beads_count,-1)
arc['state_vec'] = sv
arc['energies'] = self.bead_pes_energies.reshape(-1)
arc['gradients'] = self.bead_pes_gradients.reshape(self.beads_count, -1)
arc['pathps'] = self.pathpos()
pickle.dump(arc, self.arc_record, protocol=2)
self.arc_record.flush()
return '\n'.join(s)
def post_obj_func(self, grad):
if self.reporting:
if grad:
self.reporting.write("***Gradient call (E was %f)***\n" % self.bead_pes_energies.sum())
else:
self.reporting.write("***Energy call (E was %f)***\n" % self.bead_pes_energies.sum())
if self.prev_state == None:
# must be first iteration
assert self.eg_calls == 0
self.prev_state = self.state_vec.copy()
# skip reporting if the state hasn't changed
elif (self.state_vec == self.prev_state).all() and self.beads_count == self.prev_beads_count:
#FIXME: this is needed for the growing methods. Here the first iteration after growing
# will set prev_state = state_vec
return
self.eg_calls += 1
self._step = self.state_vec - self.prev_state
self.prev_state = self.state_vec.copy()
self.record()
if self.reporting:
s = [str(self),
common.line()]
s = '\n'.join(s) + '\n'
self.reporting.write(s)
self.reporting.flush()
else:
assert self.reporting == None
self.prev_beads_count = self.beads_count
def grow_string(self):
return False
@property
def angles(self):
"""Returns an array of angles between beed groups of 3 beads."""
angles = []
for i in range(len(self.state_vec))[2:]:
t0 = self.state_vec[i-1] - self.state_vec[i-2]
t1 = self.state_vec[i] - self.state_vec[i-1]
angles.append(common.vector_angle(t1, t0))
return array(angles)
def update_bead_separations(self):
"""Updates internal vector of distances between beads."""
# FIXME: why copy?
v = self.state_vec.copy()
# FIXME: using default cartesian norm here:
seps = common.pythag_seps(v)
self.bead_separations = seps
return seps
@property
def dimension(self):
return self.__dimension
def get_state_as_array(self):
"""Returns copy of state as flattened array."""
#Do I really need this as well as the one below?
return deepcopy(self.state_vec).flatten()
def get_bead_coords(self):
"""Return copy of state_vec as 2D array."""
tmp = deepcopy(self.state_vec)
tmp.shape = (self.beads_count, self.dimension)
return tmp
def get_maxit(self):
return self._maxit
def set_maxit(self, new):
assert new >= 0
self._maxit = new
maxit = property(get_maxit, set_maxit)
def get_state_vec(self):
return self._state_vec.copy()
def set_state_vec(self, x):
if x != None:
tmp = array(x).reshape(self.beads_count, -1)
for i in range(self.beads_count):
# Update mask: 1 update, 0 stay fixed, 2 new bead
if self.bead_update_mask[i] > 0:
self._state_vec[i] = tmp[i]
else:
print >> stderr, "ERROR: setting state vector to NONE, aborting"
exit()
state_vec = property(get_state_vec, set_state_vec)
def taylor(self, state):
## NOTE: this automatically skips if new_state_vec == None
#self.state_vec = new_state_vec
# self.reporting.write("self.prev_state updated")
# self.prev_state = self.state_vec.copy()
# This is now done by the optimizers themselves, as there were
# problems with not knowing which obj_func calls to count and
# which not
# if self.eg_calls >= self.maxit:
# raise pts.MaxIterations
# print "Objective function call: gradient = %s" % grad
# # tests whether this has already been requested
# print "Objective function call: Previously made calcs:", test_previous(self.state_vec)
# print "Objective function call: Bead update mask: ", self.bead_update_mask
# print self.state_vec
if self.bead_eg_calls == 0:
self.bead_eg_calls += self.beads_count
else:
self.bead_eg_calls += self.beads_count - 2
# Note how these arrays are indexed below:
assert len(self.bead_pes_energies) == self.beads_count
assert len(self.bead_pes_gradients) == self.beads_count
# calculation output should go to another place, thus change directory
wopl = getcwd()
if not path.exists(self.output_path):
mkdir(self.output_path)
chdir(self.output_path)
# get PES energy/gradients
es, gs = self.allvals.taylor( state)
# return to former directory
chdir(wopl)
# FIXME: does it need to be a a destructive update?
self.bead_pes_energies[:] = es
self.bead_pes_gradients[:] = gs
return array(es), array(gs)
def obj_func(self):
es, __ = self.taylor(self.state_vec)
self.post_obj_func(False)
return es
def obj_func_grad(self):
__, g_all = self.taylor(self.state_vec)
tangents = self.update_tangents()
#
# NOTE: update_tangents() is not implemented by this class!
# Consult particular subclass.
#
# Also note that at least in NEB the definition
# of the tangent may depend on the relative bead energies.
# Therefore update tangents only after self.bead_pes_energies
# was updated first. Not sure about bead separations though.
#
self.update_bead_separations()
# project gradients in para/perp components:
for i in range(self.beads_count):
# previously computed gradient:
g = g_all[i]
# contravariant tangent coordiantes:
T = tangents[i]
# covariant tangent coordiantes:
t = mt.metric.lower(T, self._state_vec[i])
# components of force parallel and orthogonal to the tangent:
para_force = - dot(T, g) / sqrt(dot(T, t))
perp_force = - g - para_force * t / sqrt(dot(T, t))
self.para_bead_forces[i] = para_force
self.perp_bead_forces[i] = perp_force
self.post_obj_func(True)
return -self.para_bead_forces, -self.perp_bead_forces
def set_positions(self, x):
"""For compatibility with ASE, pretends that there are atoms with cartesian coordinates."""
self.state_vec = x.flatten()[0:self.beads_count * self.dimension]
def get_positions(self):
"""For compatibility with ASE, pretends that there are atoms with cartesian coordinates."""
return common.make_like_atoms(self.state_vec.copy())
positions = property(get_positions, set_positions)
def get_final_bead_ix(self, i):
"""
Based on bead index |i|, returns final index once string is fully
grown.
"""
return i
def record(self):
"""Records snap-shot of chain."""
es = self.bead_pes_energies.copy()
state = self.state_vec.copy()
perp_forces = self.perp_bead_forces.copy()
para_forces = self.para_bead_forces.copy()
# FIXME: wrong place? Yes, do now only after last iteration
#ts_estim = ts_estims(self.state_vec, self.bead_pes_energies, self.bead_pes_gradients)[-1]
a = [es, state, perp_forces, para_forces]
self.history.rec(a)
def ts_estims(beads, energies, gradients, alsomodes = False, converter = None):
"""TODO: Maybe this whole function should be made external."""
pt = pts.tools.PathTools(beads, energies, gradients)
estims = pt.ts_splcub()
#f = open("tsplot.dat", "w")
#f.write(pt.plot_str)
#f.close()
tsisspl = True
if len(estims) < 1:
lg.warn("No transition state found, using highest bead.")
estims = pt.ts_highest()
tsisspl = False
estims.sort()
if alsomodes:
cx = converter
bestmode = []
for est in estims:
energies, coords, s0, s1, s_ts, l, r = est
cx.set_internals(coords)
modes = pt.modeandcurvature(s_ts, l, r, cx)
for mo in modes:
mo_name, value = mo
if tsisspl and mo_name=="frompath":
bestmode.append(value)
if not tsisspl and mo_name=="directinternal":
bestmode.append(value)
return estims, bestmode
return estims
class NEB(ReactionPathway):
"""Implements a Nudged Elastic Band (NEB) transition state searcher.
>>> from numpy import ones
>>> path = [[0,0],[0.2,0.2],[0.7,0.7],[1,1]]
>>> import pts.pes
>>> qc = pts.pes.GaussianPES()
>>> neb = NEB(path, qc, 1.0, None, beads_count = 4, workhere= 0)
>>> neb.state_vec
array([[ 0. , 0. ],
[ 0.2, 0.2],
[ 0.7, 0.7],
[ 1. , 1. ]])
>>> neb.obj_func()
-2.6541709711655024
Was changed because beads are put differently, was before:
>>> neb.obj_func_grad().round(3)
array([ 0. , 0. , -0.291, -0.309, 0.327, 0.073, 0. , 0. ])
>>> neb.step
(0.0, array([ 0., 0., 0., 0.]), array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]]))
>>> neb.state_vec = [[0,0],[0.3,0.3],[0.9,0.9],[1,1]]
>>> neb.obj_func_grad().round(3)
array([ 0. , 0. , -0.282, -0.318, 0.714, 0.286, 0. , 0. ])
>>> neb.step[1].round(1)
array([ 0. , 0.1, 0.2, 0. ])
>>> neb.eg_calls
2
>>> import pts.pes
>>> neb = NEB([[0,0],[3,3]], pts.pes.GaussianPES(), 1., None, beads_count = 10,
... workhere= 0)
>>> neb.angles
array([ 180., 180., 180., 180., 180., 180., 180., 180.])
>>> neb.obj_func()
-4.5571068838569122
Was changed because of different spacing of beads, was before
-4.5561921505021239
>>> neb.update_tangents()
array([[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678],
[ 0.70710678, 0.70710678]])
>>> neb.state_vec += 0.1
>>> abs(neb.step[1] - ones(neb.beads_count) * 0.1).round()
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> import pts.pes
>>> neb = NEB([[0,0],[1,1]], pts.pes.GaussianPES(), 1., None, beads_count = 3,
... workhere= 0)
>>> neb.angles
array([ 180.])
>>> neb.state_vec = [[0,0],[0,1],[1,1]]
>>> neb.obj_func()
-1.6878414761432885
>>> neb.update_tangents()
array([[ 0., 1.],
[ 1., 0.],
[ 1., 0.]])
>>> neb.bead_pes_energies = array([0,1,0])
>>> neb.update_tangents()
array([[ 0. , 1. ],
[ 0.70710678, 0.70710678],
[ 1. , 0. ]])
>>> neb.bead_pes_energies = array([1,0,-1])
>>> neb.update_tangents()
array([[ 0., 1.],
[ 0., 1.],
[ 1., 0.]])
"""
growing = False
def __init__(self, reagents, pes, base_spr_const, result_storage, beads_count=10, pmap = map,
parallel=False, workhere = 1, reporting=None, output_level = 3, output_path = ".",
climb_image = False, start_climb = 5
):
ReactionPathway.__init__(self, reagents, beads_count, pes, parallel, result_storage, pmap = pmap,
reporting=reporting, output_level = output_level, output_path = output_path, workhere = workhere,
climb_image = climb_image, start_climb = start_climb)
self.base_spr_const = base_spr_const
# Make list of spring constants for every inter-bead separation