1 """ @package forcebalance.lipid Matching of lipid bulk properties. Under development. 6 from __future__
import division
7 from __future__
import print_function
9 from builtins
import str
10 from builtins
import zip
11 from builtins
import map
12 from builtins
import range
19 from forcebalance.target
import Target
22 from re
import match, sub
24 from subprocess
import PIPE
26 from lxml
import etree
28 from pymbar
import pymbar
30 from collections
import defaultdict, namedtuple, OrderedDict
34 from forcebalance.output
import getLogger
35 logger = getLogger(__name__)
41 I = np.exp(-1*np.sum((W*np.log(W))))
43 C.append(sum(W[N:N+ns]))
47 logger.info(
"MBAR Results for Phase Point %s, Box, Contributions:\n" % str(PT))
48 logger.info(str(C) +
'\n')
49 logger.info(
"InfoContent: % .2f snapshots (%.2f %%)\n" % (I, 100*I/len(W)))
56 """ Subclass of Target for lipid property matching.""" 58 def __init__(self,options,tgt_opts,forcefield):
60 super(Lipid,self).
__init__(options,tgt_opts,forcefield)
62 self.set_option(tgt_opts,
'w_rho',forceprint=
True)
64 self.set_option(tgt_opts,
'w_alpha',forceprint=
True)
66 self.set_option(tgt_opts,
'w_kappa',forceprint=
True)
68 self.set_option(tgt_opts,
'w_cp',forceprint=
True)
70 self.set_option(tgt_opts,
'w_eps0',forceprint=
True)
72 self.set_option(tgt_opts,
'w_al',forceprint=
True)
74 self.set_option(tgt_opts,
'w_lkappa',forceprint=
True)
76 self.set_option(tgt_opts,
'w_scd',forceprint=
True)
78 self.set_option(tgt_opts,
'w_normalize',forceprint=
True)
80 self.set_option(tgt_opts,
'manual')
82 self.set_option(tgt_opts,
'lipid_eq_steps',forceprint=
True)
84 self.set_option(tgt_opts,
'lipid_md_steps',forceprint=
True)
86 self.set_option(tgt_opts,
'gas_eq_steps',forceprint=
False)
88 self.set_option(tgt_opts,
'gas_md_steps',forceprint=
False)
90 if tgt_opts[
'nonbonded_cutoff']
is not None:
91 self.set_option(tgt_opts,
'nonbonded_cutoff')
93 if tgt_opts[
'vdw_cutoff']
is not None:
94 self.set_option(tgt_opts,
'vdw_cutoff')
96 self.set_option(tgt_opts,
'lipid_timestep',forceprint=
True)
98 self.set_option(tgt_opts,
'lipid_interval',forceprint=
True)
100 self.set_option(tgt_opts,
'gas_timestep',forceprint=
True)
102 self.set_option(tgt_opts,
'gas_interval',forceprint=
True)
104 self.set_option(tgt_opts,
'minimize_energy',forceprint=
True)
106 self.set_option(tgt_opts,
'self_pol_mu0',forceprint=
True)
108 self.set_option(tgt_opts,
'self_pol_alpha',forceprint=
True)
110 self.
do_self_pol = (self.self_pol_mu0 > 0.0
and self.self_pol_alpha > 0.0)
112 self.set_option(tgt_opts,
'anisotropic_box',forceprint=
True)
114 self.set_option(tgt_opts,
'save_traj')
131 self.nptfiles += [
"IC"]
136 pt_label =
"IC/%sK-%s%s" % (pt[0], pt[1], pt[2])
137 if not os.path.exists(os.path.join(self.root, self.tgtdir, pt_label, self.lipid_coords)):
138 raise RuntimeError(
"Initial condition files don't exist; please provide IC directory")
140 all_ic = Molecule(os.path.join(self.root, self.tgtdir, pt_label, self.lipid_coords))
142 n_uniq_ic = int(self.
RefData[
'n_ic'][pt])
143 if n_uniq_ic > len(all_ic):
144 raise RuntimeError(
"Number of frames in initial conditions .gro file is less than the number of parallel simulations requested in data.csv")
146 for ic
in range(n_uniq_ic):
150 if not os.path.exists(os.path.join(self.root, self.tgtdir, self.lipid_coords)):
151 logger.error(
"%s doesn't exist; please provide lipid_coords option\n" % self.lipid_coords)
153 self.
lipid_mol = Molecule(os.path.join(self.root, self.tgtdir, self.lipid_coords), toppbc=
True)
155 self.nptfiles += [self.lipid_coords]
157 self.scripts += [
'npt_lipid.py']
162 self.gas_engine_args.update(self.OptionDict)
163 self.gas_engine_args.update(options)
164 del self.gas_engine_args[
'name']
166 self.
gas_engine = self.engine_(target=self, mol=self.gas_mol, name=
"selfpol", **self.gas_engine_args)
176 np.set_printoptions(precision=4, linewidth=100)
177 np.seterr(under=
'ignore')
186 """ Prepare the temporary directory by copying in important files. """ 187 abstempdir = os.path.join(self.root,self.tempdir)
188 for f
in self.nptfiles:
189 LinkFile(os.path.join(self.root, self.tgtdir, f), os.path.join(abstempdir, f))
190 for f
in self.scripts:
191 LinkFile(os.path.join(os.path.split(__file__)[0],
"data",f),os.path.join(abstempdir,f))
195 with open(os.path.join(self.tgtdir,
'data.csv'),
'rU')
as f: R0 = list(csv.reader(f))
197 R1 = [[sub(
'#.*$',
'',word)
for word
in line]
for line
in R0
if len(line[0]) > 0
and line[0][0] !=
"#"]
199 R = [[wrd.lower()
for wrd
in line]
for line
in R1
if any([len(wrd)
for wrd
in line]) > 0]
200 global_opts = OrderedDict()
201 found_headings =
False 202 known_vars = [
'mbar',
'rho',
'hvap',
'alpha',
'kappa',
'cp',
'eps0',
'cvib_intra',
203 'cvib_inter',
'cni',
'devib_intra',
'devib_inter',
'al',
'scd',
'n_ic',
'lkappa']
206 if line[0] ==
"global":
209 global_opts[line[1]] = float(line[2])
210 elif line[2].lower() ==
'false':
211 global_opts[line[1]] =
False 212 elif line[2].lower() ==
'true':
213 global_opts[line[1]] =
True 214 elif not found_headings:
215 found_headings =
True 217 if len(set(headings)) != len(headings):
218 logger.error(
'Column headings in data.csv must be unique\n')
220 if 'p' not in headings:
221 logger.error(
'There must be a pressure column heading labeled by "p" in data.csv\n')
223 if 't' not in headings:
224 logger.error(
'There must be a temperature column heading labeled by "t" in data.csv\n')
229 t = [float(val)
for head, val
in zip(headings,line)
if head ==
't'][0]
231 pval = [float(val.split()[0])
for head, val
in zip(headings,line)
if head ==
'p'][0]
232 punit = [val.split()[1]
if len(val.split()) >= 1
else "atm" for head, val
in zip(headings,line)
if head ==
'p'][0]
233 unrec = set([punit]).difference([
'atm',
'bar'])
235 logger.error(
'The pressure unit %s is not recognized, please use bar or atm\n' % unrec[0])
238 for head, val
in zip(headings,line):
239 if head ==
't' or head ==
'p' :
continue 241 self.
RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = float(val.strip())
242 elif val.lower() ==
'true':
243 self.
RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] =
True 244 elif val.lower() ==
'false':
245 self.
RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] =
False 247 self.
RefData.setdefault(head,OrderedDict([]))[(t,pval,punit)] = np.array(list(map(float, val.split())))
249 logger.error(line +
'\n')
250 logger.error(
'Encountered an error reading this line!\n')
253 logger.error(line +
'\n')
254 logger.error(
'I did not recognize this line!\n')
257 default_denoms = defaultdict(int)
259 RefData_copy = copy.deepcopy(self.
RefData)
263 if head
not in known_vars+[i+
"_wt" for i
in known_vars]:
265 logger.error(
"The column heading %s is not recognized in data.csv\n" % head)
267 if head
in known_vars:
268 if head+
"_wt" not in self.
RefData:
270 RefData_copy[head+
"_wt"] = OrderedDict([(key, 1.0)
for key
in self.
RefData[head]])
271 wts = np.array(list(RefData_copy[head+
"_wt"].values()))
272 dat = np.array(list(self.
RefData[head].values()))
274 avg = np.average(dat, weights=wts, axis=0)
279 default_denoms[head+
"_denom"] = np.average(np.sqrt(np.dot(wts, (dat-avg)**2)/wts.sum()))
281 default_denoms[head+
"_denom"] = np.sqrt(np.dot(wts, (dat-avg)**2)/wts.sum())
286 default_denoms[head+
"_denom"] = np.average(np.sqrt(np.abs(dat[0])))
288 default_denoms[head+
"_denom"] = np.sqrt(np.abs(dat[0]))
295 logger.debug(
"global_opts:\n%s\n" % str(global_opts))
296 logger.debug(
"default_denoms:\n%s\n" % str(default_denoms))
297 for opt
in global_opts:
300 self.set_option(global_opts,opt,default=default_denoms[opt])
302 self.set_option(global_opts,opt)
305 there = os.path.abspath(there)
308 for d
in os.listdir(there):
310 if os.path.exists(os.path.join(there, d,
'npt_result.p')):
312 if (float(havepts)/len(self.
Labels)) > 0.75:
317 """ Submit a NPT simulation to the Work Queue. """ 319 if not os.path.exists(
'npt_result.p'):
322 self.
lipid_mol[simnum%len(self.
lipid_mol)].write(self.lipid_coords, ftype=
'tinker' if self.
engname ==
'tinker' else None)
323 cmdstr =
'%s python npt_lipid.py %s %.3f %.3f' % (self.nptpfx, self.
engname, temperature, pressure)
325 logger.info(
"Running condensed phase simulation locally.\n")
326 logger.info(
"You may tail -f %s/npt.out in another terminal window\n" % os.getcwd())
327 _exec(cmdstr, copy_stderr=
True, outfnm=
'npt.out')
329 queue_up(wq, command = cmdstr+
' &> npt.out',
330 input_files = self.nptfiles + self.scripts + [
'forcebalance.p'],
331 output_files = [
'npt_result.p',
'npt.out'] + self.
extra_output, tgt=self)
334 d = self.
gas_engine.get_multipole_moments(optimize=
True)[
'dipole']
336 logger.info(
"The molecular dipole moment is % .3f debye\n" % np.linalg.norm(d))
344 convert = 60.240179789402056
345 dd2 = (np.linalg.norm(d)-self.self_pol_mu0)**2
346 epol = 0.5*convert*dd2/self.self_pol_alpha
350 AGrad = hasattr(self,
'Gp')
351 PrintDict = OrderedDict()
352 def print_item(key, heading, physunit):
354 printcool_dictionary(self.
Pp[key], title=
'%s %s%s\nTemperature Pressure Reference Calculated +- Stdev Delta Weight Term ' %
355 (self.name, heading,
" (%s) " % physunit
if physunit
else ""), bold=
True, color=4, keywidth=15)
356 bar =
printcool(
"%s objective function: % .3f%s" % (heading, self.
Xp[key],
", Derivative:" if AGrad
else ""))
358 self.FF.print_map(vals=self.
Gp[key])
360 PrintDict[heading] =
"% 10.5f % 8.3f % 14.5e" % (self.
Xp[key], self.
Wp[key], self.
Xp[key]*self.
Wp[key])
362 print_item(
"Rho",
"Density",
"kg m^-3")
363 print_item(
"Alpha",
"Thermal Expansion Coefficient",
"10^-4 K^-1")
364 print_item(
"Kappa",
"Isothermal Compressibility",
"10^-6 bar^-1")
365 print_item(
"Cp",
"Isobaric Heat Capacity",
"cal mol^-1 K^-1")
366 print_item(
"Eps0",
"Dielectric Constant",
None)
367 print_item(
"Al",
"Average Area per Lipid",
"nm^2")
368 print_item(
"Scd",
"Deuterium Order Parameter",
None)
369 print_item(
"LKappa",
"Bilayer Isothermal Compressibility",
"mN/m")
371 PrintDict[
'Total'] =
"% 10s % 8s % 14.5e" % (
"",
"",self.
Objective)
373 Title =
"%s Condensed Phase Properties:\n %-20s %40s" % (self.name,
"Property Name",
"Residual x Weight = Contribution")
377 def objective_term(self, points, expname, calc, err, grad, name="Quantity", SubAverage=False):
380 Weights = self.
RefData[expname+
"_wt"]
381 Denom = getattr(self,expname+
"_denom")
384 return 0.0, np.zeros(self.FF.np), np.zeros((self.FF.np,self.FF.np)),
None 386 Sum = sum(Weights.values())
389 logger.info(
"Weights have been renormalized to " + str(sum(Weights.values())) +
"\n")
393 logger.info(
"Physical quantity %s uses denominator = % .4f\n" % (name, Denom))
402 Gradient = np.zeros(self.FF.np)
403 Hessian = np.zeros((self.FF.np,self.FF.np))
408 avgGrad = np.zeros(self.FF.np)
409 for i, PT
in enumerate(points):
410 avgCalc += Weights[PT]*calc[PT]
411 avgExp += Weights[PT]*exp[PT]
412 avgGrad += Weights[PT]*grad[PT]
413 for i, PT
in enumerate(points):
416 Delta = calc[PT] - exp[PT] - avgCalc + avgExp
419 Delta = calc[PT] - exp[PT]
420 if hasattr(Delta,
"__len__"):
421 Delta = np.average(Delta)
424 ThisObj = Weights[PT] * Delta ** 2 / Denom**2
426 ThisGrad = 2.0 * Weights[PT] * Delta * G / Denom**2
431 Hessian += 2.0 * Weights[PT] * (np.outer(G, G)) / Denom**2
436 ThisObj = Weights[PT] * (S**0.5-D) / Denom
437 ThisGrad = Weights[PT] * (Delta/S**0.5) * G / Denom
438 ThisHess = Weights[PT] * (1/S**0.5-Delta**2/S**1.5) * np.outer(G,G) / Denom
444 GradMapPrint = [[
"#PhasePoint"] + self.FF.plist]
445 for PT, g
in zip(points,GradMap):
446 GradMapPrint.append([
' %8.2f %8.1f %3s' % PT] + [
"% 9.3e" % i
for i
in g])
447 o =
wopen(
'gradient_%s.dat' % name)
448 for line
in GradMapPrint:
449 print(
' '.join(line), file=o)
452 Delta = np.array([calc[PT] - exp[PT]
for PT
in points])
453 delt = {PT : r
for PT, r
in zip(points,Delta)}
455 print_out = OrderedDict([(
' %8.2f %8.1f %3s' % PT,
'\n %s' % (
' '.join(
'\t \t \t %9.6f %9.6f +- %-7.6f % 7.6f \n' % F
for F
in zip(exp[PT], calc[PT],
flat(err[PT]), delt[PT]))))
for PT
in calc])
457 print_out = OrderedDict([(
' %8.2f %8.1f %3s' % PT,
"%9.3f %9.3f +- %-7.3f % 7.3f % 9.5f % 9.5f" % (exp[PT],calc[PT],err[PT],delt[PT],Weights[PT],Objs[PT]))
for PT
in calc])
459 return Objective, Gradient, Hessian, print_out
461 def submit_jobs(self, mvals, AGrad=True, AHess=True):
466 lp_dump((self.FF,mvals,self.OptionDict,AGrad),
'forcebalance.p')
469 if (
not self.evaluated)
and self.manual:
470 warn_press_key(
"Now's our chance to fill the temp directory up with data!\n(Considering using 'read' or 'continue' for better checkpointing)", timeout=7200)
473 if self.evaluated
and self.goodstep
and self.save_traj < 2:
475 if os.path.exists(fn):
487 if not os.path.exists(label):
491 n_uniq_ic = int(self.
RefData[
'n_ic'][pt])
493 for trj
in range(n_uniq_ic):
494 rel_trj =
"trj_%i" % trj
496 if not os.path.exists(rel_trj):
505 if not self.lipid_coords
in self.nptfiles:
506 self.nptfiles += [self.lipid_coords]
514 def get(self, mvals, AGrad=True, AHess=True):
517 Fitting of lipid bulk properties. This is the current major 518 direction of development for ForceBalance. Basically, fitting 519 the QM energies / forces alone does not always give us the 520 best simulation behavior. In many cases it makes more sense 521 to try and reproduce some experimentally known data as well. 523 In order to reproduce experimentally known data, we need to 524 run a simulation and compare the simulation result to 525 experiment. The main challenge here is that the simulations 526 are computationally intensive (i.e. they require energy and 527 force evaluations), and furthermore the results are noisy. We 528 need to run the simulations automatically and remotely 529 (i.e. on clusters) and a good way to calculate the derivatives 530 of the simulation results with respect to the parameter values. 532 This function contains some experimentally known values of the 533 density and enthalpy of vaporization (Hvap) of lipid water. 534 It launches the density and Hvap calculations on the cluster, 535 and gathers the results / derivatives. The actual calculation 536 of results / derivatives is done in a separate file. 538 After the results come back, they are gathered together to form 539 an objective function. 541 @param[in] mvals Mathematical parameter values 542 @param[in] AGrad Switch to turn on analytic gradient 543 @param[in] AHess Switch to turn on analytic Hessian 544 @return Answer Contribution to the objective function 559 n_uniq_ic = int(self.
RefData[
'n_ic'][PT])
560 for ic
in range(n_uniq_ic):
561 if os.path.exists(
'./%s/trj_%s/npt_result.p' % (label, ic)):
563 ts =
lp_load(
'./%s/trj_%s/npt_result.p' % (label, ic))
567 for d_arr
in range(len(ts)):
568 if isinstance(ts[d_arr], np.ndarray):
571 ts_concat[d_arr] = np.append(ts_concat[d_arr], ts[d_arr], axis = 1)
573 ts_concat[d_arr] = np.append(ts_concat[d_arr], ts[d_arr], axis = 0)
574 if isinstance(ts_concat[d_arr], list):
575 ts_concat[d_arr] = [np.append(ts_concat[d_arr][i], ts[d_arr][i], axis = 1)
for i
in range(len(ts_concat[d_arr]))]
577 if ic == (int(n_uniq_ic) - 1):
578 lp_dump((ts_concat),
'./%s/npt_result.p' % label)
579 if os.path.exists(
'./%s/npt_result.p' % label):
580 logger.info(
'Reading information from ./%s/npt_result.p\n' % label)
582 Results[tt] =
lp_load(
'./%s/npt_result.p' % label)
585 logger.warning(
'The file ./%s/npt_result.p does not exist so we cannot read it\n' % label)
590 logger.error(
'The lipid simulations have terminated with \x1b[1;91mno readable data\x1b[0m - this is a problem!\n')
594 Rhos, Vols, Potentials, Energies, Dips, Grads, GDips, \
595 Rho_errs, Alpha_errs, Kappa_errs, Cp_errs, Eps0_errs, NMols, Als, Al_errs, Scds, Scd_errs, LKappa_errs = ([Results[t][i]
for t
in range(len(Points))]
for i
in range(18))
597 if len(set(NMols)) != 1:
598 logger.error(str(NMols))
599 logger.error(
'The above list should only contain one number - the number of molecules\n')
602 NMol = list(set(NMols))[0]
604 R = np.array(list(itertools.chain(*list(Rhos))))
605 V = np.array(list(itertools.chain(*list(Vols))))
606 E = np.array(list(itertools.chain(*list(Energies))))
607 Dx = np.array(list(itertools.chain(*list(d[:,0]
for d
in Dips))))
608 Dy = np.array(list(itertools.chain(*list(d[:,1]
for d
in Dips))))
609 Dz = np.array(list(itertools.chain(*list(d[:,2]
for d
in Dips))))
610 G = np.hstack(tuple(Grads))
611 GDx = np.hstack(tuple(gd[0]
for gd
in GDips))
612 GDy = np.hstack(tuple(gd[1]
for gd
in GDips))
613 GDz = np.hstack(tuple(gd[2]
for gd
in GDips))
614 A = np.array(list(itertools.chain(*list(Als))))
615 S = np.array(list(itertools.chain(*list(Scds))))
617 Rho_calc = OrderedDict([])
618 Rho_grad = OrderedDict([])
619 Rho_std = OrderedDict([])
620 Alpha_calc = OrderedDict([])
621 Alpha_grad = OrderedDict([])
622 Alpha_std = OrderedDict([])
623 Kappa_calc = OrderedDict([])
624 Kappa_grad = OrderedDict([])
625 Kappa_std = OrderedDict([])
626 Cp_calc = OrderedDict([])
627 Cp_grad = OrderedDict([])
628 Cp_std = OrderedDict([])
629 Eps0_calc = OrderedDict([])
630 Eps0_grad = OrderedDict([])
631 Eps0_std = OrderedDict([])
632 Al_calc = OrderedDict([])
633 Al_grad = OrderedDict([])
634 Al_std = OrderedDict([])
635 LKappa_calc = OrderedDict([])
636 LKappa_grad = OrderedDict([])
637 LKappa_std = OrderedDict([])
638 Scd_calc = OrderedDict([])
639 Scd_grad = OrderedDict([])
640 Scd_std = OrderedDict([])
643 pvkj=0.061019351687175
647 Shots = len(Energies[0])
648 Shots_m = [len(i)
for i
in Energies]
649 N_k = np.ones(BSims)*Shots
651 U_kln = np.zeros([BSims,BSims,Shots])
652 for m, PT
in enumerate(BPoints):
654 P = PT[1] / 1.01325
if PT[2] ==
'bar' else PT[1]
656 for k
in range(BSims):
660 kk = Points.index(BPoints[k])
661 U_kln[k, m, :] = Energies[kk] + P*Vols[kk]*pvkj
662 U_kln[k, m, :] *= beta
665 logger.info(
"Running MBAR analysis on %i states...\n" % len(BPoints))
666 mbar = pymbar.MBAR(U_kln, N_k, verbose=mbar_verbose, relative_tolerance=5.0e-8)
667 W1 = mbar.getWeights()
668 logger.info(
"Done\n")
669 elif len(BPoints) == 1:
670 W1 = np.ones((BPoints*Shots,BPoints))
673 def fill_weights(weights, phase_points, mbar_points, snapshots):
674 """ Fill in the weight matrix with MBAR weights where MBAR was run, 675 and equal weights otherwise. """ 676 new_weights = np.zeros([len(phase_points)*snapshots,len(phase_points)])
677 for m, PT
in enumerate(phase_points):
678 if PT
in mbar_points:
679 mm = mbar_points.index(PT)
680 for kk, PT1
in enumerate(mbar_points):
681 k = phase_points.index(PT1)
682 logger.debug(
"Will fill W2[%i:%i,%i] with W1[%i:%i,%i]\n" % (k*snapshots,k*snapshots+snapshots,m,kk*snapshots,kk*snapshots+snapshots,mm))
683 new_weights[k*snapshots:(k+1)*snapshots,m] = weights[kk*snapshots:(kk+1)*snapshots,mm]
685 logger.debug(
"Will fill W2[%i:%i,%i] with equal weights\n" % (m*snapshots,(m+1)*snapshots,m))
686 new_weights[m*snapshots:(m+1)*snapshots,m] = 1.0/snapshots
689 W2 = fill_weights(W1, Points, BPoints, Shots)
694 bar =
printcool(
"Self-polarization correction to \nenthalpy of vaporization is % .3f kJ/mol%s" % (EPol,
", Derivative:" if AGrad
else ""))
696 self.FF.print_map(vals=GEPol)
699 for i, PT
in enumerate(Points):
701 P = PT[1] / 1.01325
if PT[2] ==
'bar' else PT[1]
706 C =
weight_info(W, PT, np.ones(len(Points), dtype=int)*Shots, verbose=mbar_verbose)
715 return flat(np.dot(G,
col(W*vec))) - avg(vec)*Gbar
717 return flat(np.dot(G,
col(W*vec)))
719 Rho_calc[PT] = np.dot(W,R)
720 Rho_grad[PT] = mBeta*(
flat(np.dot(G,
col(W*R))) - np.dot(W,R)*Gbar)
723 Alpha_calc[PT] = 1e4 * (avg(H*V)-avg(H)*avg(V))/avg(V)/(kT*T)
724 GAlpha1 = -1 * Beta * deprod(H*V) * avg(V) / avg(V)**2
725 GAlpha2 = +1 * Beta * avg(H*V) * deprod(V) / avg(V)**2
726 GAlpha3 = deprod(V)/avg(V) - Gbar
727 GAlpha4 = Beta * covde(H)
728 Alpha_grad[PT] = 1e4 * (GAlpha1 + GAlpha2 + GAlpha3 + GAlpha4)/(kT*T)
730 bar_unit = 0.06022141793 * 1e6
731 Kappa_calc[PT] = bar_unit / kT * (avg(V**2)-avg(V)**2)/avg(V)
732 GKappa1 = +1 * Beta**2 * avg(V**2) * deprod(V) / avg(V)**2
733 GKappa2 = -1 * Beta**2 * avg(V) * deprod(V**2) / avg(V)**2
734 GKappa3 = +1 * Beta**2 * covde(V)
735 Kappa_grad[PT] = bar_unit*(GKappa1 + GKappa2 + GKappa3)
737 Cp_calc[PT] = 1000/(4.184*NMol*kT*T) * (avg(H**2) - avg(H)**2)
738 if hasattr(self,
'use_cvib_intra')
and self.use_cvib_intra:
739 logger.debug(
"Adding " + str(self.
RefData[
'devib_intra'][PT]) +
" to the heat capacity\n")
740 Cp_calc[PT] += self.
RefData[
'devib_intra'][PT]
741 if hasattr(self,
'use_cvib_inter')
and self.use_cvib_inter:
742 logger.debug(
"Adding " + str(self.
RefData[
'devib_inter'][PT]) +
" to the heat capacity\n")
743 Cp_calc[PT] += self.
RefData[
'devib_inter'][PT]
744 GCp1 = 2*covde(H) * 1000 / 4.184 / (NMol*kT*T)
745 GCp2 = mBeta*covde(H**2) * 1000 / 4.184 / (NMol*kT*T)
746 GCp3 = 2*Beta*avg(H)*covde(H) * 1000 / 4.184 / (NMol*kT*T)
747 Cp_grad[PT] = GCp1 + GCp2 + GCp3
749 prefactor = 30.348705333964077
750 D2 = avg(Dx**2)+avg(Dy**2)+avg(Dz**2)-avg(Dx)**2-avg(Dy)**2-avg(Dz)**2
751 Eps0_calc[PT] = 1.0 + prefactor*(D2/avg(V))/T
752 GD2 = 2*(
flat(np.dot(GDx,
col(W*Dx))) - avg(Dx)*
flat(np.dot(GDx,
col(W)))) - Beta*(covde(Dx**2) - 2*avg(Dx)*covde(Dx))
753 GD2 += 2*(
flat(np.dot(GDy,
col(W*Dy))) - avg(Dy)*
flat(np.dot(GDy,
col(W)))) - Beta*(covde(Dy**2) - 2*avg(Dy)*covde(Dy))
754 GD2 += 2*(
flat(np.dot(GDz,
col(W*Dz))) - avg(Dz)*
flat(np.dot(GDz,
col(W)))) - Beta*(covde(Dz**2) - 2*avg(Dz)*covde(Dz))
755 Eps0_grad[PT] = prefactor*(GD2/avg(V) - mBeta*covde(V)*D2/avg(V)**2)/T
757 Al_calc[PT] = np.dot(W,A)
758 Al_grad[PT] = mBeta*(
flat(np.dot(G,
col(W*A))) - np.dot(W,A)*Gbar)
761 kbT = 1.3806488e-23 * T
762 LKappa_calc[PT] = (1e3 * 2 * kbT / 128) * (avg(A_m2) / (avg(A_m2**2)-avg(A_m2)**2))
764 al_sq_avg = avg(A_m2**2)
765 al_avg_sq = al_avg**2
766 al_var = al_sq_avg - al_avg_sq
767 GLKappa1 = covde(A_m2) / al_var
768 GLKappa2 = (al_avg / al_var**2) * (covde(A_m2**2) - (2 * al_avg * covde(A)))
769 LKappa_grad[PT] = (1e3 * 2 * kbT / 128) * (GLKappa1 - GLKappa2)
771 Scd_calc[PT] = np.dot(W,S)
774 Scd_grad[PT] = mBeta * (
flat(np.average(np.dot(G, (S * W[:, np.newaxis])), axis = 1)) - np.average(np.average(S * W[:, np.newaxis], axis = 0), axis = 0) * Gbar)
776 Rho_std[PT] = np.sqrt(sum(C**2 * np.array(Rho_errs)**2))
777 Alpha_std[PT] = np.sqrt(sum(C**2 * np.array(Alpha_errs)**2)) * 1e4
778 Kappa_std[PT] = np.sqrt(sum(C**2 * np.array(Kappa_errs)**2)) * 1e6
779 Cp_std[PT] = np.sqrt(sum(C**2 * np.array(Cp_errs)**2))
780 Eps0_std[PT] = np.sqrt(sum(C**2 * np.array(Eps0_errs)**2))
781 Al_std[PT] = np.sqrt(sum(C**2 * np.array(Al_errs)**2))
784 Scd_std[PT] = np.sqrt(sum(np.dot(
row(C**2), np.array(Scd_errs)**2)))
785 LKappa_std[PT] = np.sqrt(sum(C**2 * np.array(LKappa_errs)**2)) * 1e6
788 X_Rho, G_Rho, H_Rho, RhoPrint = self.
objective_term(Points,
'rho', Rho_calc, Rho_std, Rho_grad, name=
"Density")
789 X_Alpha, G_Alpha, H_Alpha, AlphaPrint = self.
objective_term(Points,
'alpha', Alpha_calc, Alpha_std, Alpha_grad, name=
"Thermal Expansion")
790 X_Kappa, G_Kappa, H_Kappa, KappaPrint = self.
objective_term(Points,
'kappa', Kappa_calc, Kappa_std, Kappa_grad, name=
"Compressibility")
791 X_Cp, G_Cp, H_Cp, CpPrint = self.
objective_term(Points,
'cp', Cp_calc, Cp_std, Cp_grad, name=
"Heat Capacity")
792 X_Eps0, G_Eps0, H_Eps0, Eps0Print = self.
objective_term(Points,
'eps0', Eps0_calc, Eps0_std, Eps0_grad, name=
"Dielectric Constant")
793 X_Al, G_Al, H_Al, AlPrint = self.
objective_term(Points,
'al', Al_calc, Al_std, Al_grad, name=
"Avg Area per Lipid")
794 X_Scd, G_Scd, H_Scd, ScdPrint = self.
objective_term(Points,
'scd', Scd_calc, Scd_std, Scd_grad, name=
"Deuterium Order Parameter")
795 X_LKappa, G_LKappa, H_LKappa, LKappaPrint = self.
objective_term(Points,
'lkappa', LKappa_calc, LKappa_std, LKappa_grad, name=
"Bilayer Compressibility")
797 Gradient = np.zeros(self.FF.np)
798 Hessian = np.zeros((self.FF.np,self.FF.np))
800 if X_Rho == 0: self.
w_rho = 0.0
801 if X_Alpha == 0: self.
w_alpha = 0.0
802 if X_Kappa == 0: self.
w_kappa = 0.0
813 w_1 = self.
w_rho / w_tot
816 w_5 = self.
w_cp / w_tot
818 w_7 = self.
w_al / w_tot
819 w_8 = self.
w_scd / w_tot
822 Objective = w_1 * X_Rho + w_3 * X_Alpha + w_4 * X_Kappa + w_5 * X_Cp + w_6 * X_Eps0 + w_7 * X_Al + w_8 * X_Scd + w_9 * X_LKappa
824 Gradient = w_1 * G_Rho + w_3 * G_Alpha + w_4 * G_Kappa + w_5 * G_Cp + w_6 * G_Eps0 + w_7 * G_Al + w_8 * G_Scd + w_9 * G_LKappa
826 Hessian = w_1 * H_Rho + w_3 * H_Alpha + w_4 * H_Kappa + w_5 * H_Cp + w_6 * H_Eps0 + w_7 * H_Al + w_8 * H_Scd + w_9 * H_LKappa
829 self.
Xp = {
"Rho" : X_Rho,
"Alpha" : X_Alpha,
830 "Kappa" : X_Kappa,
"Cp" : X_Cp,
"Eps0" : X_Eps0,
"Al" : X_Al,
"Scd" : X_Scd,
"LKappa" : X_LKappa}
831 self.
Wp = {
"Rho" : w_1,
"Alpha" : w_3,
832 "Kappa" : w_4,
"Cp" : w_5,
"Eps0" : w_6,
"Al" : w_7,
"Scd" : w_8,
"LKappa" : w_9}
833 self.
Pp = {
"Rho" : RhoPrint,
"Alpha" : AlphaPrint,
834 "Kappa" : KappaPrint,
"Cp" : CpPrint,
"Eps0" : Eps0Print,
"Al" : AlPrint,
"Scd" : ScdPrint,
"LKappa": LKappaPrint}
836 self.
Gp = {
"Rho" : G_Rho,
"Alpha" : G_Alpha,
837 "Kappa" : G_Kappa,
"Cp" : G_Cp,
"Eps0" : G_Eps0,
"Al" : G_Al,
"Scd" : G_Scd,
"LKappa" : G_LKappa}
840 Answer = {
'X':Objective,
'G':Gradient,
'H':Hessian}
def npt_simulation(self, temperature, pressure, simnum)
Submit a NPT simulation to the Work Queue.
def check_files(self, there)
def lp_load(fnm)
Read an object from a bzipped file specified by the path.
Nifty functions, intended to be imported by any module within ForceBalance.
MBarEnergy
Evaluated energies for all trajectories (i.e.
loop_over_snapshots
LPW 2018-02-11: This is set to True if the target calculates a single-point property over several exi...
def LinkFile(src, dest, nosrcok=False)
def objective_term(self, points, expname, calc, err, grad, name="Quantity", SubAverage=False)
def flat(vec)
Given any list, array, or matrix, return a single-index array.
def in_fd()
Invoking this function from anywhere will tell us whether we're being called by a finite-difference f...
def submit_jobs(self, mvals, AGrad=True, AHess=True)
def fdwrap(func, mvals0, pidx, key=None, kwargs)
A function wrapper for finite difference designed for differentiating 'get'-type functions.
def queue_up(wq, command, input_files, output_files, tag=None, tgt=None, verbose=True, print_time=60)
Submit a job to the Work Queue.
def lp_dump(obj, fnm, protocol=0)
Write an object to a zipped pickle file specified by the path.
def col(vec)
Given any list, array, or matrix, return a 1-column 2D array.
def link_dir_contents(abssrcdir, absdestdir)
def get(self, mvals, AGrad=True, AHess=True)
Fitting of lipid bulk properties.
def warn_press_key(warning, timeout=10)
def printcool_dictionary(Dict, title="Dictionary Keys : Values", bold=False, color=2, keywidth=25, topwidth=50, center=True, leftpad=0)
See documentation for printcool; this is a nice way to print out keys/values in a dictionary...
def polarization_correction(self, mvals)
def printcool(text, sym="#", bold=False, color=2, ansi=None, bottom='-', minwidth=50, center=True, sym2="=")
Cool-looking printout for slick formatting of output.
SavedTraj
Saved trajectories for all iterations and all temperatures.
def weight_info(W, PT, N_k, verbose=True)
SavedMVal
Saved force field mvals for all iterations.
def prepare_temp_directory(self)
Prepare the temporary directory by copying in important files.
def __init__(self, options, tgt_opts, forcefield)
Subclass of Target for lipid property matching.
def f12d3p(f, h, f0=None)
A three-point finite difference stencil.
def isfloat(word)
Matches ANY number; it can be a decimal, scientific notation, integer, or what have you...
def wopen(dest, binary=False)
If trying to write to a symbolic link, remove it first.
def row(vec)
Given any list, array, or matrix, return a 1-row 2D array.